TutorialsPythonControl Flow
Share:

Control Flow

intermediate

Part of Core Python

Theory

Control flow determines the order in which code executes. Python provides conditional statements and loops to create dynamic, decision-making programs.

Conditional statements use if, elif, and else to execute code based on conditions:

if condition:
    # code if condition is True
elif other_condition:
    # code if other_condition is True
else:
    # code if no conditions are met

Comparison operators compare values: ==, !=, >, <, >=, <=. Logical operators combine conditions: and, or, not.

Truthy and falsy values: In Python, values are considered True or False in a boolean context. Falsy values include None, False, 0, 0.0, empty strings "", empty lists [], empty tuples (), empty dicts {}, and empty sets set(). Everything else is truthy.

while loops repeat code as long as a condition remains True. Be careful to avoid infinite loops — ensure the condition can become False.

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

for loops iterate over sequences. Use range() to generate numeric sequences:

  • range(stop) — 0 to stop-1
  • range(start, stop) — start to stop-1
  • range(start, stop, step) — with custom step
for i in range(5):
    print(i)  # 0, 1, 2, 3, 4
 
for item in ["a", "b", "c"]:
    print(item)

Loop control statements:

  • break — exits the loop immediately
  • continue — skips the rest of the current iteration
  • pass — does nothing (placeholder)

Loops can also have an else clause, which executes when the loop completes normally (not via break).

Nested loops place one loop inside another. The inner loop runs completely for each iteration of the outer loop.

Practical Examples

Example 1: Conditionals and Logical Operators
python
Example 2: Loops and Control Statements
python

Exercises

Even or Odd Checker

easy

Write a program that asks the user for a number using input(). Check if the number is even or odd using the modulo operator (%). Print an appropriate message. Also check if it's divisible by 5.

Starter Code:

num = int(input('Enter a number: '))\n# Your code here

Expected Output:

Enter a number: 15\n15 is odd\n15 is divisible by 5

Number Guessing Game

medium

Write a program that picks a random number between 1 and 20 using import random; secret = random.randint(1, 20). The user gets 5 attempts to guess it. Give hints like 'Too high' or 'Too low'. Use a while loop with a counter.

Starter Code:

import random\nsecret = random.randint(1, 20)\nattempts = 0\n# Your game logic here

Expected Output:

Guess the number (1-20): 10\nToo low!\nGuess the number (1-20): 15\nToo high!\nGuess the number (1-20): 12\nCorrect! It took you 3 attempts.

FizzBuzz Challenge

medium

Print numbers from 1 to 50. For multiples of 3, print 'Fizz' instead of the number. For multiples of 5, print 'Buzz'. For multiples of both 3 and 5, print 'FizzBuzz'. Use a for loop with range() and if-elif-else.

Starter Code:

for num in range(1, 51):\n  # Your code here

Expected Output:

1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz ...

Mini Quiz

Mini Quiz

Mini Project

Mini Project: Simple ATM Simulator

Create an ATM simulation program that handles deposits, withdrawals, and balance checks using control flow.

Requirements:

    Bonus Challenge

    Add a history feature that stores all transactions and prints them on request.