Python:输入功能无法正常工作 [英] Python: input function not working as expected

查看:60
本文介绍了Python:输入功能无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说SECRET_NUMBER =77.我希望函数一直提示用户,直到猜测到秘密号码为止.但是,您的猜测过低"或您的猜测过高"无法正常工作.如果我输入guess_number(4),它表示猜测值太低,但是如果我接下来输入100,它仍然表示我的猜测值太低.我的功能可能有什么问题?

Say that the SECRET_NUMBER = 77. I want the function to keep prompting the user until the secret number is guessed. However, the 'your guess is too low' or 'your guess is to high' isn't working properly. If I enter guess_number(4), it says guess is too low, but if I next put in 100, it still says my guess is too low. What might be wrong with my function?

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!')

推荐答案

input() 返回,无论用户输入了什么.您没有存储函数返回的内容;而是丢弃.

input() returns whatever the user entered. You are not storing what the function returns; it is discarded instead.

将其存储在您的变量中:

Store it in your variable:

num = input('Guess a number: ')

您可能想将其转换为整数; input()返回一个字符串:

You probably want to turn that into an integer; input() returns a string:

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

每次尝试只需要问一次:

You only need to ask for it once for each try:

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!')

另请参见 用户输入,直到他们给出有效的响应为止. .

Also see Asking the user for input until they give a valid response.

这篇关于Python:输入功能无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