Python

Chapter 6: Mastering Control Structures in Python

Mastering Control Structures in Python
Mastering Control Structures in Python

Control Structures in Python

Introduction

Control structures are a fundamental part of programming because they determine how a program makes decisions, repeats operations, and controls the order in which instructions are executed. Without control structures, a program would generally follow the same sequence of instructions every time. Python provides several useful structures that allow programs to respond to conditions, repeat tasks, and process collections efficiently.

In this chapter, we will focus on conditional statements such as if, elif, and else, loops such as for and while, and list comprehensions. We will also practice these concepts through ten coding questions covering FizzBuzz, factorials, grade calculation, digit sums, multiplication tables, filtering, prime numbers, common elements, and string reversal.

Chapter 6: Mastering Control Structures in Python

Conditional Statements: Making Decisions in Code

Conditional statements allow a Python program to execute different blocks of code depending on whether particular conditions are true or false. They provide the decision-making logic used in many programming tasks.

The if Statement

The if statement is the simplest form of a conditional statement in Python. It executes an indented block of code only when its condition evaluates to true.

age = 20

if age >= 18:
    print("You are an adult.")

Here, Python checks the value of age. Since the value is 20, the condition age >= 18 is true, so the message is displayed.

The elif Statement

When a program needs to test multiple conditions, the elif statement can be used after an if statement. The word elif means “else if.” Python checks an elif condition when the previous condition was false.

The else Statement

The else statement provides an alternative block that executes when none of the preceding conditions are true. It is useful when a program needs a final option for all remaining cases.

age = 16

if age >= 18:
    print("You are an adult.")
elif age >= 13:
    print("You are a teenager.")
else:
    print("You are a child.")

For an age of 16, the first condition is false, while the elif condition is true. Therefore, Python prints the teenager message. If both conditions were false, the else block would execute.

Loops: Repeating Actions in Code

Loops are used when a block of instructions needs to be executed repeatedly. They are particularly useful when processing multiple items in a collection or performing an operation several times.

The for Loop

The for loop is used to iterate over an iterable such as a list, tuple, string, or range. During each iteration, the loop variable receives the next available item.

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print(fruit)

The output is:

apple
banana
cherry

The loop processes each item in the fruits list and prints it. This makes the for loop useful whenever the program needs to perform an operation for every item in a collection.

The while Loop

The while loop continues executing its block as long as its condition remains true. It is useful when the number of iterations depends on a condition rather than being directly determined by a collection.

count = 1

while count <= 5:
    print("Count:", count)
    count += 1

The output is:

Count: 1
Count: 2
Count: 3
Count: 4
Count: 5

The value of count increases during each iteration. This eventually makes the condition false and stops the loop. Updating the condition-related value is important when using a while loop so that the loop can terminate.

List Comprehensions: Creating Lists

List comprehensions provide a concise way to create new lists from existing iterables. They can apply an expression to every item and can optionally include a condition to decide which items should be included.

Basic List Comprehension

The following example creates a list containing the squares of values from 0 to 9:

squares = [x**2 for x in range(10)]

print(squares)

The output is:

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

The expression goes through each value generated by range(10), calculates its square, and places the result into the new list.

List Comprehension with Conditions

A condition can be included in a list comprehension to filter the values that should appear in the resulting list.

even_squares = [x**2 for x in range(10) if x % 2 == 0]

print(even_squares)

The output is:

[0, 4, 16, 36, 64]

In this example, only even values satisfy the condition, so Python calculates and includes the squares of those values.

Coding Questions: Practice Control Structures

1. FizzBuzz Challenge

Write a Python program that prints numbers from 1 to 50. Print Fizz for multiples of three, Buzz for multiples of five, and FizzBuzz for numbers divisible by both three and five.

for num in range(1, 51):
    if num % 3 == 0 and num % 5 == 0:
        print("FizzBuzz")
    elif num % 3 == 0:
        print("Fizz")
    elif num % 5 == 0:
        print("Buzz")
    else:
        print(num)

2. Calculate Factorial

Write a Python function that calculates the factorial of a number using a while loop.

def factorial(n):
    result = 1

    while n > 0:
        result *= n
        n -= 1

    return result

print(factorial(5))  # Output: 120

3. List of Even Numbers

Use list comprehension to generate a list containing even numbers between 1 and 100.

even_numbers = [x for x in range(1, 101) if x % 2 == 0]

print(even_numbers)

4. Grade Calculator

Create a Python program that returns a letter grade according to the following scale: A for 90–100, B for 80–89, C for 70–79, D for 60–69, and F below 60.

