Tuesday, 21 March 2017

Python: range function

range( ) in Python:

  • it is a predefined function in python
  • range( ) function generating the group of values.
  • range value stores the group of values.
  • range value starting from zero( 0 ) by default.
type 1: 
pass one parameter or value,that value is ending value and that value is exclusive.
syntax: 
                 range(stop)
example:
range(3)

output:
range(0, 3)

Retrieve the one by one values from range by using for loop.

Example:
x=range(3)
for p in x:
    print(p)

Output:
0
1
2

Example:
x=range(3)
print(id(x))
print(type(x))
for p in x:
    print(p)
    print(type(p))
    print(id(p))

Output:
55317392
<class 'range'>
0
<class 'int'>
1926046384
1
<class 'int'>
1926046416
2
<class 'int'>
1926046448

type 2:
pass two parameters or values, first parameter or value take starting value,it is inclusive.
second parameter or value take stop value,it is exclusive.

syntax:
               range(start,stop)

here by default increment by 1

Example:
y=range(1,5)
for p in y:
    print(p)

Output:
1
2
3
4

type 3:
pass 3 parameters or values,first parameter/value takes start value,it is inclusive.
second parameter/value takes stop value,it is exclusive.
third value take step,increment/decrement value.

syntax:
                        range(start,stop, [step] )

Example:
z=range(0,10,2)
for p in z:
    print(p)

Output:
0
2
4
6
8

Example:
a=range(5,0,-1)
for p in a:
    print(p)

Output:
5
4
3
2
1

Example:
a=range(0,5,-1)
for p in a:
    print(p)

Output:
no output 

How to use range function in for loop:

Example:
for p in range(5):
    print(p)
Output:
0
1
2
3
4
Example:
for p in range(0,5):
    print(p)

Output:
0
1
2
3
4

Example:
for p in range(0,5,2):
    print(p)

Output:
0
2
4

Example:
for p in range(5,0,-2):
    print(p)

Output:
5
3
1





No comments:

Post a Comment