how to assign value to variables between if and elif statement?
It shows me "An illegal target for a variable annotation" when I assgin b = 2 between if and elif. I do not want to assign b = 2 before if statement.
a = 1
if a > 1:
print("something")
b = 2
elif b > 1:
print("something")
CodePudding user response:
You can use Python's assignment expressions. They let you assign a variable within a conditional, then return the value assigned. Like this:
a = 1
if a > 1:
print("something")
elif (b := 2) > 1:
print("something")
If you wanted to only assign the variable b
, but not use it within the conditional, then you could rewrite your code as this (it is fairly ugly, but works in all cases):
a = 1
if a > 1:
print("something")
elif (b := 2, EXPRESSION TO TEST)[1]:
print("something")
CodePudding user response:
You simply don't write elif
in such case.
Instead you write else
, do what you want and if
:
a = 1
if a > 1:
print("something")
else:
b = 2
if b > 1:
print("something")