Skip to content
Advertisement

How to execute multiple statement in a one line if loop?

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 ,:

test = 0
if True : test = 4, print(test)
> 0

print (test)
> (4, None)

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 :

test = ""
if True :  test = "hello" and print(test)
> 

print(test)
> None

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:

if True: print(test := "hello")
> hello
  • you get 0, since test = 4, print(test) evaluates right hand side part as a tuple and assigns it to the test variable, thus it will assign to test 4 and the result of the print function, which is None
  • test = "hello" and print(test) will once again evaluate the right side. you use and operator, which evaluates the first argument, which for not empty strings is True. 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 is None
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement