PYTHON: Single-Line IF & IF/ELSE Statements
Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
PYTHON: IF & IF/ELSE Statements on a Single-Line
In this tutorial, we will explore how to place "IF" and "IF/ELSE" statements on a single-line.
The Standard Way
First, let's review how to do IF and IF/ELSE statemtents:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# The IF Statement:
a = 5
if a == 5:
print("True")
# The IF/ELSE Statement:
a = 5
if a == 5:
print("True")
else:
print("False")
Enter to Rename, Shift+Enter to Preview
Try it for yourself.
Single-Line Code
Now, let's condense them into single-line code snippets.
1
2
3
4
5
6
7
8
9
10
# The IF Statement:
a = 5
if a == 5:print("True")
# The IF/ELSE Statement:
a = 5
print("True" if a == 5 else "False")
Enter to Rename, Shift+Enter to Preview
Try it for yourself... you should get the same result.
Happy Coding, @Code-Parser
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content