2024-05-17 14:33:48 发布
网友
我有以下代码:
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时,它确实进入了循环。 为什么会这样?你知道吗
您使用的是字符串而不是数字('5','1')。字符串比较由单个字符完成,“45”中的字符“4”小于字符“5”。你知道吗
'5'
'1'
>>> ord('4') 52 >>> ord('5') 53
Python不以分号结束语句
while或not都不需要括号。你知道吗
while
not
你需要比较数字,而不是字符串。但是等等,input在Python3中返回一个字符串,所以您也需要int()这样做。你知道吗
input
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");
您使用的是字符串而不是数字(
'5'
,'1'
)。字符串比较由单个字符完成,“45”中的字符“4”小于字符“5”。你知道吗Python不以分号结束语句
while
或not
都不需要括号。你知道吗你需要比较数字,而不是字符串。但是等等,
input
在Python3中返回一个字符串,所以您也需要int()
这样做。你知道吗对于有效的输入,这将是一个无限while循环,所以请做好准备
你可以写下:
相关问题 更多 >
编程相关推荐