我试着做了一个程序,当用户每次输入一个数字时,如果数字在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)
希望有人能帮我弄清楚这一点。非常感谢!
2条答案
按热度按时间jaql4c8m1#
您可以执行以下操作:
注意
()
在not (num > 0 and num < 2)
中的重要性。现在not
对两个num > 0 and num < 2
都求反。与前面一样,not
只对boolean
条件的num > 0
部分求反。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 > 0
和num < 2
。