Reputation: 25
I'm trying to make a error message for my dice sim
import random
loop=1
while loop == 1:
dice=input("Choose dice 4,6 or 12 sided")
if dice =="4":
n=random.randint(1,4)
print(dice)
print(n)
if dice =="6":
n=random.randint(1,dice)
print(dice)
print(n)
if dice =="12":
n=random.randint(1,dice)
print(dice)
print(n)
else:
print("Error")
error comes up for 4 and 6 but when i use the 12 sided no error comes up
Choose dice 4,6 or 12 sided4
4
4
Error
Upvotes: 1
Views: 57
Reputation: 1426
You should really state which programming language you're using. I'm assuming this is Python, but if it's not my answer might be wrong.
Your problem is that you need to be using elif
, not if. You're also trying to implicitly convert between strings and integers, which doesn't work. This code should, unless I've missed something else.
import random
loop=1
while loop == 1:
dice=input("Choose dice 4,6 or 12 sided")
if dice =="4":
n=random.randint(1,4)
print(dice)
print(str(n))
elif dice =="6":
n=random.randint(1,int(dice))
print(dice)
print(str(n))
elif dice =="12":
n=random.randint(1,int(dice))
print(dice)
print(str(n))
else:
print("Error")
Upvotes: 1
Reputation: 6095
You need to use elif
instead of if, or a switch
statement.
The code you provided says "if dice does not equal 12 then print Error".
Try something like:
while loop == 1:
dice=input("Choose dice 4,6 or 12 sided")
if dice =="4":
n=random.randint(1,4)
print(dice)
print(n)
elif dice =="6":
n=random.randint(1,dice)
print(dice)
print(n)
elif dice =="12":
n=random.randint(1,dice)
print(dice)
print(n)
else:
print("Error")
This lets you break out of the loop early without evaluating every single expression.
Upvotes: 0