0

I want to make my code loop with an else statement. Is there a way to make it loop infinitely?

import random

a = random.randint (1,6)
b = random.randint (1,6)
c = random.randint (1,6)
sum = a+b
sum2 = a+b+c

jah = input ("How Many Dice Do You Want To Roll? 1, 2, Or 3? ")

if jah == "1": 
    print ("You Rolled A",a,)
elif jah == "2": 
    print ("You Rolled A",a,", And A",b,". In Total, You Got A", sum)
elif jah == '3':
    print ("You Got,",a,',',b,", And",c,". In Total, You Got A,",sum2)  
else: 
    print("Please Roll Again.")
    input("How Many Dice Do You Want To Roll? 1, 2, Or 3? ")
Olvin Roght
  • 7,677
  • 2
  • 16
  • 35
  • Yes, you put your if.elif.else inside a loop. while True, for example. – mauve Oct 14 '19 at 20:23
  • Possible duplicate of [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – quamrana Oct 14 '19 at 20:28

2 Answers2

0

Use a while loop:


a = random.randint (1,6)
b = random.randint (1,6)
c = random.randint (1,6)
sum = a+b
sum2 = a+b+c

jah = input ("How Many Dice Do You Want To Roll? 1, 2, Or 3? ")

while jah not in ["1", "2", "3"]:
  print("Please Roll Again.")
  jah = input("How Many Dice Do You Want To Roll? 1, 2, Or 3? ")

if jah == "1": 
  print ("You Rolled A",a,)
elif jah == "2": 
  print ("You Rolled A",a,", And A",b,". In Total, You Got A", sum)
elif jah == '3':
  print ("You Got,",a,',',b,", And",c,". In Total, You Got A,",sum2)  ```
jumelet
  • 313
  • 2
  • 9
0

A Different Approach

You can also write a function to roll your dice, and have that function call itself when the next dice should be rolled. It's called a recursive function.

Like this:

import random

a = random.randint (1,6)
b = random.randint (1,6)
c = random.randint (1,6)
sum1 = a+b
sum2 = a+b+c

def roll():
    """Roll the dice."""
    jah = input ("How Many Dice Do You Want To Roll? 1, 2, Or 3? ")

    if jah == "1":
        print ("You Rolled A",a,)
    elif jah == "2": 
        print ("You Rolled A",a,", And A",b,". In Total, You Got A", sum1)
    elif jah == '3':
        print ("You Got,",a,',',b,", And",c,". In Total, You Got A,",sum2)  
    else:
        print("Please Roll Again.")
    # Recursion.  Call the function to roll again.
    roll()

# Let the games begin!
roll()

Best Practice Edit

I made a simple edit to your code by renaming your sum variable to sum1; otherwise you are renaming a built-in function. Categorically a very bad idea.

S3DEV
  • 8,768
  • 3
  • 31
  • 42