gpt4 book ai didi

Python Int 对象不可调用

转载 作者:行者123 更新时间:2023-12-01 03:04:11 28 4
gpt4 key购买 nike

请帮忙!我不明白这里的错误。当我输入 0、1 或 2 以外的数字时,为什么会收到错误消息:“‘int’对象不可调用”?相反,它应该打印“您输入了错误的数字,请重试”并返回询问问题。

第二个问题:另外,如何更改代码,即使我输入字母字符,也不会给出值错误并继续重新提出问题?谢谢!

def player_action():        
player_action = int(input("Enter 0 to stay, 1 to go Up, or 2 to go Down: "))

if player_action == 0:
print ("Thank You, you chose to stay")


if player_action == 1:
print ("Thank You, you chose to go up")

if player_action == 2:
print ("Thank You, you chose to go down")

else:
print ("You have entered an incorrect number, please try again")
player_action()

player_action()

最佳答案

您应该按照@Pedro Lobito的建议更改变量名称,按照@Craig的建议使用while循环,并且还可以包含try... except语句,但不是 @polarisfox64 的做法,因为他把它放在了错误的位置。

以下是完整版本供您引用:

def player_action():    
while True:
try:
user_input = int(input("Enter 0 to stay, 1 to go Up, or 2 to go Down: "))
except ValueError:
print('not a number')
continue

if user_input == 0:
print ("Thank You, you chose to stay")

if user_input == 1:
print ("Thank You, you chose to go up")

if user_input == 2:
print ("Thank You, you chose to go down")

else:
print ("You have entered an incorrect number, please try again")
continue
break

player_action()

关于Python Int 对象不可调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43564465/

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