In Python, loops are used to execute a block of code repeatedly based on a condition. Python supports two main types of loops: for loops and while loops.
Types of looping statements:
1. for
2. while
3. while with else
4. nested loops
The syntax for the looping statements are as follows:
1. for loop
for var_name in range ( start : end : increment ) :
Example-
a. for i in range ( 6 ) :
print ( i )
Output :
0
1
2
3
4
5
b. str = " xyz "
for i in str :
print ( i )
Output-
x
y
z
2. while loop
a. while ( a <= 5 ) :
print ( a )
a = a + 1
Output:
0
1
2
3
4
5
b. a=1
while ( a <=5 ) :
print ( a )
a = a + 1
else :
print ( " End " )
Output:
0
1
2
3
4
5
End
Consider the following code for inputting and squaring the elements of the list
l = []
for i in range ( 10000000 ) :
s = int ( input ( " Enter values for list - " ) )
l.append(s)
if ( s==0 ) :
break
else:
continue
for j in range( len(l) ) :
l[j] = l[j] * l[j]
print ( l[j] )
Output:
0 Comments