繁体   English   中英

没有错误时出现错误代码

[英]error code comes up when no error

我正在尝试为我的骰子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")

4和6出现错误,但是当我使用12面时,没有错误出现

Choose dice 4,6 or 12 sided4
4
4
Error

您应该真正说明所使用的编程语言。 我假设这是Python,但是如果不是,我的答案可能是错误的。

您的问题是您需要使用elif ,而不是if。 您还试图在字符串和整数之间进行隐式转换,这是行不通的。 除非我错过了其他事情,否则这段代码应该会。

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

您需要使用elif代替if或switch语句。

您提供的代码显示“如果骰子不等于12,则显示错误”。

尝试类似:

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

这使您可以尽早摆脱循环,而无需评估每个表达式。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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