python-3.x 使用while循环检查条件

k4ymrczo  于 2023-04-08  发布在  Python
关注(0)|答案(2)|浏览(146)

我试着做了一个程序,当用户每次输入一个数字时,如果数字在0到2之间,它会返回用户输入的数字。否则,它会一直打印出“输入选择:“到控制台,直到用户输入了一个在范围内的值。我的问题是,我的while循环似乎不起作用,所以每次无论我输入什么值(即使它在范围0,2之外),值仍然返回。
下面是我现有的代码:

def get_user_option_input():
    number = input('Please enter a number: ')
    num = int(number)
    while not num > 0 and num < 2:
        print('Enter selection: ')
    return num
 
number = get_user_option_input()
print(number)

希望有人能帮我弄清楚这一点。非常感谢!

jaql4c8m

jaql4c8m1#

您可以执行以下操作:

def get_user_option_input():
    # Set num to something that is not in the valid range
    num = -1
    # Do until num is between 0 and 2
    while not (num > 0 and num < 2):
        # Get user input
        number = input('Please enter a number: ')
        num = int(number)
    return num

number = get_user_option_input()
print(number)

注意()not (num > 0 and num < 2)中的重要性。现在not对两个num > 0 and num < 2都求反。与前面一样,not只对boolean条件的num > 0部分求反。

zed5wv10

zed5wv102#

如果用户输入的第一个数字超出了范围,那么它将永远运行print('Enter selection: '),因为num在循环中永远不会更改。要解决这个问题,您需要将print('Enter selection: ')更改为num = int(input('Enter selection: '))。此外,将while not num > 0 and num < 2:更改为while not (num > 0 and num < 2):。否则,not仅对num > 0取反。通过添加括号,not否定num > 0num < 2

相关问题