[英]error code comes up when no error
I'm trying to make a error message for my dice sim 我正在尝试为我的骰子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 4和6出现错误,但是当我使用12面时,没有错误出现
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.
我假设这是Python,但是如果不是,我的答案可能是错误的。
Your problem is that you need to be using elif
, not if. 您的问题是您需要使用
elif
,而不是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. 您需要使用
elif
代替if或switch
语句。
The code you provided says "if dice does not equal 12 then print Error". 您提供的代码显示“如果骰子不等于12,则显示错误”。
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. 这使您可以尽早摆脱循环,而无需评估每个表达式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.