ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

Python Tutorial• 5 min read

Python Loops & Conditionals

For loops, while loops, break, continue, and if-elif-else logic

Control flow structures dictate the order in which code statements are executed based on logical conditions.

Iterating with `for` and `range()`

A for loop is used for iterating over a sequence (list, tuple, dictionary, set, or string).

The range(start, stop, step) function generates numbers for iteration.

Loops and Conditions in Python
# Loop through range and calculate squares
squares = []
for n in range(1, 6):
    sq = n ** 2
    squares.append(sq)
    print(f"{n} squared is {sq}")

# List comprehension (Pythonic shorthand)
cubes = [x**3 for x in range(1, 6)]
print("Cubes:", cubes)
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

Which built-in function is commonly used to generate a sequence of numbers in a for loop?