def get_grade(score):
    if score >= 90:
        return "A"
    elif score >= 80:
        return "B"
    elif score >= 70:
        return "C"
    elif score >= 60:
        return "D"
    else:
        return "F"

score = 85

print(f"Score: {score}, Grade: {get_grade(score)}")

5. Sum of Digits

Write a Python program that takes a number and calculates the sum of its digits using a while loop.

def sum_of_digits(num):
    total = 0

    while num > 0:
        total += num % 10
        num //= 10

    return total

print(sum_of_digits(1234))  # Output: 10

6. Multiplication Table

Write a Python program that prints the multiplication table for a given number using a for loop.

def multiplication_table(n):
    for i in range(1, 11):
        print(f"{n} x {i} = {n * i}")

multiplication_table(5)

7. Filter Words by Length

Write a Python program using list comprehension to keep only the words that are longer than a specified length.

words = ["apple", "banana", "cherry", "date",
         "elderberry", "fig", "grape"]

length = 5

filtered_words = [word for word in words if len(word) > length]

print(filtered_words)
# Output: ['banana', 'cherry', 'elderberry']

8. Check Prime Number

Write a Python program that checks whether a number is prime using a for loop and conditional statements.

def is_prime(n):
    if n <= 1:
        return False

    for i in range(2, int(n**0.5) + 1):
        if n % i == 0:
            return False

    return True

print(is_prime(11))  # Output: True
print(is_prime(25))  # Output: False

9. Find Common Elements

Use list comprehension to find elements that occur in both lists.

list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]

common_elements = [x for x in list1 if x in list2]

print(common_elements)  # Output: [4, 5]

Complete Advance AI Topics: Click Here
SQL Tutorial:
Click Here
YT:- DecodeIT

10. Reverse a String

Write a Python program that reverses a string using a for loop.

def reverse_string(s):
    reversed_s = ""

    for char in s:
        reversed_s = char + reversed_s

    return reversed_s

print(reverse_string("hello"))  # Output: "olleh"

Why Control Structures Matter

Control structures allow Python programs to respond to data and conditions rather than always following exactly the same sequence of instructions. Conditional statements provide decision-making capabilities, loops automate repetitive operations, and list comprehensions offer a compact approach for creating filtered or transformed lists.

These features can also be combined within the same program. For example, a loop can process a collection while an if statement checks each item. A list comprehension can then create a new collection containing only values that satisfy a particular condition. Practicing these combinations helps learners understand how program logic works.

Conclusion

Control structures are a core part of Python programming. The if, elif, and else statements provide decision-making capabilities, while for and while loops handle repeated operations. List comprehensions provide a concise way to construct lists and apply conditions to selected values.

The ten practice problems in this chapter provide hands-on opportunities to apply these concepts. By working through problems such as FizzBuzz, factorial calculation, grade classification, digit sums, prime checking, and string reversal, learners can improve their understanding of Python program flow.

Regular practice with conditions, loops, and comprehensions will make it easier to design programs that respond to different situations and process data efficiently. These concepts form an important foundation for progressing toward more advanced Python programming.

Frequently Asked Questions

1. What are control structures in Python?

Control structures are programming constructs that control the flow and execution of Python code. Conditional statements and loops are common examples.

2. What is the purpose of an if statement?

An if statement executes a block of code when its specified condition evaluates to true.

3. When should elif be used?

elif is used when a program needs to test an additional condition after a previous if or elif condition is false.

4. What is the difference between for and while loops?

A for loop commonly iterates over an iterable, while a while loop continues as long as its condition remains true.

5. What is list comprehension in Python?

List comprehension is a concise syntax for creating a new list by applying an expression to items in an iterable, optionally using a condition.

6. Why is count += 1 used in the while loop example?

It changes the value of count during each iteration so that the loop condition eventually becomes false.

7. What is the FizzBuzz problem?

FizzBuzz is a programming exercise where numbers are checked for divisibility by three and five, with specific words printed for the matching conditions.

8. Can conditional statements and loops be used together?

Yes. A loop can process multiple values while conditional statements determine what should happen to each value.

Keywords: Chapter 6 Mastering Control Structures in Python, Control Structures in Python, Python control structures, Python if statement, Python elif else, Python for loop, Python while loop, Python list comprehension, Python coding questions, Python control flow, Python practice programs

Source Code Available

Interested in This Project?

Get the complete source code for this project at a very affordable price — perfect for your portfolio, college submission, or learning. Message us on WhatsApp and we'll get back to you instantly!

Full source code included Step-by-step setup guide Instant delivery on WhatsApp Instant reply on WhatsApp
Chat on WhatsApp

We usually reply within a few minutes

Leave a Reply

Your email address will not be published. Required fields are marked *

Chat with us