Logo
Unit 8 – Python Control Structures: Loops

Python Control Structures: Loops

Duration: 5 minutes

Loops come in handy when we need to execute a chunk of code repeatedly. To tackle such recurring activities, Python has **‘for’ **and **‘while’ **loops.

For Loop

The **for** loop in Python is used to iterate over a sequence (such as a** list, tuple, dictionary,** set, or string) or other iterable objects. Example:

# Iterating over a list
fruits = ["apple""banana""cherry"]
for fruit in fruits:
print(fruit)

Here, the **fruit** variable goes through each element in the **fruits** list, printing each one in turn.

While Loop

The **while** loop in Python is used to execute a block of statements repeatedly until a given condition is true. When the condition becomes false, the line immediately after the loop is executed.

Example:

# Counting up
count = 1
while count <= 5:
print(count)
count += 1

Here, as long as the **count** variable is less than or equal to 5, it gets printed, and then **1 **is added to it.

Exercise

Now it’s your turn to practice loops! Write a Python program using a **for** loop to print the square of all numbers from 1 to 10. Then, using a **while** loop, create a countdown from 10 to 0.#### ConclusionLoops are essential control structures in Python, allowing for efficient repetition of code based on conditions and sequences. Becoming comfortable with these constructs will allow you to handle complex tasks with ease. Keep experimenting with different loop scenarios to enhance your proficiency!

Next Tutorial: Python Functions

5 minutes Minutes

Continue

Code on the Go with our Mobile App!

Unleash your coding potential anytime, anywhere!

Download Now!