§ If you want to execute set of statements number of times then we
are required to use iterative statements
§ Python supports 2 types of iterative statements.
1. for loop
2. while loop
for loop
§ If you want to execute set of statements multiple times then we
have to require to use for loop.
If we want to execute some action for every element present in
some sequence (it may be string or collection) then we have to require to use
for loop.Syntax of for Loop
§ Here,
value is the variable that takes the value of the item inside the sequence on
each iteration.
Loop
continues until we reach the last item in the sequence. The body of for loop is
separated from the rest of the code using indentation.range() function
§
range ()
is a built-in function of Python. It is used
when a user needs to perform an action for a specific number of times.
§ The range type
represents an immutable sequence of numbers and is commonly used for looping a
specific number of times in for loops.
The range () function is used to
generate a sequence of numbers.class range(stop)
range(n):
§ generates a set of whole numbers starting from
0 to (n-1).
For example:
range(8) is equivalent to [0, 1, 2, 3, 4,
5, 6, 7]
range(start, stop):
generates a set of whole numbers starting from start to stop-1
range(start, stop):
generates a set of whole numbers starting from start to stop-1
For example:
range(5, 9) is equivalent to [5, 6, 7, 8]
range(5, 9) is equivalent to [5, 6, 7, 8]
class range(start, stop[, step])
range(start, stop, step_size):
§ The default step_size is 1 which is why when we
didn’t specify the step_size, the numbers generated are having difference of 1.
However by specifying step_size we can generate numbers having the difference
of step_size.
For example:
range(1, 10, 2) is equivalent to [1, 3, 5, 7, 9]
For example:
range(1, 10, 2) is equivalent to [1, 3, 5, 7, 9]
§ Write
a program to display from 0 to n natural numbers.
for i in
range(10):
print(i)Output:
The output will be from 0..9
§ Write
a program to display of first 1 to 10 natural numbers.
for i in
range(1,11):
print(i)Output:
The output will be from 1……10
§ Write
a program to display odd number between 1 to 10.
for i in
range(1,11,2):
print(i)Output:
1
3
5
7
9
Post a Comment