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,080 points

edited Dec 6, 2018 by Anirudh 16,477 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!!

If you need to know more about Python, join Python online course today.


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

edited Dec 6, 2018 by Nymeria

Related Questions In Python

0 votes
5 answers

how to exit a python script in an if statement

Instead of using the normal UTF-8 encoding, ...READ MORE

answered Jul 4, 2023 in Python by bodymist
• 140 points
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,820 points
0 votes
4 answers
+1 vote
12 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
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, 2019 in Python by Waseem
• 4,540 points
0 votes
2 answers
+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 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,114 views
+1 vote
10 answers

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,560 points
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,560 points
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP