Lesson 21/48 ยท ๐ Loops & Repetition
๐ Loops & RepetitionLesson 21/48
Phase 3 ยท Loops & Repetition25 min
For Loops, Doing Things Repeatedly
Stop copying and pasting, let loops do the repetitive work for you
Imagine you had to print the numbers 1 to 1000. You're not going to write 1000
print() statements. That's what loops are for, repeat an action many times without repeating your code.How would you approach this? Think first, then expand.
For loop basicspython
# Loop through a range of numbers
for i in range(5):
print(i)
# prints: 0, 1, 2, 3, 4
# range(start, stop)
for i in range(1, 6):
print(i)
# prints: 1, 2, 3, 4, 5๐Code TracerStep 1 / 9
trace.py
1fruits = ["apple", "banana", "cherry"]โ
2for fruit in fruits:
3 print(fruit)
Variables
No variables yet
Step 1 / 9
Loop through a listpython
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# prints: apple, banana, cherry`range(n)` generates numbers from 0 to n-1. `range(start, stop)` generates from start up to (not including) stop. `range(start, stop, step)`, step controls the increment.
Accumulator pattern, building a result in a looppython
# Sum all numbers from 1 to 10
total = 0
for i in range(1, 11):
total += i # same as: total = total + i
print(total) # 55The accumulator pattern (start with 0, add to it in a loop) solves dozens of problems: sum, count, build a string, find max/min, etc.
๐In the Real World...
Iterating over a list of servers to check health. Looping through pod names to find crashed ones. Processing each line in a log file. This pattern is the backbone of DevOps scripting.
Practice Exercises
0/3 solvedExercise 1 of 3easy
โฑ 00:00Sum 1 to N
Write a function
Example:
sum_to_n(n) that returns the sum of all integers from 1 to n (inclusive).Example:
sum_to_n(5) โ 15 (1+2+3+4+5)solution.py
1 / 3
Exercise 2 of 3easy
โฑ 00:00Multiplication Table
Write a function
Example output for
times_table(n) that prints the multiplication table for n, from 1 to 10.Example output for
times_table(3):`3 x 1 = 33 x 2 = 6...3 x 10 = 30`solution.py
2 / 3
Exercise 3 of 3easy
โฑ 00:00Only Even Numbers
Write a function
Example:
filter_evens(numbers) that returns a new list containing only the even numbers from the input list.Example:
filter_evens([1,2,3,4,5,6]) โ [2,4,6]solution.py
3 / 3
Solve all 3 exercises to unlock completion