简体   繁体   中英

error code comes up when no error

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

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")

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM