[英]Defining new variable before elif statement that is used as a condition
I'm trying to define a certain logic with if-elif-else
statement.我正在尝试使用
if-elif-else
语句定义某种逻辑。 But it seems that what seems logical to me turns out to be invalid syntax.但在我看来似乎合乎逻辑的东西似乎是无效的语法。 And I can't really understand why.
我真的不明白为什么。 I suppose there is a rather simple answer to this.
我想对此有一个相当简单的答案。
I wrote some logic as follows:我写了一些逻辑如下:
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
The problem is with definition of myvar
and the consequent elif
statement.问题在于
myvar
的定义和随之而来的elif
语句。 This code gives invalid syntax, and pycharm defines it as 'Illegal target for variable annotation'.此代码给出了无效的语法,pycharm 将其定义为“变量注释的非法目标”。 The question is: why can't the
myvar
be defined right before the elif
statement.问题是:为什么不能在
elif
语句之前定义myvar
。 Does all conditions has to be predefined before executing the statement even tho the code might not get to a certain elif
statement?即使代码可能无法到达某个
elif
语句,是否必须在执行语句之前预定义所有条件? Or there simply can't be any extra code in between if-elif-else
parts?或者
if-elif-else
部分之间根本不能有任何额外的代码? In this case myvar
can't be predefined because it might be out of range.在这种情况下,无法预定义
myvar
,因为它可能超出范围。
As a solution I made it like this:作为一个解决方案,我这样做了:
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
Yes, there can't be any extra code in between if-elif-else
.是的,在
if-elif-else
之间不能有任何额外的代码。 So you should just put myvar
before the 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.