If- Then- Else in Python

Examples (if clause):


a = 1
b = 2
if a < b:
    print("a is less than b")

Output:

a is less than b

Indents (4 spaces) are important (see example below)!

Another example

Here the A and B variables are changed so the If-clause is not true. 

a = 3
b = 2
if a < b:
    print("a is less than b")
print("Something else, unrelated")

Output:

Something else, unrelated

Yet another example

c = 3
d = 4
if c < d:
    print("c is less than d")
else:
    print("c is NOT less than d")
print("outside the if block")

Output:

c is less than d
outside the if block

Else-if example


e = 7
f = 8
if e < f:
    print("e is less than f")
elif e == f:
    print("e is equal to f")
else:
    print("e is greater than f")

Output:

e is less than f

Several ELSE-IF example

e = 7
f = 8
if e < f:
    print("e is less than f")
elif e == f:
    print("e is equal to f")
elif e > f + 10:
    print("e is greather than f by more than 10")
else:
    print("e is greater than f")

Output:

e is less than f

An IF within an ELSE clause, example


g = 7
h = 8
if g < h:
    print("g is less than h")
else:
    if g == h:
        print("g is equal to h")
    else:
        print("g is greater than h")

Output:

g is less than h




Comments

Popular posts from this blog

Installing Microsoft ODBC Driver to connect to SQL from Python on Mac OS X

Connection to MSSQL with Pythonan and pyodbc (on Mac OS X)

Installing PyCharm on Mac