Reputation: 29
I have made this code for a project and i have run into a problem with the while loop becasue it just repeat the first input function, here is the code, i would aprriecate it if someone could point out my problem and help me fix my code, thnx
import random
roll_agn='yes'
while roll_agn=='yes':
dice=input ('Please choose a 4, 6 or 12 sided dice: ')
if dice ==4:
print(random.randint(1,4))
elif dice ==6:
print(random.randint(1,6))
elif dice ==12:
print(random.randint(1,12))
else:
roll_agn=input('that is not 4, 6 or 12, would you like to choose again, please answer yes or no')
if roll_agn !='yes':
print ('ok thanks for playing')
Upvotes: 1
Views: 1421
Reputation: 11039
Your indentation is off as others have pointed out. Here are a few suggestions on how to improve your code a little further
import random
while True:
try:
dice = int(input ('Please choose a 4, 6 or 12 sided dice: ')) # this input should be an int
if dice in (4, 6, 12): # checks to see if the value of dice is in the supplied tuple
print(random.randint(1,dice))
choice = input('Roll again? Enter yes or no: ')
if choice.lower() == 'no': # use .lower() here so a match is found if the player enters No or NO
print('Thanks for playing!')
break # exits the loop
else:
print('that is not 4, 6 or 12')
except ValueError: # catches an exception if the player enters a letter instead of a number or enters nothing
print('Please enter a number')
This will work no matter what the player enters.
Upvotes: 0
Reputation: 20391
Your else
statement is unindented (outside of the loop), so the variable within is never reset, so the condition that the while
loop requires is always True
, hence an infinite loop. You just need to indent this:
elif dice ==12:
...
else:
^ roll_agn = input()
Upvotes: 0
Reputation: 2161
The else block of the while would be executed only if roll_agn became non-'yes' inside the loop. You never change it inside the while loop, so it loops forever.
Upvotes: 1