![](/img/trans.png)
[英]Python: getting nested while loops to work with boolean statements(beginner)
[英]If Statement in Python (Nested Boolean statements)
我不知道如果標題使用了正確的術語,但我希望得到一些代碼並嘗試減少代碼的長度,這樣我就可以更快地輸入評估。 這是以及如果我以漫長的方式做到這一點的示例。
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
or
運算符是一個短路比較,返回最早的truthy值,如果沒有truthy值,則返回最后一個值。 在(Row or Column) < 0
,評估第一Row or Column
。 如果Row
非零,則該部分返回Row
。 否則,它將返回Column
。 然后它將此單個值與0
進行比較。 對於另一個比較也是如此,我假設它有一個拼寫錯誤,並且打算(Row or Column) > 9
(而不是> 0
)。
您還可以嘗試以下(不是詳盡的列表):
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))
選擇在程序環境中最有意義的那個。
你可以嘗試這個,但這會創建一個包含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.