Python (Beginner) - Lesson 4: Control Structures – Conditionals and Loops

Welcome to Lesson 4! In this lesson, we will dive into control structures in Python, which allow your programs to make decisions and repeat actions. You will learn how to use conditionals to execute code based on different conditions and loops to perform repeated operations. These constructs are fundamental for writing dynamic and efficient programs. Throughout this lesson, you will work in Visual Studio Code, utilizing its integrated terminal and debugging tools to run and test your code.

Definitions & Explanations

Conditionals:

  • Overview:
    Conditionals enable your program to execute certain code blocks only if specific conditions are met. This decision-making capability is crucial for creating interactive and responsive programs.

  • Key Constructs:

    • if Statement:
      The if statement evaluates a condition (an expression that returns either True or False). If the condition is True, the code block under the if statement is executed.

    • elif Statement:
      Short for "else if," the elif statement allows you to check multiple conditions sequentially. If the initial if condition is not met, Python will evaluate the elif condition(s) in order.

    • else Statement:
      The else block is executed if none of the preceding conditions (if or any elif statements) are met. It serves as a fallback.

  • Example Concept:
    Consider a program that needs to respond differently based on whether a user-provided number is positive, negative, or zero. You would use conditionals to branch the logic accordingly.

Loops:

Loops enable your program to execute a block of code repeatedly. There are two main types of loops in Python:

  • For Loop:

    • Purpose: Iterates over a sequence such as a list, tuple, or range of numbers.

    • Usage: Often used when the number of iterations is known beforehand.

    • Syntax Example:

for i in range(1, 6):
    print(i)

This loop iterates from 1 to 5, printing each number.

  1. While Loop:

    • Purpose: Repeats a block of code as long as a given condition remains true.

    • Usage: Ideal when the number of iterations is not predetermined.

    • Syntax Example:

count = 1
while count <= 5:
    print(count)
    count += 1

This loop continues until the condition count <= 5 is no longer true.

  • Loop Control Statements:

    • break: Immediately exits the loop, regardless of the loop’s condition. Use this when a certain condition requires you to stop looping.

    • continue: Skips the remainder of the loop’s current iteration and proceeds with the next iteration. Use this when you want to bypass certain iterations based on a condition.

Understanding both conditionals and loops is essential for controlling the flow of your programs. With these tools, you can handle a wide variety of scenarios, from simple decision-making tasks to complex, iterative computations.

Example Code

Below are detailed examples that demonstrate both conditionals and loops. Open Visual Studio Code, create a new Python file (for example, lesson4_control_structures.py), and type the following code.

Example 1: Using Conditionals

# This program checks if a number is even or odd.

# Convert the user input to an integer using int()
number = int(input("Enter a number: "))

# Check if the number is even using the modulus operator %
if number % 2 == 0:
    print("The number is even.")
else:
    print("The number is odd.")

Explanation:

  • User Input Conversion:

    • The input() function captures user input as a string. We then use int() to convert it to an integer so that arithmetic operations can be performed.

  • Conditional Check:

    • The expression number % 2 == 0 checks if the remainder when number is divided by 2 is zero. If true, the number is even; otherwise, it is odd.

  • Output:

    • The appropriate message is printed based on whether the condition is met.

Example 2: Using For Loops

# This program uses a for loop to print numbers from 1 to 5.

# The range() function generates a sequence of numbers from 1 up to, but not including, 6.
for i in range(1, 6):
    print("Number:", i)

Explanation:

  • Range Function:

    • range(1, 6) creates a sequence of numbers starting at 1 and ending before 6.

  • Iteration:

    • The for loop iterates over each number in this sequence, and the print() function outputs each number preceded by the text "Number:".

Example 3: Using While Loops with Loop Control Statements

# This program demonstrates a while loop with break and continue.

# Initialize a counter variable.
count = 1

# The while loop runs as long as count is less than or equal to 10.
while count <= 10:
    # If count equals 5, skip printing this iteration using continue.
    if count == 5:
        count += 1  # Increment count before continuing.
        continue
    
    # If count is greater than 8, exit the loop early using break.
    if count > 8:
        break
    
    print("Current count is:", count)
    count += 1  # Increment the counter.

Explanation:

  • Loop Execution:

    • The loop continues as long as count is less than or equal to 10.

  • continue Statement:

    • When count equals 5, the continue statement skips the rest of the loop's body for that iteration, so the number 5 is not printed.

  • break Statement:

    • When count becomes greater than 8, the break statement terminates the loop immediately.

  • Incrementing the Counter:

    • It is crucial to increment count within the loop to ensure it eventually stops. Failing to do so could lead to an infinite loop.

Tasks

Now it’s time for you to apply what you’ve learned. Complete the following tasks in Visual Studio Code:

  1. Positive, Negative, or Zero Checker:

    • Create a new Python file (e.g., number_sign_checker.py).

    • Write a program that:

      • Asks the user to enter a number.

      • Uses an if-elif-else structure to determine whether the number is positive, negative, or zero.

      • Prints a message to the screen indicating the result.

    • Ensure you handle the input conversion properly (e.g., converting the input to an integer or float).

  2. Iterative Number Printer:

    • In a new Python file (e.g., print_numbers.py), write a program that:

      • Prompts the user to enter a number.

      • Uses a loop (choose between a for loop or a while loop) to print out numbers from 1 up to the absolute value of the entered number.

    • Experiment with both loop types to see which one feels more natural for this task.

    • Use the abs() function to handle negative numbers appropriately.

  3. Loop Control Experiment:

    • Modify the program from Task 2 to include the following:

      • Use a continue statement to skip printing multiples of a specific number (for example, skip printing numbers that are divisible by 3).

      • Use a break statement to exit the loop early if a particular condition is met (for instance, stop printing if the number exceeds a certain threshold).

    • Add comments to explain why you chose to use continue or break at those specific points in your code.

Recall Questions

Review and answer the following questions to reinforce the key concepts from this lesson:

  • What is the purpose of the if-elif-else structure?

    • Explain how this structure allows your program to choose different paths based on the evaluation of conditions.

  • How do for and while loops differ?

    • Describe the scenarios where you might prefer one loop type over the other and how they are structured.

  • When would you use break or continue in a loop?

    • Discuss the practical reasons for using break to exit a loop early or continue to skip certain iterations.

By the end of this lesson, you should feel comfortable using conditionals to control the flow of your program and employing loops to execute repetitive tasks efficiently. These concepts are the building blocks for creating dynamic and responsive applications. Continue experimenting with these control structures in Visual Studio Code to gain confidence in your coding abilities.

Previous
Previous

Python (Beginner) - Lesson 3: Variables, User Input, and Basic I/O

Next
Next

Python (Beginner) - Lesson 5: Functions and Modular Programming