[英]Defining new variable before elif statement that is used as a condition
我正在嘗試使用if-elif-else
語句定義某種邏輯。 但在我看來似乎合乎邏輯的東西似乎是無效的語法。 我真的不明白為什么。 我想對此有一個相當簡單的答案。
我寫了一些邏輯如下:
mylist = ['a', 'aa', 'aaa']
for index, element in enumerate(mylist):
if index == len(mylist)-1:
# Case: this is the last element
pass
myvar = mylist[index+1]
elif len(myvar) == 2:
# Case: this is not the last element and the next element length is 2
pass
else:
# Case: this is not the last element and the next element length is not 2 ()
pass
問題在於myvar
的定義和隨之而來的elif
語句。 此代碼給出了無效的語法,pycharm 將其定義為“變量注釋的非法目標”。 問題是:為什么不能在elif
語句之前定義myvar
。 即使代碼可能無法到達某個elif
語句,是否必須在執行語句之前預定義所有條件? 或者if-elif-else
部分之間根本不能有任何額外的代碼? 在這種情況下,無法預定義myvar
,因為它可能超出范圍。
作為一個解決方案,我這樣做了:
for index, element in enumerate(mylist):
if index == len(mylist) - 1:
# Case: this is the last element
pass
else:
myvar = mylist[index + 1]
if len(myvar) == 2:
# Case: this not the last element and the length of next element is 2
pass
else:
# Case: this is not the last element and the length of next element is not 2
pass
是的,在if-elif-else
之間不能有任何額外的代碼。 所以你應該把myvar
放在if-elif-else
之前。
for index, element in enumerate(mylist):
myvar = mylist[index+1]
if index == len(mylist) - 1:
pass
elif len(myvar) == 2:
pass
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.