Hi i am trying to make the program only accept the numbers 0, 4, 6, and 12, and not allow anything else to be inputted. So far i have been successful in only allowing certain integers to be entered, however i am having trouble with not allowing any letters to be entered. When a letter is entered, the entire program crashes. Please could you help me only allow integers to be entered? Thank you.
My code is below:
from random import randint
def simul():
dice = int(input("What sided dice would you like to roll? 4, 6 or 12? 0 to not roll:"))
if dice != 4 and dice!=6 and dice!=12 and dice!=0:
print('You must either enter 4, 6, or 12')
simul()
elif dice==0:
exit()
else:
while dice !=0 and dice==4 or dice==6 or dice ==12 :
print (randint(1,dice))
dice = int(input("What sided dice would you like to roll? 4, 6 or 12? press 0 to stop."))
simul()
A couple of things you could look for in your code:
from random import randint
def simul():
while True:
try:
dice = int(input("What sided dice would you like to" \
" roll? 4, 6 or 12? 0 to not roll: "))
if dice not in (4, 6, 12, 0):
raise ValueError()
break # valid value, exit the fail loop
except ValueError:
print("You must enter either 4, 6, 12, or 0")
if dice == 0:
return 0
print(randint(1, dice))
return dice
if __name__ == '__main__':
while simul() != 0:
pass