Intro to Computer Science / Unit 6: Loops
6.1 For Loops and range()
Notes
A loop repeats code. A for loop runs once for each item in a sequence. The range() function makes a sequence of numbers.
range(5)gives 0, 1, 2, 3, 4 (starts at 0, stops before 5).range(2, 6)gives 2, 3, 4, 5.range(0, 10, 3)gives 0, 3, 6, 9 (the third number is the step).
for i in range(3):
print("Hello", i)
- This prints
Hello 0,Hello 1,Hello 2on separate lines: 3 repetitions.
Practice
How many times does
for i in range(4): print(i) run its body?range(4) produces 0, 1, 2, 3, which is 4 values.
Which values does
range(1, 5) produce?It starts at 1 and stops before 5.
What does
for n in range(10, 0, -3): print(n) print?Counting down by 3 from 10 gives 10, 7, 4, 1 and stops before reaching 0.
Ready for more? Take the Unit 6 test.