Exploring "For" Loops
In this step, you will learn about "for" loops, which are used to iterate over sequences (like lists, strings, or ranges) in Python.
Let's start with a simple for loop using a range. In the Python interpreter, type:
for i in range(5):
print(i)
Output:
0
1
2
3
4
The range(5) function generates a sequence of numbers from 0 to 4, and the loop iterates over each number.
range() can take multiple arguments to specify the start, end, and step values. Let's try a different range:
for i in range(1, 10, 2):
print(i)
Output:
1
3
5
7
9
- The
range(1, 10, 2) function generates a sequence of numbers starting from 1, up to (but not including) 10, with a step of 2.
Now, let's iterate over a list:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I like {fruit}")
Output:
I like apple
I like banana
I like cherry
Here, the loop iterates over each item in the fruits list.
You can also use for loops with strings:
for char in "Python":
print(char.upper())
Output:
P
Y
T
H
O
N
This loop iterates over each character in the string "Python".
Let's combine a "for" loop with conditional statements:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for num in numbers:
if num % 2 == 0:
print(f"{num} is even")
else:
print(f"{num} is odd")
Output:
1 is odd
2 is even
3 is odd
4 is even
5 is odd
6 is even
7 is odd
8 is even
9 is odd
10 is even
This loop checks each number in the list and prints whether it's even or odd.
Understanding the modulo operator (%): The % symbol is called the modulo operator (or modulus operator). It returns the remainder when one number is divided by another. For example:
5 % 2 equals 1 (because 5 divided by 2 is 2 with a remainder of 1)
4 % 2 equals 0 (because 4 divided by 2 is 2 with no remainder)
10 % 3 equals 1 (because 10 divided by 3 is 3 with a remainder of 1)
When we check num % 2 == 0, we're asking: "Does dividing this number by 2 leave a remainder of 0?" If the answer is yes (the remainder equals 0), then the number is even. If the remainder is 1 (or any other number), then the number is odd. The == is the equality comparison operator that checks if two values are equal, returning True if they are and False if they are not.