繁体   English   中英

Python Int对​​象不可调用

[英]Python Int object not callable

请帮忙! 我不明白这里的错误。 当我键入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)已回答您问题的第一个答案,但至于第二个答案,请尝试try语句可以解决此问题:

编辑:是的,对不起,我把它弄乱了……有更好的答案,但我认为我应该花点时间解决这个问题

def player_action():
    try:
        player_action_input = int(input("Enter 0 to stay, 1 to go Up, or 2 to go Down: "))
    except ValueError:
        print("Non valid value") # or somehting akin
        player_action()
    if player_action_input == 0:
        print ("Thank You, you chose to stay")
    elif player_action_input == 1:
        print ("Thank You, you chose to go up")
    elif player_action_input == 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()

只需将变量名称player_action更改为函数的差异名称即可,即:

def player_action():
    user_input = int(input("Enter 0 to stay, 1 to go Up, or 2 to go Down: "))
    if user_input == 0:
        print ("Thank You, you chose to stay")
    elif user_input == 1:
        print ("Thank You, you chose to go up")
    elif user_input == 2:
        print ("Thank You, you chose to go down")
    else:
        print ("You have entered an incorrect number, please try again")
        player_action()

player_action()

暂无
暂无

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

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