gpt4 book ai didi

python - 没有错误时出现错误代码

转载 作者:太空宇宙 更新时间:2023-11-03 18:44:13 24 4
gpt4 key购买 nike

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

关于python - 没有错误时出现错误代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19914090/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com