当你表现得很怪异的时候

2024-05-17 14:33:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码:

fn = input("Choose a function(1, 2, 3, 4, 5, other(quit)): ");
while (not(fn > '5' or fn < '1')):
    print("hello world");

大多数情况下,这是有效的。例如,如果我输入54或某个疯狂的数字,它将永远不会打印“hello world”。
但是,当我输入45时,它确实进入了循环。
为什么会这样?你知道吗


Tags: or代码helloworldinputnot情况function
3条回答

您使用的是字符串而不是数字('5''1')。字符串比较由单个字符完成,“45”中的字符“4”小于字符“5”。你知道吗

>>> ord('4')
52
>>> ord('5')
53

Python不以分号结束语句

whilenot都不需要括号。你知道吗

你需要比较数字,而不是字符串。但是等等,input在Python3中返回一个字符串,所以您也需要int()这样做。你知道吗

fn = input("Choose a function(1, 2, 3, 4, 5, other(quit)): ")
if fn == 'quit':
    # break out of this choose a function prompt
else: 
    while int(fn) in range(1, 5 + 1): # +1 because non-inclusive ranges
       print("hello world")

对于有效的输入,这将是一个无限while循环,所以请做好准备

你可以写下:

fn = input("Choose a function(1, 2, 3, 4, 5, other(quit)): ");
while str(fn) + ',' in '1,2,3,4,5,':
    print("hello world");

相关问题 更多 >