5.3. Conditional Statements

5.3.1. Positive and Negative Values

Negative values:

  • empty bool() or False

  • empty int() or 0

  • empty float() or 0.0

  • empty complex() or 0+0j or 0.0+0.0j

  • empty str() or ''

  • empty tuple() or ()

  • empty list() or []

  • empty set()

  • empty frozenset()

  • empty dict() or {}

  • None

Positive values:

  • any other

5.3.2. Conditional Statement

Listing 5.17. if generic syntax
if <condition>:
    <do something>
Listing 5.18. Single line statements
if True:
    print('First line of the true statement')

# First line of the true statement
Listing 5.19. Multiline blocks
if True:
    print('First line of the true statement')
    print('Second line of the true statement')
    print('Third line of the true statement')

# First line of the true statement
# Second line of the true statement
# Third line of the true statement
Listing 5.20. Multiline blocks
if True:
    print('First line of the true statement')
    print('Second line of the true statement')

    if True:
        print('First line of inner true statement')

# First line of the true statement
# Second line of the true statement
# First line of inner true statement
Listing 5.21. Checking for simple value
age = 7

if age == 7:
    print('Go to school')

# Go to school
Listing 5.22. Checking for simple value.
country = 'USA'

if country == 'USA':
    job = 'astronaut'

print(job)
# astronaut
Listing 5.23. Checking for simple value
number = 4

if number % 2 == 0:
    print('Even')

# Even
Listing 5.24. Checking if value is in range
age = 7

if 0 <= age < 18:
    print('Age is between [0, 18)')

# Age is between [0, 18)
Listing 5.25. Checking if value is in range
a = 10
b = 100

if 0 <= a <= 50 < b:
    print('Yes')

# Yes
Listing 5.26. Checking if has value
name = input('What is your name?: ')
# What is your name?: Jan Twardowski<ENTER>

if name:
    print(f'My name is... {name}')

# My name is Jan Twardowski
Listing 5.27. Checking if has value
name = input('What is your name?: ')
# What is your name?: <ENTER>

if name:
    print(f'My name... {name}')

5.3.3. Unconditional Alternative

  • Optional

  • Executed when condition is not met

Listing 5.28. else generic syntax
if <condition>:
    <do something>
else:
    <do something>
Listing 5.29. Single line statements
if True:
    print('True statement')
else:
    print('Else statement')

# True statement
Listing 5.30. Multiline blocks
if True:
    print('True statement, first line')
    print('True statement, second line')
else:
    print('Else statement, first line')
    print('Else statement, second line')

# True statement, first line
# True statement, second line
Listing 5.31. Nested multiline blocks
if True:
    print('Outer block, true statement, first line')
    print('Outer block, true statement, second line')

    if True:
        print('Inner block, true statement, first line')
        print('Inner block, true statement, second line')
    else:
        print('Inner block, else statement, fist line')
        print('Inner block, else statement, second line')

else:
    print('Outer block, else statement, first line')
    print('Outer block, else statement, second line')

# Outer block, true statement, first line
# Outer block, true statement, second line
# Inner block, true statement, first line
# Inner block, true statement, second line
number = 3

if number % 2 == 0:
    print('Even')
else:
    print('Odd')

# Odd
Listing 5.32. Checking if variable is certain value
country = 'USA'

if country == 'Russia':
    job = 'cosmonaut'
else:
    job = 'astronaut'

print(job)
# astronaut
Listing 5.33. Checking if variable is certain value
name = input('What is your name?: ')
# What is your name?: <ENTER>

if name:
    print(f'My name is... {name}')
else:
    print('Did you forget to type your name?')

# Did you forget to type your name?
data = [True, False, True]

if any(data):
    print('Yes')
else:
    print('No')

# Yes
data = [True, False, True]

if all(data):
    print('Yes')
else:
    print('No')

# No

5.3.4. Conditional Alternative

  • Used to check for additional condition if first is not met

  • In other languages is known as else if

Listing 5.34. elif generic syntax
if <condition>:
    <do something>
elif <condition>:
    <do something>
else:
    <do something>
language = input('What is your language?: ')
# What is your language?: Polish<ENTER>

if language == 'English':
    print('Hello')
elif language == 'Russian':
    print('Здравствуйте')
elif language == 'German':
    print('Guten Tag')
elif language == 'Polish':
    print('Witaj')
else:
    print("I don't speak this language")

# Witaj

5.3.5. Shorthand Expressions

number = 3
is_even = (number % 2 == 0 )

print(is_even)
# True
number = 3
is_digit = (number in range(0,10))

print(is_digit)
# True

5.3.6. Conditional Expression

number = 3

if number in range(0,10):
    is_digit = True
else:
    is_digit = False

print(is_digit)
# True
number = 3
is_digit = True if number in range(0,10) else False

print(is_digit)
# True
ip = '127.0.0.1'
protocol = 'IPv4' if '.' in ip else 'IPv6'

print(protocol)
# IPv4
Listing 5.35. Normal if
country = 'USA'

if country == 'Russia':
    job = 'cosmonaut'
else:
    job = 'astronaut'

print(job)
# astronaut
Listing 5.36. Inline if
country = 'USA'
job = 'cosmonaut' if country == 'Russia' else 'astronaut'

print(job)
# astronaut
Listing 5.37. Is Numeric
age = input('What is your age?: ')
age = float(age) if age.isnumeric() else None
print(age)

5.3.7. Switch

  • No switch statement in Python!

  • switch in Object Oriented Programming is considered a bad practise

  • PEP 275

switch = {
    'English': 'Hello',
    'Russian': 'Здравствуйте',
    'German': 'Guten Tag',
    'Polish': 'Witaj',
    'default': "I don't speak this language"}


language = input('What is your language?: ')
# What is your language?: French<ENTER>

switch.get(language, switch['default'])
# "I don't speak this language"
def switch(key):
    data = {
        'English': 'Hello',
        'Russian': 'Здравствуйте',
        'German': 'Guten Tag',
        'Polish': 'Witaj',
        'default': "I don't speak this language"}
    return data.get(language, data['default'])


switch('Russian')
# 'Здравствуйте'

switch('French')
# "I don't speak this language"

5.3.8. Assignments

5.3.8.1. Conditional Statements

English
  1. Ask user to input age

  2. User will pass only valid int

  3. Print whether user is adult

Polish
  1. Poproś użytkownika o wprowadzenie swojego wieku

  2. Użytkownika poda tylko poprawne int

  3. Wypisz czy użytkownik jest pełnoletni

The whys and wherefores
  • Reading input

  • Type casting

  • Conditional statements

  • Defining variables

  • Magic Number