Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

I need to print some stuff only when a boolean variable is set to True. So, after looking at this, I tried with a simple example:

>>> a = 100

>>> b = True

>>> print a if b

File "<stdin>", line 1

print a if b ^

SyntaxError: invalid syntax

Same thing if I write print a if b==True.

What am I missing here?

2 Answers

0 votes
by (106k points)

In Python, there is no trailing if statement. So you can not write inline if statement for print:-

In Python, there are two kinds of if statements:

  • The first if statement is as follows: if condition: statement if condition: block

  • The second if statement is an expression which is introduced in Python 2.5 and later versions.
    expression_if_true if condition else expression_if_false

Also, note that as you have written both print a and b = a are statements. Only the a part is an expression.

So if you write:-

print a if b else 0 

Then it means:-

print (a if b else 0)

0 votes
by (20.3k points)

Inline if-else EXPRESSION must always contain else clause like this: 

a = 1 if b else 0

But, If you want to leave your 'a' variable value unchanged - assing old 'a' value (else is still required by syntax demands) then you can do this:

a = 1 if b else a

In the above case, a will remain unchanged when b turns to be False.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Aug 26, 2019 in Python by Sammy (47.6k points)

Browse Categories

...