Generating a Range of Numbers in Python
In Python, you can easily generate a range of numbers using the built-in range()
function. This function allows you to create a sequence of numbers within a specified range.
Using the range()
Function
The range()
function takes three arguments:
- Start: The starting number of the range (inclusive). If not provided, the default value is 0.
- Stop: The ending number of the range (exclusive).
- Step: The step size between each number in the range. If not provided, the default step size is 1.
Here's an example of how to use the range()
function:
## Generate a range from 1 to 10 (exclusive)
print(list(range(1, 11))) ## Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
## Generate a range from 0 to 20 with a step size of 2
print(list(range(0, 21, 2))) ## Output: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
## Generate a range in reverse order
print(list(range(10, 0, -1))) ## Output: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
Iterating Over a Range
Once you have a range of numbers, you can easily iterate over them using a for
loop. This is particularly useful when you want to perform an operation on each number in the range.
## Iterate over a range of numbers
for num in range(1, 11):
print(num)
## Output:
## 1
## 2
## 3
## 4
## 5
## 6
## 7
## 8
## 9
## 10
By understanding how to generate and iterate over ranges of numbers in Python, you can effectively work with divisibility by 7 in the next section.