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.
1# Simple if statement2age = 183if age >= 18:4 print("You are an adult")56# if-else statement7temperature = 258if temperature > 30:9 print("It's hot!")10else:11 print("It's not too hot")1213# if-elif-else chain14score = 8515if 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.
1# Iterate over a list2fruits = ["apple", "banana", "orange"]3for fruit in fruits:4 print(fruit)56# Using range()7for i in range(5): # 0 to 48 print(i)910# range() with start and stop11for i in range(2, 5): # 2 to 412 print(i)1314# range() with step15for i in range(0, 10, 2): # Even numbers 0 to 816 print(i)1718# Enumerate for index and value19for 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.
1# Simple while loop2count = 03while count < 5:4 print(count)5 count += 167# Break statement8number = 09while True:10 if number == 5:11 break12 print(number)13 number += 11415# Continue statement16for i in range(5):17 if i == 2:18 continue # Skip 219 print(i)
🎯 Practice Exercise
Try these exercises to practice control flow concepts:
1# 1. FizzBuzz2# Print numbers from 1 to 153# For multiples of 3, print "Fizz"4# For multiples of 5, print "Buzz"5# For multiples of both 3 and 5, print "FizzBuzz"67# 2. Password Checker8# Ask for password until correct one is entered9# Use while loop and break1011# 3. Pattern Printing12# Print this pattern:13# *14# * *15# * * *16# * * * *17# * * * * *
Related Tutorials
Learn how to create and use functions in Python.
Learn moreWork with sequences in Python.
Learn moreHandle errors and exceptions in Python.
Learn more