python - 在 Python 中编写更紧凑的 if 语句

标签 python if-statement

我一直在用 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/

相关文章:

javascript - ELSE IF using 怎么写? : in javascript

javascript - 检查字符串是否包含大于/小于的数字并更改其在 DOM 中的样式

Bash 条件管道

javascript - OR if 语句问题中的逻辑。

python - 如何生成预算受限的加权随机样本,其中项目具有不同的概率和权重?

python - Pandas - 识别以列表中的值开头的数据框值

python - 有没有办法按值删除列表中的对象?

python - 使用 pyqtgraph 和线程进行实时绘图

Python - 如何将嵌套列表拆分为更多列表?

java - 嵌套 if 语句 - 变量可能尚未初始化