How to write inline if statement for print in Python?

0 votes

I have a requirement to print content only when a boolean variable is set to True. 

I tried this example:

>>> x = 100
>>> y = True
>>> print x if y
  File "<stdin>", line 1
    print x if y
             ^
SyntaxError: invalid syntax  

Same thing if I write print x if y==True.

What is going wrong here?

Dec 4, 2018 in Python by Anirudh
• 2,070 points

edited Dec 6, 2018 by Anirudh 1,078 views

1 answer to this question.

0 votes

Inline if-else expression must always contain the else clause.

For example:

x = 1 if y else 0

If you want to leave the value 'y' variable value unchanged - adding old 'x' value

(Else is needed due to syntax):

x = 1 if y else x

This piece of code leaves x unchanged when y turns to be False.

Hope this helps!

answered Dec 4, 2018 by Nymeria
• 3,520 points

edited Dec 6, 2018 by Nymeria

Related Questions In Python

0 votes
1 answer

how to exit a python script in an if statement

This works fine for me: while True: ...READ MORE

answered Sep 19, 2018 in Python by bug_seeker
• 15,350 points
3,443 views
0 votes
1 answer

How to break for loop in an if statement

You can break out of each loop ...READ MORE

answered Nov 16, 2018 in Python by Jino
• 5,560 points
70 views
0 votes
4 answers
+2 votes
11 answers
0 votes
1 answer

How to use nested if else statement in python?

The working of nested if-else is similar ...READ MORE

answered Nov 19, 2018 in Python by Nabarupa
51 views
0 votes
1 answer

what is an else if statement in python?

if condition:    statement elif condition:     statement #this is how you use ...READ MORE

answered Mar 15 in Python by Waseem
• 4,480 points
38 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 283 views
0 votes
1 answer

How to fix this? ValueError: invalid literal for int() with base 10 error in Python

The following are totally acceptable in python: passing ...READ MORE

answered Nov 16, 2018 in Python by Nymeria
• 3,520 points
15,867 views
0 votes
1 answer

How should I write tests for Forms in Django with Python?

from django.tests import TestCase class MyTests(TestCase): ...READ MORE

answered Nov 20, 2018 in Python by Nymeria
• 3,520 points
38 views