I am trying to add a value to a variable and print it, in the same one line if loop.
First i tried to separate my 2 actions with a ,
:
JavaScript
x
8
1
test = 0
2
if True : test = 4, print(test)
3
> 0
4
5
print (test)
6
> (4, None)
7
8
I don’t uderstand why my variable get the value 0 when printed from the if. Outside i get a list, like test value is 4, print(test)
After i tried to use and
between 2 actions :
JavaScript
1
7
1
test = ""
2
if True : test = "hello" and print(test)
3
>
4
5
print(test)
6
> None
7
I think my variable is trying to get the value : test and print(toto)
Do you know if and how can i do multiple actions in a single line if loop ?
(sorry for possible duplicate but i keep matching answers for multiple condition in one if loop)
Advertisement
Answer
as of python 3.8 you can use walrus operator for both evaluating and assigning:
JavaScript
1
3
1
if True: print(test := "hello")
2
> hello
3
- you get 0, since
test = 4, print(test)
evaluates right hand side part as a tuple and assigns it to thetest
variable, thus it will assign totest
4 and the result of the print function, which isNone
test = "hello" and print(test)
will once again evaluate the right side. you useand
operator, which evaluates the first argument, which for not empty strings isTrue
. it then proceeds to the next argument and it assigns its value to the variable. in your case it is the result of the print function, which isNone