How to do a one line if statement in python?


If Statements are logical alternatives that will execute something based on something. They

vba if statements

are very intuitive as you are already doing them everyday in your everyday life, it is just a matter of learning the syntax for them (code language for saying how to write them in Python).

For example, should I get coffee? if yes, then add cream, if not, get tea with honey.

IF statements follows the following structure

Python works a lot with indentation. please note that the print comment is indented. if it wouldn't be, then an error would be thrown. Same goes for loops.

If Logical statement:    
   #Do something if the logical statement is true.
   Print ("Pls Fix Thx")

Logical expressions.

Logical expressions in python follow similar structure as most languages.

Equals a == b
Not Equals a != b
Less than a < b
Less than or equal to a <= b
Greater than a > b
Greater than or equal to a >= b

"and", "or" between logical expressions works like normal. 

If with multiple conditions.

Similar to most coding languages. "Else if", is shortened in python to just "Elif"

x = 7
y = 5

if x > y:
    print("x is greater")
elif x == y:
    print("x and y are equal")
else:
    print("y is greater")

Nested if statement

In some cases you will want to nest your if statement. an if in another if.

x = 7
y = 5
z = 14

if x > y:
    print("x is greater than y")
    if x > z:
        print("x is greater than z")
    else: 
        print("x is smaller than z")

Shorter if statement - single if.

x = 7
y = 7

if y == x: print("x and y are equal.")

Shorter if statement - 2 ifs.

#Result = is "Thx."
x = 7
y = 7

print("Please Fix") if a > b else print("Thx.")

Shorter if statement - 3 ifs.

#Result = is "Fix"
x = 7
y = 7

print("Please") if a > b else print("Fix") if a == b else print("Thx.")

Learn more about Python here for all my posts: https://www.pls-fix-thx.com/python

If you have found this article or website helpful. Please show your support by visiting the shop below.


57 views0 comments