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:
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
forloop to iterate over the elements in the
fruitslist. The variable
fruittakes on each element’s value in each iteration, and we print it.
- In example 2, we use a
whileloop to repeatedly execute the block of code as long as the condition
count < 5is true. We print the current value of
countand 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
Once you’ve completed the task, you can proceed to the next lesson.