Python Guide Sidebar

Control Flow in Python: Everything You Need to Know

Control flow refers to the order in which individual statements, instructions, or function calls are executed or evaluated in a program. In Python, control flow is governed by conditional statements, loops, and function calls.

Table of Contents

  1. What is Control Flow?
  2. Conditional Statements
    • if, elif, else
  3. Loops
    • for Loop
    • while Loop
    • break, continue, and else in Loops
  4. Handling Exceptions with try and except
  5. The pass Statement
  6. Mini-Project: Number Guessing Game
  7. Common Pitfalls and Best Practices
  8. Interview Questions and Answers (Google, Amazon, TCS, Infosys, Zoho)

1. What is Control Flow?

Control flow in programming refers to the sequence in which individual statements and instructions are executed. In Python, you can control the flow using:

  • Conditional statements: To decide which actions to take based on conditions.
  • Loops: To repeat actions multiple times.
  • Function calls: To break the program into smaller, reusable pieces of code.

2. Conditional Statements

Conditional statements allow you to execute code based on whether a condition is True or False.

a) if Statement

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

Syntax:

if condition:
# Code to execute if condition is True

Example:

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

b) elif and else Statements

  • elif is short for “else if” and is used to check multiple conditions.
  • else is used to execute a block of code when the condition is False.

Syntax:

if condition1:
# Code if condition1 is True
elif condition2:
# Code if condition2 is True
else:
# Code if no conditions are True

Example:

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

3. Loops

Loops allow you to execute a block of code multiple times.

a) for Loop

The for loop is used to iterate over a sequence (such as a list, tuple, string, or range).

Syntax:

for item in sequence:
# Code to execute for each item in sequence

Example:

for i in range(5):
    print(i)

This prints:

0
1
2
3
4

b) while Loop

The while loop repeats as long as the condition is True.

Syntax:

while condition:
# Code to execute while condition is True

Example:

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

c) break, continue, and else in Loops

  • break: Exits the loop.
  • continue: Skips the current iteration and moves to the next one.
  • else: Executes a block of code when the loop finishes (without a break).

Example:

for i in range(10):
    if i == 5:
        break  # Exit the loop when i equals 5
    print(i)
else:
    print("Loop completed.")

This will print:

0
1
2
3
4

Example with continue:

for i in range(5):
    if i == 2:
        continue  # Skip the iteration when i equals 2
    print(i)

This will print:

0
1
3
4

4. Handling Exceptions with try and excep

Python provides error handling through try, except, and finally blocks. This allows your program to continue executing even if an error occurs.

Syntax:

try:
# Code that might cause an error
except ErrorType:
# Code to handle the error
finally:
# Code that runs regardless of an exception

Example:

try:
    num = int(input("Enter a number: "))
    result = 10 / num
except ValueError:
    print("Invalid input! Please enter a valid number.")
except ZeroDivisionError:
    print("You cannot divide by zero.")
finally:
    print("Execution finished."

5. The pass Statement

The pass statement is a placeholder that allows you to define an empty block of code. It is often used when you want to create an empty function or loop that you plan to implement later.

Example:

def my_function():
    pass  # Function implementation goes here

6. Mini-Project: Number Guessing Game

Let’s create a simple number guessing game using control flow statements.

Objective:

The program will randomly pick a number between 1 and 100, and the player will have to guess it. The game will provide feedback on whether the guess is too high or too low.

import random

# Generate a random number between 1 and 100
number_to_guess = random.randint(1, 100)
attempts = 0

print("Welcome to the Number Guessing Game!")
print("Guess the number between 1 and 100.")

while True:
    guess = int(input("Enter your guess: "))
    attempts += 1

    if guess < number_to_guess:
        print("Too low! Try again.")
    elif guess > number_to_guess:
        print("Too high! Try again.")
    else:
        print(f"Congratulations! You've guessed the number in {attempts} attempts.")
        break

Sample Output:

Welcome to the Number Guessing Game!
Guess the number between 1 and 100.
Enter your guess: 50
Too low! Try again.
Enter your guess: 75
Too high! Try again.
Enter your guess: 60
Congratulations! You've guessed the number in 3 attempts.

7. Common Pitfalls and Best Practices

Pitfall 1: Infinite Loops

  • Issue: Forgetting to modify the loop condition may result in an infinite loop.
  • Solution: Always ensure the condition in the loop is eventually met to stop the loop.

Pitfall 2: Misuse of break in for loops

  • Issue: Using break prematurely may cause the loop to exit without completing its intended iterations.
  • Solution: Use break only when necessary.

Best Practice: Use Clear Conditions

Ensure your conditions in if, while, and for statements are clear and logically correct.


Interview Questions and Answers


Google

Q: What is the difference between if and elif statements?
A: if checks the first condition, and if it’s True, it runs the associated block. elif is used to check multiple conditions if the initial if is False. You can have multiple elif statements, but only one if.

Amazo

Q: Write a Python program to find the largest number in a list.
A:

numbers = [3, 5, 2, 8, 1]
largest = max(numbers)
print(f"The largest number is {largest}.")

TCS

Q: How can you exit a while loop in Python?
A: Use the break statement to exit the loop based on a condition.

Infosys

Q: What will happen if the else block is used with a while loop?
A: The else block will execute after the loop finishes iterating (i.e., if the loop condition becomes False) unless the loop is terminated by break.

Zoho

Q: Write a Python program that prints numbers from 1 to 10, but skips the number 5.
A:

for i in range(1, 11):
    if i == 5:
        continue
    print(i)

Conclusion

Mastering control flow in Python is essential for writing efficient, flexible, and readable code. By understanding and utilizing conditional statements, you can ensure your program reacts to different situations accordingly. Furthermore, with loops, you can handle repetitive tasks effectively, saving both time and effort. In addition, error handling allows your program to deal with unexpected situations gracefully. As a result, these control structures enable you to create interactive, user-friendly programs that can respond intelligently to various inputs, ultimately improving the overall user experience.

Control flow