Using the range() Function
The range() function is commonly used with for loops to generate a sequence of numbers.
Examples:
range(5) → Counts from 0 to 4 (5 numbers).
range(1, 6) → Counts from 1 to 5.
range(1, 10, 2) → Counts from 1 to 9, skipping by 2.
Code Example:
for number in range(1, 10, 2):
print(number)
Output:
1
3
5
7
9
A for loop can iterate through items in a list.
Example:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
A for loop can iterate through characters in a string.
Example:
word = "Python"
for letter in word:
print(letter)
Output:
P
y
t
h
o
n
Exercise 1: Count to 10
Write a for loop to print numbers from 1 to 10.
Exercise 2: Favorite Colors
Create a list of three favorite colors. Use a for loop to print each color.
Exercise 3: Multiplication Table
Write a program that uses a for loop to print the multiplication table for 5.
Exercise 4: Sum of Numbers
Write a program that calculates the sum of all numbers from 1 to 100 using a for loop.
Exercise 5: Count Characters
Write a program that counts the number of vowels in a string.
Write a program that asks the user to enter 5 numbers, one at a time, and stores them in a list. Use a for loop to calculate and print the average of the numbers.
You’ve learned the basics of for loops and how to use them with sequences like lists, strings, and ranges. Keep practicing to build your Python skills further! 🎉