Python is a versatile programming language that comes with many built-in functions that make coding easier and more efficient. One such function is the range() function, which is used to generate a sequence of numbers within a specified range. The range() function is a powerful tool for creating loops and iterating over a set of values.
The range() function is used to create a range of numbers starting from a specified start value and incrementing by a specified step size. The basic syntax for the range() function is as follows:
|
range(start, stop, step)
|
where start is the starting value of the range, stop is the ending value of the range (exclusive), and step is the increment between each number in the range.
Here are some examples of using the range() function:
Example 1: Printing a sequence of numbers
|
for i in range(1, 6):
print(i)
|
Output:
1 2 3 4 5In this example, the range() function creates a sequence of numbers from 1 to 5 (inclusive) and the for loop iterates over each number in the sequence and prints it to the console.
Example 2: Creating a list of even numbers
|
even_numbers = list(range(0, 10, 2))
print(even_numbers)
|
Output:
[0, 2, 4, 6, 8]In this example, the range() function creates a sequence of even numbers from 0 to 8 (inclusive) with a step size of 2. The list() function is used to convert the sequence to a list, which is then printed to the console.
Example 3: Summing a sequence of numbers
|
total = 0
for i in range(1, 11):
total += i
print(total)
|
Output:
55In this example, the range() function creates a sequence of numbers from 1 to 10 (inclusive) and the for loop iterates over each number in the sequence, adding it to the total variable. The final value of total is then printed to the console.
The range() function is a versatile tool that can be used in many different scenarios, including generating sequences of numbers, creating loops, and iterating over lists. By mastering the range() function, you can write more efficient and concise Python code.