range() in python

 In Python, range() is a built-in function used to generate a sequence of numbers. It takes three arguments:

  • start (optional) - starting number of the sequence (default is 0)
  • stop (required) - stopping number of the sequence (exclusive)
  • step (optional) - step size between each number (default is 1)

range() returns a sequence of integers starting from the start parameter (default 0) up to (but not including) the stop parameter, incremented by step (default 1). It can be used in for loops, list comprehensions, and other similar constructs.

Here are some examples:

python
# Print numbers from 0 to 4 
for i in range(5): 
    print(i) # Print even numbers from 0 to 10 
for i in range(0, 11, 2): 
    print(i) # Generate a list of squares of numbers from 0 to 4 
squares = [i ** 2 for i in range(5)] 
print(squares)

Output:

csharp
0 
1 
2 
3 
4 
0 
2 
4 
6 
8 
10 
[0, 1, 4, 9, 16]

In the first example, the range() function generates a sequence of integers from 0 to 4, which is used in the for loop to print each number.

In the second example, the range() function generates a sequence of even numbers from 0 to 10 (0, 2, 4, 6, 8, 10), which is used in the for loop to print each number.

In the third example, the range() function generates a sequence of integers from 0 to 4, which is used in the list comprehension to generate a list of squares of those numbers.

Post a Comment

Previous Post Next Post