Day 4: Control Structures - Conditionals#

Conditional statements, commonly known as “if statements,” are a fundamental aspect of programming, allowing the code to execute different actions depending on certain conditions. This concept, often referred to as “branching,” enables programs to make decisions, thereby increasing their complexity and capability.

If This, Then That#

The if statement is the most basic form of conditional execution in Python. It tests a condition and executes a block of code if the condition is true. The syntax requires an indentation block, which defines the scope of the statement.

if condition:
    # This code runs if condition is True
    do_something()
x = 42

if x > 40:
  print("voila!")
voila!
print(x)

if x > 50:
  print("...also voila?")
42

Otherwise, Do This!#

The else statement is used in conjunction with if. It defines a block of code that is executed when the if condition is not met.

if condition:
    do_something()
else:
    # This code runs if condition is False
    do_something_else()
print(x)

if x > 50:
  print("...also voila?")
else:
  print("Not voila!")
42
Not voila!

Code Block of Last Resort#

The elif (short for “else if”) statement is used to check multiple expressions for truth value and execute a block of code as soon as one of the conditions evaluates to True. It’s a way to handle multiple, mutually exclusive conditions.

if condition1:
    do_something()
elif condition2:
    do_something_else()
else:
    # This runs if neither condition1 nor condition2 is True
    do_another_thing()

if/elif statements in Python can be likened to a C-style switch block, where different cases are checked, and corresponding actions are taken based on which case is true.

x = 42

if x > 60:
  print("Largest case")
elif x > 40:
  print("Medium case")
else:
  print("Final case")
Medium case

Saving on Words: Succinct Versions#

In Python, if statements can be written in a more compact form, especially when the action to be executed is short.

if condition: do_something()

There is also the ternary expression in Python, which allows for a quick evaluation of a condition in a single line. It’s a concise way of writing an if-else statement.

result = a if condition else b

This expression assigns a to result if condition is True, and b otherwise. Understanding and using these forms of conditional statements enhance the readability and efficiency of your code, especially in scenarios where decision-making is a key aspect of the program logic.

x = 42

if x > 60: print("Largest case")
elif x > 40: print("Medium case")
else: print("Final case")
Medium case
# consider using vertical alignment and whitespace to improve readability

x = 42

if   x > 60: print("Largest case")
elif x > 40: print("Medium case")
else:        print("Final case")
Medium case

Lesson Project: FizzBuzz and a Similar Challenge#

FizzBuzz Problem Statement#

FizzBuzz is a classic programming task, often used in job interviews to assess basic programming skills. The challenge is as follows:

  • Print numbers from 1 to 100.

  • For multiples of 3, print “Fizz” instead of the number.

  • For multiples of 5, print “Buzz” instead of the number.

  • For numbers which are multiples of both 3 and 5, print “FizzBuzz”.

FizzBuzz Solution in Python#

This solution uses a for loop to iterate through the numbers 1 to 100 and conditional statements (if, elif, else) to determine what to print for each number.

for i in range(1, 101):
    if i % 3 == 0 and i % 5 == 0:
        print("FizzBuzz")
    elif i % 3 == 0:
        print("Fizz")
    elif i % 5 == 0:
        print("Buzz")
    else:
        print(i)
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
Buzz
Fizz
22
23
Fizz
Buzz
26
Fizz
28
29
FizzBuzz
31
32
Fizz
34
Buzz
Fizz
37
38
Fizz
Buzz
41
Fizz
43
44
FizzBuzz
46
47
Fizz
49
Buzz
Fizz
52
53
Fizz
Buzz
56
Fizz
58
59
FizzBuzz
61
62
Fizz
64
Buzz
Fizz
67
68
Fizz
Buzz
71
Fizz
73
74
FizzBuzz
76
77
Fizz
79
Buzz
Fizz
82
83
Fizz
Buzz
86
Fizz
88
89
FizzBuzz
91
92
Fizz
94
Buzz
Fizz
97
98
Fizz
Buzz

Alternative Lesson Project: Temperature Analyzer#

Temperature Analyzer Problem Statement#

Create a program that analyzes temperature data and categorizes each temperature entry. The challenge is as follows:

  • Iterate over a list of temperature readings (in Celsius).

  • For each temperature:

    • If it’s below 0, categorize it as “Freezing”.

    • If it’s between 0 and 15 (inclusive), categorize it as “Cold”.

    • If it’s between 16 and 25 (inclusive), categorize it as “Moderate”.

    • If it’s above 25, categorize it as “Hot”.

  • Print the temperature and its category.

Temperature Analyzer Solution in Python#

This solution uses a for loop to iterate through a predefined list of temperatures and conditional statements (if, elif, else) to determine the category for each temperature.

temperatures = [3, 16, -2, 21, 30, 15, 1, -5, 24, 27]

for temp in temperatures:
    if temp < 0:
        category = "Freezing"
    elif temp <= 15:
        category = "Cold"
    elif temp <= 25:
        category = "Moderate"
    else:
        category = "Hot"

    print(f"Temperature: {temp}°C, Category: {category}")
Temperature: 3°C, Category: Cold
Temperature: 16°C, Category: Moderate
Temperature: -2°C, Category: Freezing
Temperature: 21°C, Category: Moderate
Temperature: 30°C, Category: Hot
Temperature: 15°C, Category: Cold
Temperature: 1°C, Category: Cold
Temperature: -5°C, Category: Freezing
Temperature: 24°C, Category: Moderate
Temperature: 27°C, Category: Hot

Your Challenge: Daily Step Counter#

Problem Statement: Write a program that interprets a list of daily step counts. For each day’s step count:

  • If the steps are less than 5,000, categorize as “Sedentary”.

  • If the steps are between 5,000 and 7,499 (inclusive), categorize as “Lightly Active”.

  • If the steps are between 7,500 and 9,999 (inclusive), categorize as “Moderately Active”.

  • If the steps are 10,000 or more, categorize as “Very Active”.

  • Print the day number and the corresponding activity category.

Further Resources#