Lesson 5: Loops (for and while)

Jun 18, 2023 | Uncategorized | 0 comments

Home 9 Uncategorized 9 Lesson 5: Loops (for and while)

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

Explanation:

  • In example 1, we use a for loop to iterate over the elements in the fruits list. The variable fruit 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 condition count < 5 is true. We print the current value of count and increment it by 1 in each iteration.

Now it’s time for a practical task:

Task 5:

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.

Join The FFF Newsletter

Future Flow Forecast

Future Flow Forecast

Joinย the number one AI newsletter and learn how to be at the forefront of the latest discoveries. This is your "dotcom bubble" chance!

You have Successfully Subscribed!