What is range() function in python?
       The range() function is a built-in function in Python, just like print() or input(). The main functionality of the range() function is that it helps to generate a sequence of numbers.

Syntex:

range(start, end, increment)

  In the range() function, there are some default values for its three parameters. These values are used when we do not pass specific values to the function:

  • start: 0 (the sequence starts from 0)
  • end: n−1 (the sequence ends at n−1)
  • increment: 1 (the sequence increases by 1 each time)

Note : The range() function is primarily used in for loops or list to generate a sequence of numbers.

Problem: How to Use the range() Function in a List?

x = list(range(10))
print(x)

When we pass a single value to the range() function then it is counted as an end. so, how does the range function work:
in this , range(10)

range(10)
After filling in all default values:

range(start, end, increment)
range(0, 10-1, 1)

range(0, 9, 1)

 Output:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

=== Code Execution Successful ===

One another example, genrate a sequence of list using range() function.

Problem: Generate a list of numbers starting from 20 and ending at 70, where each consecutive number differs by 7.

Solution:

lst = list(range(20, 70, 7))
print(lst)

 Output:

[20, 27, 34, 41, 48, 55, 62, 69]

=== Code Execution Successful ===


How to use the range() function with for loop in Python?

As we know, the syntax of a for loop is:

for variable_name in sequence: 
    # block of code

   In this syntax, instead of using a string, list, tuple, set, or dictionary, we can use the range() function:

for variable_name in range(start, stop, step):
    # block of code

let's do some example of range() function with for loop:

Problem Statement: Print the numbers from 0 to 10.

for hlo_veriable in range(11):
    print(hlo_veriable) # hlo_veriable this is just a veriable

   In this syntax, instead of using a string, list, tuple, set, or dictionary, we can use the range() function:

0
1
2
3
4
5
6
7
8
9
10

=== Code Execution Successful ===

 Problem Statement: Print the table of 2 in the best way.

for i in range(1, 11):
    print(f"2 x {i} = {2*i}")

 i use f-string concept to print, read by click here.

2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16
2 x 9 = 18
2 x 10 = 20

=== Code Execution Successful ===

 

Leave a comment

You must be logged in to post a comment.

0 Comments