Skip to content

Control Flow in Python

Shaswat Raj edited this page Dec 17, 2024 · 1 revision

Python One-Shot for Beginners 2025: Control Flow in Python

Welcome to Section 4 of the Python One-Shot for Beginners 2025! In this section, we will cover how to control the flow of your Python programs using if statements, else statements, and loops. These concepts are vital for making decisions, repeating actions, and creating interactive programs.


1. If Statements and Conditions

An if statement lets your program make decisions based on certain conditions. You can control whether a block of code runs or not based on boolean expressions (True or False).

Syntax:

if condition:
    # Code to run if the condition is True

Example:

age = int(input("Enter your age: "))

if age >= 18:
    print("You are an adult!")
else:
    print("You are a minor!")

In this example:

  • If the user's age is 18 or older, the program prints "You are an adult!".
  • If the age is less than 18, it prints "You are a minor!".

Common Mistakes to Avoid:

  • Missing Colon: Always remember to add a colon (:) at the end of the if or else statement.
  • Indentation: Python relies on indentation to define code blocks. Make sure your code inside the if and else statements is indented correctly.

2. Elif Statements (Else If)

You can check multiple conditions using the elif keyword. If the first condition is not met, Python will check the next condition in the elif statement.

Syntax:

if condition1:
    # Code if condition1 is True
elif condition2:
    # Code if condition2 is True
else:
    # Code if none of the above conditions are True

Example:

age = int(input("Enter your age: "))

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

In this example:

  • The program first checks if the user is 18 or older.
  • If not, it checks if the user is 13 or older.
  • If neither condition is true, it prints "You are a child!"

Order of Conditions:

  • The order of conditions matters. Python will check each condition in sequence. If the first condition is true, the rest of the conditions won’t be checked.

3. Loops: Repeating Actions

Loops allow you to repeat code multiple times, which is essential for handling repetitive tasks.

For Loop

A for loop is used to iterate over a sequence (such as a list, range, or string). It's great for repeating an action a specific number of times.

Syntax:

for variable in sequence:
    # Code to repeat

Example:

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

This loop runs 5 times, printing the numbers from 0 to 4.

While Loop

A while loop repeats a block of code as long as a condition is True.

Syntax:

while condition:
    # Code to repeat

Example:

count = 0
while count < 5:
    print("Count is:", count)
    count += 1  # Increment to avoid infinite loop

In this example, the loop continues until count reaches 5.


Common Mistake: Infinite Loops

An infinite loop happens when the loop's condition never becomes False, causing the loop to run forever.

Example of an Infinite Loop:

while True:
    print("This will never stop!")

How to Fix It:

Make sure you modify the condition inside the loop to eventually become False. You can use a break statement to stop the loop if necessary.


4. Nested If Statements and Loops

You can also nest if statements inside each other or place a loop inside an if statement. This is useful for more complex conditions and repetitive tasks.

Example of Nested If Statements:

age = int(input("Enter your age: "))

if age >= 18:
    print("You are an adult!")
    if age >= 21:
        print("You can also drink alcohol!")
    else:
        print("But you cannot drink alcohol yet.")
else:
    print("You are a minor!")

In this example:

  • If the user is 18 or older, we check if they are 21 or older to determine if they can drink alcohol.

5. Practice Exercises

Exercise 1: Age Categorization

Write a program that asks for the user's age and:

  1. Prints if they are eligible to vote (18 or older).
  2. Prints if they are eligible to drive (16 or older).

Exercise 2: Number Sign

Write a program that checks if a number entered by the user is:

  1. Positive
  2. Negative
  3. Zero

Exercise 3: Number Guessing Game (Using Loops)

Create a Guess the Number game where the user has to guess a number between 1 and 10. The program should give feedback based on whether the guess is correct or incorrect. Use a loop to allow the user to keep guessing until they get it right.


6. Key Takeaways

  • If Statements help you make decisions in your program based on conditions.
  • Elif lets you check for multiple conditions.
  • Loops allow you to repeat actions multiple times using for or while loops.
  • Nested Statements and Loops help handle complex logic.

7. What's Next?

Now that you understand control flow, you're ready to handle more complex logic in your programs. In the next section, we'll dive into functions—a way to group your code into reusable blocks to make your programs more organized and efficient.


Summary

This section has equipped you with the foundational skills of controlling the flow of your Python programs using conditions and loops. By mastering these concepts, you can start making your programs more dynamic and interactive, responding to user input and repeating tasks when necessary.

Stay tuned for the next section, where we will tackle functions and learn how to structure our code for better readability and reuse.