简体   繁体   English

If Python in Python(嵌套布尔语句)

[英]If Statement in Python (Nested Boolean statements)

I have no Idea if the title uses the correct terms but I am looking to get some code and to try and reduce the length of the code so It will be quicker for me to type in the assessment. 我不知道如果标题使用了正确的术语,但我希望得到一些代码并尝试减少代码的长度,这样我就可以更快地输入评估。 Here is and Example of How it would look if I did it the long winded way. 这是以及如果我以漫长的方式做到这一点的示例。

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

However, I was trying to to make that smaller by doing something along the lines of: 但是,我试图通过以下方式做一些事情来缩小规模:

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

Can someone explain why it doesn't seem work and can someone please demonstrate how they would solve it. 有人可以解释为什么它似乎不起作用,有人可以请证明他们将如何解决它。 I am only trying to slim down my if statements since throughout the assessment I will be using a large amount of them. 我只是试图减少我的if语句,因为在整个评估过程中我会使用大量的语句。

Update:- Can this also be put into a Try - Catch so it wouldn't crash the program upon entering a Null Value or No value 更新: - 这也可以放入Try-Catch中,这样在输入空值或无值时不会导致程序崩溃

Thanks 谢谢

You can remove the if statement completely. 您可以完全删除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

The or operator is a short-circuiting comparison that returns the earliest truthy value, or the last value if none are truthy. or运算符是一个短路比较,返回最早的truthy值,如果没有truthy值,则返回最后一个值。 In (Row or Column) < 0 , first Row or Column is evaluated. (Row or Column) < 0 ,评估第一Row or Column If Row is nonzero, that section returns Row . 如果Row非零,则该部分返回Row Otherwise, it would return Column . 否则,它将返回Column It then compares this single value to 0 . 然后它将此单个值与0进行比较。 The same goes for the other comparison, which I assume has a typo and was intended to be (Row or Column) > 9 (rather than > 0 ). 对于另一个比较也是如此,我假设它有一个拼写错误,并且打算(Row or Column) > 9 (而不是> 0 )。

You can also try the following (not an exhaustive list): 您还可以尝试以下(不是详尽的列表):

if not 0<=row<=9 or not 0<=column<=9
if row not in range(10) or column not in range(10)
if not all(0<=x<=9 for x in (row,column))

Choose the one that makes the most sense in the context of your program. 选择在程序环境中最有意义的那个。

You could try this, but this create an array of 10 elements [0..9].. 你可以尝试这个,但这会创建一个包含10个元素[0..9]的数组。

Valid = True
rangeValue = range(10)
while Valid:
  Column = int(input("Insert Column: "))
  Row = int(input("Insert Row: "))
  Valid = Row in rangeValue and Column in rangeValue

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM