Loops are used to repeatedly execute a block of code. They are essential for performing repetitive tasks and iterating over collections of data. In Python, we have two types of loops: for
and while
.
Let's explore how to use loops in Python:
# Example 1: for loop
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(fruit)
# Example 2: while loop
count = 0
while count < 5:
print("Count:", count)
count += 1
- In example 1, we use a
for
loop to iterate over the elements in thefruits
list. The variablefruit
takes on each element's value in each iteration, and we print it. - In example 2, we use a
while
loop to repeatedly execute the block of code as long as the conditioncount < 5
is true. We print the current value ofcount
and increment it by 1 in each iteration.
Now it's time for a practical task:
Write a Python program that prompts the user to enter a positive integer and prints all the numbers from 1 to that integer using a for
loop.
Once you've completed the task, you can proceed to the next lesson.