gpt4 book ai didi

python - 对于输入 =4,if ( Selection < 0) 和 (Selection > 3) 条件的行为不同。为什么?

转载 作者:行者123 更新时间:2023-11-30 22:34:15 25 4
gpt4 key购买 nike

def PrintBlue():
print (" You chose Blue!\r\n")

def PrintRed():
print (" You chose Red!\r\n")

def PrintOrange():
print (" You chose Orange!\r\n")

def PrintYellow():
print (" You chose Yellow!\r\n")

#Let's create a dictionary with unique key

ColorSelect = {
0:PrintBlue,
1:PrintRed,
2:PrintOrange,
3:PrintYellow
}

Selection = 0

while (Selection != 4):
print ("0.Blue")
print ("1.Red")
print ("2.Orange")
print ("3.Yellow")
try:
Selection = int(input("Select a color option: "))
x=0
if ( Selection < 0) and (Selection > 3):
raise KeyError(" Enter a number >=0 and <4)")
else:
ColorSelect[Selection]() # Run the function inside dictionary as well
except KeyError:
pass

上面是我的Python代码。我用的是2.7版本。但运行后我得到了输入=4的不同结果。虽然我期望 Selection<0 或 >3 得到相同的结果。结果如下:

0.蓝色1.红色2.橙色3.黄色选择颜色选项:50.蓝色1.红色2.橙色3.黄色选择颜色选项:4

请注意,在我输入 input =4 后,python 退出运行时。当我输入 0,1,2,3,5,6,7 时,每次它都会再次要求输入值,但是当我输入 4 时退出。

最佳答案

if ( Selection < 0) and (Selection > 3):

表示“如果 Selection 既小于零又大于三”,这是不可能发生的。我怀疑你的意思是

if ( Selection < 0) or (Selection > 3):

如果输入超出有效范围,则会引发错误。

当您输入 4 时,程序正在退出,因为

while (Selection != 4):

如果这不是所需的行为,您需要更改该行。例如,如果您希望循环永远运行,则可能只是

while True:

关于python - 对于输入 =4,if ( Selection < 0) 和 (Selection > 3) 条件的行为不同。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44898066/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com