Nearby lessons
43 of 159Python - For Loop
- Define the for loop and the sequences it can iterate over
- Understand the three forms of the range() function
- Use range(n) to generate numbers from 0 to n-1
- Use range(begin, end) to print a range of numbers
- Use range(begin, end, step) to print even, odd and reverse-order numbers
What is a for Loop?
If we want to execute a group of statements for every element present in a sequence, we use the for loop.
A sequence can be a string, list, tuple, set, range, or dictionary.
Syntax of for Loop
Another Syntax
Flow of for Loop
- Take the first element from the sequence.
- Execute the loop body.
- Take the next element.
- Repeat until all elements are processed.
- When there are no more elements, the loop stops.
range() Function
The range() function is used to generate a sequence of numbers.
It returns a range object.
Three Forms of range()
| Form | Description |
|---|---|
range(n) |
Generates numbers from 0 to n-1. |
range(begin, end) |
Generates numbers from begin to end-1. |
range(begin, end, step) |
Generates numbers using the specified step value. |
Form 1 - range(n)
This form generates numbers from 0 to n-1.
Example 1 - Print Numbers from 0 to 9
Explanation
range(10) generates numbers from 0 to 9.
The value 10 is not included.
Example 2 - Print "Hello" 5 Times
Form 2 - range(begin, end)
This form generates numbers from begin to end-1.
Example 1 - Print Numbers from 10 to 20
Explanation
The starting value is included.
The ending value is excluded.
Therefore, range(10, 21) prints numbers from 10 to 20.
Example 2 - Print Numbers from 1 to 10
Example 3 - Print Numbers from 5 to 10
Form 3 - range(begin, end, step)
The third argument specifies the increment or decrement.
Example 1 - Print Even Numbers
Explanation
The value increases by 2 after every iteration.
Only even numbers are printed.
Example 2 - Print Odd Numbers
Example 3 - Print Numbers from 10 to 1
Explanation
A negative step decreases the value after every iteration.
This prints the numbers in reverse order.
Example 4 - Print Even Numbers in Reverse
Example 5 - Print Numbers from 10 to 0
- The for loop executes a group of statements for every element in a sequence
- A sequence can be a string, list, tuple, set, range or dictionary
- range() generates a sequence of numbers and returns a range object
- range(n) generates numbers from 0 to n-1
- A negative step value prints numbers in reverse order