2017-04-22 101 views
1

请帮忙!我不明白这里的错误。为什么当我输入0,1或2以外的数字时,出现错误:“'int'object is not callable”?相反,假设打印出“您输入的数字不正确,请重试”,然后回到提问。Python Int对​​象不可调用

第二个问题:我该如何更改代码,即使我输入字母字符,它也不会给我Value Error并继续重新提问?谢谢!

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

你的变量名阴影函数名。您尝试调用函数'player_action()',但实际上调用变量'player_action',这是一个int。不要为函数和变量使用相同的名称! – Craig

+1

此外,没有理由使此函数递归。只要放一个'while'循环,直到你得到一个有效的输入,然后用这个输入做一些事情。 – Craig

+0

哦,好的,谢谢! –

回答

1

你应该改变变量名@Pedro洛比托建议,使用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() 
0

只要改变变量名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() 
1

首先回答你的问题已经被佩德罗回答,但作为第二个答案,一尝试不同的说法应该解决这个问题:

编辑:噢,抱歉,我搞砸了一点点......有更好的答案,但我想我应该花时间来解决这个问题

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