Python Int对​​象不可调用

时间:2017-04-22 20:50:53

标签: python object int

请帮忙!我不明白这里的错误。为什么我会收到错误说:"' int'对象不可调用"当我输入0,1或2以外的数字?相反,它打算打印"您输入了错误的数字,请再试一次"然后回去问问题。

第二个问题:另外,我怎样才能改变代码,即使我输入字母字符,它也不会给我价值错误并继续重新提问?谢谢!

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

3 个答案:

答案 0 :(得分:1)

Pedro已回答了您的问题的第一个答案,但对于第二个答案,尝试除了声明应该解决这个问题:

编辑:对不起,我把它搞砸了......有更好的答案,但我想我应该花点时间来解决这个问题

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

答案 1 :(得分:1)

您应该将变量名称更改为@Pedro Lobito建议,使用while循环作为@Craig建议,您还可以包含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()

答案 2 :(得分:0)

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

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