Intro to for Loops in Python
5.1 Introduction
Loops are one of the fundamental concepts in programming. They allow us to repeat actions multiple times without writing repetitive code. In Python, the for loop is one of the most commonly used looping structures.
In this lesson, we will learn:
- The basic syntax of a
forloop. - How to iterate over lists and other iterable objects.
- The
range()function and its uses. - Nested loops and loop control statements.
5.2 - Loops
A loop is a way to execute a block of code multiple times. In Python, the for loop is used to iterate over a sequence (such as a list, tuple, dictionary, or string).
Basic Syntax of a for Loop:
for item in iterable:
# Code to execute
The for loop goes through each item in the iterable and executes the block of code inside it.
Example:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
5.3 - The range() Function
Sometimes, we need to loop a specific number of times instead of iterating through a list. This is where the range() function comes in.
The range() function generates a sequence of numbers, which we can iterate over.
Using range():
for i in range(5):
print(i)
Output:
0
1
2
3
4
Using range(start, stop, step):
for i in range(1, 10, 2):
print(i)
Output:
1
3
5
7
9
5.4 - Processing Lists
We can use for loops to iterate over lists and perform operations on their elements.
Example: Squaring numbers in a list
numbers = [1, 2, 3, 4, 5]
for num in numbers:
print(num ** 2)
Output:
1
4
9
16
25
Example: Creating a new list with modified values
numbers = [1, 2, 3, 4, 5]
squared_numbers = [num ** 2 for num in numbers]
print(squared_numbers)
Output:
[1, 4, 9, 16, 25]
5.5 - Conclusion
The for loop is a powerful tool that allows us to iterate over sequences easily. We learned how to use it with lists and the range() function to perform repetitive tasks efficiently.
Exercise: Try It Yourself!
- Write a
forloop to print numbers from 10 to 1 in reverse order. - Create a list of colors (
red,blue,green) and use aforloop to print each color in uppercase. - Write a
forloop to print only even numbers between 1 and 20. - Use the
range()function to generate a list of numbers from 5 to 50, incrementing by 5.