Ques.Write a program using for loop that loops over a sequence
Answer :
For loops iterate over a given sequence.In sequence either (dictionary, tuple, set, list and string )
for loop syntax (for variable in sequence or range)
for loop concept
Examples
#For loop in list
color_list=['red','green','white','purple','pink','marron']
for i in color_list:
print(i)
#For loop in string
fr_string="Goeduhub technologies"
for i in fr_string:
print(i)
#For loop in dictionary
fr_dict={1:'q',2:'w',3:'e',4:"r"}
for i in fr_dict:
print(i)
#Sum of all the list elements
Num=[1,2,3,4,5,6,7,8,9,10]
Sum=0
for i in Num:
Sum=Sum+i
print(Sum)
Output
red green white purple pink marron
G o e d u h u b t e c h n o l o g i e s
1 2 3 4
55
For loop with range() Function
range() syntax
range(a) - Generates a sequence started from 0 to a , where a is excluded
range(a,b)- Generates a sequence started from a ,end at b , where b is excluded
range(a,b,c)- Generates a sequence started from a, end at (b-1) and c is difference (steps)
Note:-By default range() function take difference of 1, if difference is not given.
Example
color_list=['red','green','white','purple','pink','marron']
for i in range(len(color_list)):
print(color_list[i])
s=0
for i in range(1,14,3):
print(i)
s=s+i
print("sum is =",s)
Output
red green white purple pink marron
1
4
7 10 13
sum is= 35
For more Rajasthan Technical University CSE VI Sem Python Lab Experiments Click here