❮ Previous Next ❯

Python For Loop

for loop is very popular and widely used loop. In general when loop concept coming to the picture then immediately for loop concept come to our mind.

A for loop in Python is such type of loop which is especially used for iterate over a sequence(thar is either a list, or a tuple, or
a set, a string, or a dictionary)

With the for loop we can execute a set of statements, once for each item in a list, tuple, set, dictionary etc. python for loop


Example;
Print each car in a fruit list:

cars=["Maruti","Honda","Ford"]

for k in cars:

   print(k)

Output:
Maruti
Honda
Ford

Looping Through a String

We know strings contain a sequence of characters:

Example

Loop through the letters in the word "Maruti":

for x in "Maruti":

   print(x)

Output:
M

a

r

u

t

i

#Python program to find the sum of numbers
x=[1,2,3,4,5]
sum=0
for i in x:
   sum=sum+i
print("summation is:",sum)

Output:
summation is:15

The range() Function

In python the range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 by default , and ends at a specified number.


Example
Using the range() function:
for x in range(5):
   print(x)
Output: 0
1
2
3
4
    Range() function can take 2 arguments. However it is possible to specify the starting value by adding a parameter: range(2, 5), which means values from 2 to 5 (but not including 5):



Example;
for x in range(2,5):
   print(x)
Output 2
3
4

The range() function defaults to increment the sequence by 1, however it is possible to specify the increment value by adding a third parameter: range(2, 40, 4):


Example;
for x in range(2,40,4):
   print(x)
Output
2
6
10
14
18
22
26
30
34
38


Nested Loop

When a loop is embedded in another loop is known as nested loop. The "inner loop" will be executed one time for each iteration of the "outer loop":

Example
Print each color for every car:
colors=["red","blue","green"]
cars=["maruti","honda","ford"]
for x in colors:
   for y in cars:
     print(x,y)


Output:
red maruti
red honda
red ford
blue maruti
blue honda
blue ford
green maruti
green honda
green ford

❮ Previous Next ❯

Follow Us




  Tutorials

Popular Links

Contact Us

address Plot No-741,2ND Floor
Opp. Bhagabati Temple,Jayadev Vihar
      Bhubaneswar-751013
      Email: info@silantechnology.com
      Phone: 0674-2361252
address
39877, sundale dr, apt#101, Fremont, California 94538, USA
       Phone: +1(262)388-7619

facebook twitter google linked in

© 2018 Silan Technology. All Rights Reserved