0
0
Pythonprogramming~5 mins

Why loops are needed in Python

Choose your learning style9 modes available
Introduction

Loops help us repeat actions many times without writing the same code again and again. They save time and make programs shorter and easier to read.

When you want to print numbers from 1 to 10.
When you need to check every item in a shopping list.
When you want to add up all the scores in a game.
When you want to keep asking a user for input until they give a correct answer.
Syntax
Python
for item in collection:
    # do something with item

while condition:
    # do something while condition is true

for loop repeats for each item in a list or group.

while loop repeats as long as a condition stays true.

Examples
This prints numbers 0 to 4, one on each line.
Python
for number in range(5):
    print(number)
This prints 'Hello' three times using a while loop.
Python
count = 0
while count < 3:
    print('Hello')
    count += 1
Sample Program

This program uses a for loop to say what fruits we like, one by one.

Python
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
    print(f'I like {fruit}')
OutputSuccess
Important Notes

Loops help avoid repeating code and make programs easier to change.

Be careful with while loops to make sure they stop eventually, or the program will run forever.

Summary

Loops repeat actions to save time and code.

Use for loops to go through items in a list.

Use while loops to repeat while a condition is true.