Lesson 8: for
Loops and range()
Topics Covered:
- Understanding
for
loops - Using the
range()
function - Looping through lists and strings
What is a for
Loop?
A for
loop repeats a block of code a specific number of times or over a sequence.
for i in range(5):
print("Hello!")
Using range()
range()
generates numbers:
for i in range(1, 6):
print(i)
range(start, stop)
starts at the first number and ends just before the second number.
Counting with Steps
for i in range(0, 10, 2):
print(i) # Prints even numbers from 0 to 8
Looping Through a List
animals = ["cat", "dog", "bird"]
for animal in animals:
print("I like", animal)
Looping Through a String
word = "Python"
for letter in word:
print(letter)
Activity: Print Numbers
Print all numbers from 1 to 10 and say if they are even or odd:
for num in range(1, 11):
if num % 2 == 0:
print(num, "is even")
else:
print(num, "is odd")
Challenge
- Ask the user for a number.
- Print a multiplication table up to 10 for that number.
num = int(input("Enter a number: "))
for i in range(1, 11):
print(num, "x", i, "=", num * i)