2017-04-22 135 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()