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.黄色 选择颜色选项:5 0.蓝色 1.红色 2.橙色 3.黄色 选择颜色选项:4
block 引用> block 引用>请注意,在我输入 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/