In Tech Knowledge learn various technologies

Recent Post

Friday, December 20, 2019

PYTHON FOR LOOP

PYTHON FOR LOOP

 PYTHON FOR LOOP


When we want to execute a block of statements several times, then we used loop. For loops are used for sequential traversal of a string, tuples and list etc.


PYTHON FOR LOOP
Flow Chart of FOR Loop

Python For Loop Syntax

for iterating_variable in sequence :
                statement(s)



The for loop can be a single statement or a block of code with multiple statements. Firstly it is checked whether or not the program reached the last item in the sequence. If the program is not reached the last item in the sequence, before executing the statement inside the body of for loop, the value from the sequence gets assigned to the iterating_variable. If the program is reached the last item in the sequence, the flow of program jumps out of for loop.

Python For Loop List
Example 1:  Print items in the list.
Coding 
Example 1.1: 
 
num = [1,'SMITH',3.2]
for i in num :
    print(i)




Example 1.2:
for i in [1, 'SMITH', 3.2] :
    print(i)





Output
 1
SMITH
3.2




Python For Loop String

Example 2:  Print characters of a string.
Coding
name = 'SMITH'
for i in name :
    print(i)
 



Output

S
M
I
T
H








Python For Loop Range

range() function is used to generates a set of integer number. By default is start from 0 to n-1 and increments by 1.

Python For Loop Range Syntax
range(start, stop, step)
 


start specifies the starting integer.
stop specifies the position where to stop the iteration.
step specifying the incrementation. By default the numbers generated are having difference of 1.


Example 3:  Print first 10 numbers.
Coding
for i in range(10) :
    print(i)




Output  
0
1
2
3
4
5
6
7
8
9
 












Example 4:  Print from the range of 1 to 20 with the difference of 4.
Coding
for i in range(1,20,4) :
    print(i)



Output
1
5
9
13
17
 







Example 5:  Print from the range of 1 to 20 with the difference of 4 in reverse order.
Coding
for i in range(20,1,-4) :
    print(i)




Output
1
5
9
13
17






Python Nested For Loops

When a for loop is written inside the body of the another for loop, then it is known as nesting of for loop.

Example 7:  Python program for the pyramid.
Output
 *
* *
* * *
* * * *
* * * * *






Coding
for i in range(1,6):
   for j in range(i):
        print("*",end=' ')
    print()


No comments:

Post a Comment

please do not enter any spam link in the comment box