Progress0%

5 of 20 topics completed

Control Flow in Python

Control flow statements determine the order in which program instructions are executed. In this tutorial, you'll learn about if statements, loops, and other control structures in Python.

Quick Overview

If Statements

Make decisions in your code based on conditions

Loops

Repeat code blocks with for and while loops

Control Statements

Control loop execution with break and continue

If Statements

If statements allow you to execute different code blocks based on conditions. They're fundamental for creating decision-making logic in your programs.

Python
1# Simple if statement
2age = 18
3if age >= 18:
4 print("You are an adult")
5
6# if-else statement
7temperature = 25
8if temperature > 30:
9 print("It's hot!")
10else:
11 print("It's not too hot")
12
13# if-elif-else chain
14score = 85
15if score >= 90:
16 grade = "A"
17elif score >= 80:
18 grade = "B"
19elif score >= 70:
20 grade = "C"
21else:
22 grade = "F"
23print(f"Your grade is {grade}")

For Loops

For loops are used to iterate over sequences like lists, tuples, and strings. They provide a clean way to repeat code for each item in a collection.

Python
1# Iterate over a list
2fruits = ["apple", "banana", "orange"]
3for fruit in fruits:
4 print(fruit)
5
6# Using range()
7for i in range(5): # 0 to 4
8 print(i)
9
10# range() with start and stop
11for i in range(2, 5): # 2 to 4
12 print(i)
13
14# range() with step
15for i in range(0, 10, 2): # Even numbers 0 to 8
16 print(i)
17
18# Enumerate for index and value
19for index, fruit in enumerate(fruits):
20 print(f"{index}: {fruit}")

While Loops

While loops repeat a block of code as long as a condition is true. They're perfect for situations where you don't know how many iterations you'll need.

Python
1# Simple while loop
2count = 0
3while count < 5:
4 print(count)
5 count += 1
6
7# Break statement
8number = 0
9while True:
10 if number == 5:
11 break
12 print(number)
13 number += 1
14
15# Continue statement
16for i in range(5):
17 if i == 2:
18 continue # Skip 2
19 print(i)

🎯 Practice Exercise

Try these exercises to practice control flow concepts:

Python
1# 1. FizzBuzz
2# Print numbers from 1 to 15
3# For multiples of 3, print "Fizz"
4# For multiples of 5, print "Buzz"
5# For multiples of both 3 and 5, print "FizzBuzz"
6
7# 2. Password Checker
8# Ask for password until correct one is entered
9# Use while loop and break
10
11# 3. Pattern Printing
12# Print this pattern:
13# *
14# * *
15# * * *
16# * * * *
17# * * * * *

Related Tutorials

Learn how to create and use functions in Python.

Learn more

Work with sequences in Python.

Learn more

Handle errors and exceptions in Python.

Learn more