7. Range n
range() is a built-in function that produces a sequence of numbers. The one-argument form is:
stop— the number where the sequence stops. It is excluded.- The sequence starts at
0and moves by1, sorange(3)gives0,1,2. range()returns a range object, not a list. In aforloop you use it directly.
When you do not need the number itself, use _ as the loop variable by convention: for _ in range(3): means "repeat three times".
Coming from JavaScript? range(n) replaces the classic for (let i = 0; i < n; i++). The stop is excluded, and range is lazy, not an array.
Loop from zero
Loop over range(3) and print each number.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Start printing at one
Loop over range(5) and print each number plus 1.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Repeat a message
Use for _ in range(3) to print Hi three times. The name _ means the number itself is not used.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Print squares
Loop over range(4) and print each number squared with **.
Print exactly:
Create a free account to save your progress and unlock chapter 2.