mardi 16 novembre 2021

Python oneliner if condition with multiple statements separated with commas and semicolons

a = True

if a : print('msg1'), print('msg2');
# msg1 and msg2 are printed

if a : print('msg1'), print('msg2'), b = 1;
# if a : print('msg1'), print('msg2'), b = 1;
#       ^
# SyntaxError: can't assign to function call

if a : print('msg1'); print('msg2'); b = 1;
# msg1 and msg2 are printed and b is also assigned the value 1

if a : b = 1; c = 5; print(b), print(c)
# b and c are assigned values 1 and 5, and both are printed

The 1st if statement works with the comma between the 2 print statements.
The 3rd if statement works as well with all statements separated with semicolons.

The 2nd if statement with a combination between commas and semicolons doesn't work anymore.
The 4th if statement with print statements separated by commas, and normal statements by semicolons works again.

So it seems to me that while print statments can be separated by commas, normal statements cannot. And thus it is better to just separate everything with semicolons in a oneliner if statement.

Could someone maybe explain / confirm the logic behind this?

Aucun commentaire:

Enregistrer un commentaire