2013-06-20 71 views
0

說SECRET_NUMBER = 77.我希望該函數能夠一直提示用戶,直到猜測出祕密數字。但是,「您的猜測太低」或「您的猜測過高」無法正常工作。 如果我輸入guess_number(4),它表示猜測值太低,但如果我接下來輸入100,它仍然表示我的猜測太低。我的功能可能有什麼問題?Python:輸入函數無法按預期方式工作

def guess_number(num): 

    '''(int) -> NoneType 

     Print out whether the secret number was guessed or a hint, if the 
     number was not guessed. Make this prompt the user for a number until the 
     secret number is guessed. 

     >>> guess_number(50) 
     Your guess was too low! 
    ''' 
    while num != SECRET_NUMBER: 

     if num < SECRET_NUMBER: 
      print('Your guess was too low!') 
      input('Guess a number: ') 

     elif num > SECRET_NUMBER: 
      print('Your guess was too high!') 
      input('Guess a number: ') 

    else: 
     print('You guessed it!') 

回答

3

input()回報任何用戶輸入。你不存儲函數返回的內容;它被丟棄。

儲存於您的變量:

num = input('Guess a number: ') 

你可能想將其轉換成一個整數; input()返回一個字符串:

num = int(input('Guess a number: ')) 

你只需要一次提出要求爲每個嘗試:

while num != SECRET_NUMBER: 

    if num < SECRET_NUMBER: 
     print('Your guess was too low!') 

    elif num > SECRET_NUMBER: 
     print('Your guess was too high!') 

    num = int(input('Guess a number: ')) 

else: 
    print('You guessed it!') 

另見Asking the user for input until they give a valid response

1

您需要輸入值賦值給一個變量,例如

num = int(input('Guess a number: ')) 

請注意,我也投來詮釋,因爲input()返回一個字符串

相關問題