Control Flow – Conditional Statements & Loops

Introduction

Control flow is a fundamental concept in programming that determines the execution order of statements. In Python, control flow is managed using conditional statements and loops. These structures allow you to make decisions in your code and repeat tasks efficiently.

By the end of this module, you will understand how to use if-else statements for decision-making, for and while loops for iteration, and loop control statements like break, continue, and pass. You will also apply these concepts in a fun Number Guessing Game project!


Conditional Statements

Conditional statements allow the program to execute different blocks of code based on certain conditions.

if Statement

The if statement executes a block of code only if a specified condition is True.

age = 18
if age >= 18:
    print("You are eligible to vote.")

if-else Statement

The if-else statement allows two possible execution paths: one for when the condition is True, and another when it is False.

age = 16
if age >= 18:
    print("You are eligible to vote.")
else:
    print("You are not eligible to vote.")

if-elif-else Statement

When multiple conditions need to be checked, we use elif (short for else if).

score = 85
if score >= 90:
    print("Grade: A")
elif score >= 80:
    print("Grade: B")
elif score >= 70:
    print("Grade: C")
else:
    print("Grade: F")

Nested if Statements

if statements can be nested within each other to check multiple conditions.

num = 10
if num > 0:
    if num % 2 == 0:
        print("Positive even number")
    else:
        print("Positive odd number")

Logical Operators in Conditions

Python provides logical operators to combine multiple conditions:

  • and – Returns True if both conditions are true.
  • or – Returns True if at least one condition is true.
  • not – Reverses the boolean value.
age = 20
has_id = True
if age >= 18 and has_id:
    print("Allowed to enter.")

Common Mistakes to Avoid

  • Forgetting colons (:) at the end of if, elif, and else statements.
  • Misusing indentation (Python relies on indentation to define blocks).
  • Using = instead of == in conditions.
  • Not covering all possible cases when using multiple conditions.

Loops in Python

Loops are used to execute a block of code multiple times, reducing redundancy and improving efficiency.

for Loop

The for loop is used to iterate over a sequence (list, tuple, string, etc.).

for i in range(5):
    print("Iteration:", i)

Looping Through a List

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

Looping Through a String

word = "Python"
for letter in word:
    print(letter)

while Loop

The while loop executes as long as a given condition is True.

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

Using while with User Input

password = "secure123"
user_input = ""
while user_input != password:
    user_input = input("Enter password: ")
print("Access granted!")

Loop Control Statements

  • break: Exits the loop prematurely.
  • continue: Skips the current iteration and moves to the next one.
  • pass: Does nothing and is used as a placeholder.
for num in range(10):
    if num == 5:
        break  # Exits the loop
    print(num)
for num in range(10):
    if num == 5:
        continue  # Skips this iteration
    print(num)

Best Practices for Using Loops

  • Ensure while loops have an exit condition to prevent infinite loops.
  • Use break sparingly to maintain readability.
  • Use list comprehensions where possible to simplify loops.
  • Optimize loop conditions to prevent unnecessary iterations.

Mini Project: Number Guessing Game

Project Steps:

  1. Generate a random number.
  2. Ask the user to guess the number.
  3. Give hints if the guess is too high or too low.
  4. Repeat until the user guesses correctly.
  5. Provide an option to play again.

Code Example:

import random

def play_game():
    secret_number = random.randint(1, 100)
    guess = None
    attempts = 0

    while guess != secret_number:
        try:
            guess = int(input("Guess the number (1-100): "))
            attempts += 1
            if guess < secret_number:
                print("Too low! Try again.")
            elif guess > secret_number:
                print("Too high! Try again.")
            else:
                print(f"Congratulations! You guessed it right in {attempts} attempts.")
        except ValueError:
            print("Invalid input! Please enter a number.")

while True:
    play_game()
    replay = input("Do you want to play again? (yes/no): ").strip().lower()
    if replay != 'yes':
        print("Thanks for playing! Goodbye!")
        break

Enhancements & Challenges:

✅ Limit the number of attempts and display a message if the user runs out of tries.
✅ Allow the user to choose a difficulty level (Easy: 10 attempts, Hard: 5 attempts).
✅ Provide a hint feature that tells if the guess is within 10 numbers of the secret number.
✅ Implement a scoring system based on the number of attempts.
✅ Add a leaderboard to track top scores.


Conclusion

Control flow structures like conditional statements and loops allow programs to make decisions and perform repetitive tasks efficiently. Mastering these concepts is essential for writing complex programs.

🚀 Next Up: We will explore Functions and Modules in Python!