Search notes:

Python: if statement

if

if 'one' < 'two':
    print('one < two')
Github repository about-Python, path: /statements/if/simple.py

if … else

if 'one' < 'two':
   print('one < two')
else:
   print('one >= two')
Github repository about-Python, path: /statements/if/else.py

else if

Python uses the shortcut elif for else if:
a = 1
b = 1

if   a < b:
     print('a < b' )

elif a > b:
     print('a > b' )

else:
     print('a == b')
Github repository about-Python, path: /statements/if/elif.py

Ternary operator

The ternary operator … ? … : …, as found in C related languages, can be simulated in Python with … if … else …:
val = 42
result = 'yes' if val == 42 else 'no'
print(result)

val = 99
result = 'yes' if val == 42 else 'no'
print(result)
Github repository about-Python, path: /statements/if/ternary.py

Assignment in if statement

PEP-572 defines the assignment expression (aka walrus operator) with which it is (finally) possible to have an assignment in an if statement:
def half(n):

    r = n/2
    return r if int(r) == r else None


def F(n):

    if h := half(n):
       print('half({}) = {}'.format(n,h))
    else:
       print('{} is odd'.format(n))


F(42)
F(99)
Github repository about-Python, path: /statements/if/assignment.py

Using if in list comprehensions

if can also be used in list comprehensions to select the elements in a list that meet the given condition:
result = [ expr(x) for x in someList if criterion(x)]

See also

Each object can be evaluated in a boolean context, such as an if or while statement. The rules if an object is considered to be True or False are described here.
The else clause
statements

Index