I'm making a D&D -type dice roller with the option for the user to choose what die to roll. I get the program to work, but i want the program to not crash every time you enter something that is not an integer. The specific error that occurs is Value error.
Also would like recommendations how to better the program. Goal is to make it "bug free" and later create GUI for it.
I've tried tinkering the program with try and except, but failed. Also tested if i could get rid of the problem by just adding more If statements
print("choose a die: \n 1 = d4 \n 2 = d6 \n 3 = d8 \n 4 = d10 \n 5 = d12 \n 6 = d20 \n 7 = d100 \n or 0 to quit program")
u_input = int(input())
while u_input != 0:
if u_input == 1:
print("rolled a: [", random.randrange(1, 5), "] on a d4")
u_input = int(input())
elif u_input == 2:
print("rolled a: [", random.randrange(1, 7), "] on a d6")
u_input = int(input())
elif u_input == 3:
print("rolled a: [", random.randrange(1, 9), "] on a d8")
u_input = int(input())
elif u_input == 4:
print("rolled a: [", random.randrange(1, 11), "] on a d10")
u_input = int(input())
elif u_input == 5:
print("rolled a: [", random.randrange(1, 13), "] on a d12")
u_input = int(input())
elif u_input == 6:
print("rolled a: [", random.randrange(1, 21), "] on a d20")
u_input = int(input())
elif u_input == 7:
print("rolled a: [", random.randrange(1, 101), "] on a d100")
u_input = int(input())
Rolls the results as supposed to, but crashes when the input is anything else than an integer.
You can check the type of input to avoid getting the value error.
Check the code below:
import random
print("choose a die: \n 1 = d4 \n 2 = d6 \n 3 = d8 \n 4 = d10 \n 5 = d12 \n 6 = d20 \n 7 = d100 \n or 0 to quit program")
#Initialization out of any of the expected values
u_input = 500
while u_input != 0:
u_input = input()
if type(u_input) != int:
print("Entered input is not of int type")
u_input = 500
continue
if u_input == 1:
print("rolled a: [", random.randrange(1, 5), "] on a d4")
elif u_input == 2:
print("rolled a: [", random.randrange(1, 7), "] on a d6")
elif u_input == 3:
print("rolled a: [", random.randrange(1, 9), "] on a d8")
elif u_input == 4:
print("rolled a: [", random.randrange(1, 11), "] on a d10")
elif u_input == 5:
print("rolled a: [", random.randrange(1, 13), "] on a d12")
elif u_input == 6:
print("rolled a: [", random.randrange(1, 21), "] on a d20")
elif u_input == 7:
print("rolled a: [", random.randrange(1, 101), "] on a d100")