python - Python 中的 If 语句(嵌套 boolean 语句)

标签 python python-3.x if-statement boolean

我不知道标题是否使用了正确的术语,但我希望获得一些代码并尝试减少代码的长度,以便我可以更快地输入评估。这是一个例子,如果我用冗长的方式来做,它会是什么样子。

Valid = True
while Valid:
  Column = int(input("Insert Column: "))
  Row = int(input("Insert Row: "))
  if Row < 0 or Row > 9 or Column < 0 or Column > 9:
    Valid = False

但是,我试图通过按照以下方式做一些事情来缩小它:

"If (Row or Column) < 0 or (Row or Column) > 0:
   valid = False"

有人可以解释为什么它似乎不起作用,有人可以演示他们将如何解决它。我只是想精简我的 if 语句,因为在整个评估过程中我将使用大量它们。

更新:- 这也可以放入 Try - Catch 中,这样它就不会在输入空值或无值时使程序崩溃

谢谢

最佳答案

您可以完全删除 if 语句。

Valid = True
while Valid:
  try:
     Column = int(input("Insert Column: "))
     Row = int(input("Insert Row: "))
     Valid = Row in range(10)  and Column in range(10)
  except Exception as e:
     print(e)
     Valid = False

关于python - Python 中的 If 语句(嵌套 boolean 语句),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37080693/

相关文章:

python - 在 Python 中实现并行 for 循环

python - 获取给定当前点、距离和方位的纬度/经度

python - 类型错误 : 'Popen' object is not callable

python - 有没有办法使用 python 3.x 访问 Protocol Buffer ?

将以下 SWITCH 语句转换为 IF...ELSE 语句

Python 索引错误 : list assignment index out of range when listing txt file

python - 将Python代码转换为C代码

Python删除相等列表

c# - 为什么我的简单 if 语句不起作用?

MySQL 错误 1241 操作数应包含 1 列(IF EXISTS)