Google News
logo
Python For Loops
The for statement differs from what programmers of C or C++ are used to. The for statement of Python looks a bit like the for loop of the Bash shell. 
We often need to go through all the elements of a list or perform an operation over a series of numbers. The Python for statement is the right tool to go easily through various types of lists and ranges.
Syntax :
for variable in sequence:
	Statement1
	Statement2	
	...
	Statementn
else:
	Else-Statement1
	Else-Statement2
	...
	Else-Statementm
>>> languages = ["C Language", "C++", "PHP", "Java", "Python"]
>>> for x in languages:
	print(x)

	
C Language
C++
PHP
Java
Python
>>> 

range() Function

The built-in function range() is the right function to iterate over a sequence of numbers. It generates lists of arithmetic progressions :

>>> num=2
>>> for a in range (1,6):
	print  (num * a)

	
2
4
6
8
10
>>> 
Another Example :
>>> sum=0
>>> for n in range(3,9):
	sum+=n
	print (sum)

	
3
7
12
18
25
33
>>>

Nested Loops

Loops defined within another Loop is called Nested Loop. When an outer loop contains an inner loop in its body it is called Nested Looping.

Syntax :
for  <expression>:  
        for <expression>:  
            Body
Syntax :
>>> for i in range(1,6):
	for j in range (1,i+1):
		print (i,)
		print

		
1
<built-in function print>
2
<built-in function print>
2
<built-in function print>
3
<built-in function print>
3
<built-in function print>
3
<built-in function print>
4
<built-in function print>
4
<built-in function print>
4
<built-in function print>
4
<built-in function print>
5
<built-in function print>
5
<built-in function print>
5
<built-in function print>
5
<built-in function print>
5
<built-in function print>
>>>