If you have any query feel free to chat us!
Happy Coding! Happy Learning!
In Python, the
range()
function is used to generate a sequence of numbers. It is commonly used withfor
loops to iterate over a specific range of numbers. Therange()
function can take up to three arguments:
start
: The starting value of the sequence (inclusive). If not specified, the default value is 0.stop
: The ending value of the sequence (exclusive). The sequence will generate numbers up to, but not including, this value.step
: The increment between each number in the sequence. If not specified, the default value is 1.The syntax for the
range()
function is as follows:pythonCopy code
range([start], stop, [step])
Here are some examples of using the
range()
function:Example 1: Generating a sequence of numbers from 0 to 4 (exclusive):
pythonCopy code
for num in range(5): print(num)
Output:
Copy code
0 1 2 3 4
Example 2: Generating a sequence of even numbers from 0 to 10 (exclusive):
pythonCopy code
for num in range(0, 10, 2): print(num)
Output:
Copy code
0 2 4 6 8
Example 3: Generating a sequence of numbers in reverse order from 10 to 1 (exclusive):
pythonCopy code
for num in range(10, 0, -1): print(num)
Output:
Copy code
10 9 8 7 6 5 4 3 2 1
In each example, the
range()
function is used to generate a sequence of numbers based on the specified arguments, and then thefor
loop iterates over the generated sequence to print each number. Therange()
function is a useful tool for creating number sequences and controlling the iteration of loops in Python.
Comments: 0