我一直在用 Python 开发一个计算器。计算器没有问题,但我想对其中的部分代码进行更优化/缩短。
这是我想要优化/缩短的代码:
#In this code i check to see if they have entered a valid option in my calculator
option = int(input("Option: "))
if option != 0:
if option != 1:
if option != 2:
if option != 3:
if option != 4:
print("Please enter a valid choice")
#As you can see it needs to check 5 numbers
如果您能想出一种方法来缩短上面的代码,我们将不胜感激!
最佳答案
如果您将所有选项都列在一个列表中,这将是最快捷、最简单的方法。
if option not in [1,2,3,4]:
print("Not a valid choice")
关于python - 在 Python 中编写更紧凑的 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26825985/