Python                                                          Home : www.sharetechnote.com

 

 

 

 

For Loop 

 

NOTE : All the examples in this page are written in Python 3.x. It may not work if you use Pyton 2.x

NOTE 1 : All the examples in this page are written in Python 3.x. It may not work if you use Pyton 2.x

NOTE 2 : All the examples in this page are assumed to be written/run on Windows 7 unless specifically mentioned. You MAY (or may not) need to modify the syntax a little bit if you are running on other operating system.

 

 

< Syntax >

 

for x in sequence :

    do_things_on_x

 

 

< Example >

 

< Example 1 >

 

for i in range(10) :

   print("current i =",i)

 

Result :------------------------------------

 

current i = 0

current i = 1

current i = 2

current i = 3

current i = 4

current i = 5

current i = 6

current i = 7

current i = 8

current i = 9

 

 

< Example 2 >

 

for i in range(-5,5) :

   print("current i =",i)

 

Result :------------------------------------

 

current i = -5

current i = -4

current i = -3

current i = -2

current i = -1

current i = 0

current i = 1

current i = 2

current i = 3

current i = 4

 

 

< Example 3 >

 

aString = "Hello World"

 

for c in aString :

   print("current letter =",c)

 

Result :------------------------------------

 

current letter = H

current letter = e

current letter = l

current letter = l

current letter = o

current letter =

current letter = W

current letter = o

current letter = r

current letter = l

current letter = d

 

 

< Example 4 >

 

fruits =["apple","banana","strawberry"]

 

for fruit in fruits :

   print("A fruit in the basket =",fruit)

 

Result :------------------------------------

 

A fruit in the basket = apple

A fruit in the basket = banana

A fruit in the basket = strawberry