Skip to content

Latest commit

 

History

History
33 lines (21 loc) · 1.13 KB

005.md

File metadata and controls

33 lines (21 loc) · 1.13 KB

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.