Advertisement
range(start, end, increment)
# Python for loop with range() function
# This gives us a sequence of values starting from 2 to 4 and incrementing by 1
x = range(2,5)
print('First for loop :')
# Using for loop is used to print the sequence of values
for i in x:
print(i)
# This gives us a sequence of values starting from 0 to 5 and incrementing by 1
x = range(6)
print('Second for loop :')
# For loop is used to print Hello for each number in the sequence of values
for n in x:
print('Hello')
print(n)
First for loop:
2
3
4
Second for loop:
Hello
0
Hello
1
Hello
2
Hello
3
Hello
4
Hello
5
Advertisement
#Python - for loop iterating over elements stored in a list
#A list
a_list = [1, 2, 3, 4, 5]
#for loop iterating over list
for x in a_list:
print("x =", x)
x = 1
x = 2
x = 3
x = 4
x = 5
#Python - for loop iterating over elements stored in a tuple
#A tuple
a_list = (1, 2, 3, 4, 5)
#for loop iterating over list
for x in a_list:
print("x =", x)
x = 1
x = 2
x = 3
x = 4
x = 5
#Python - for loop iterating over elements stored in a set
#A set
a_set = {1, 2, 3, 4, 5}
#for loop iterating over a set
for x in a_set:
print("x =", x)
x = 1
x = 2
x = 3
x = 4
x = 5
#Python - for loop iterating over elements stored in a list
#A dictionary
a_dictionary = {
"one":"1",
"two":"2",
"three":"3",
"four":"4",
"five":"5"
}
#for loop iterating over pairs of key and value stored in a dictionary
for x in a_dictionary:
print(x, a_dictionary[x])
one 1
two 2
three 3
four 4
five 5
Advertisement
Advertisement
Please check our latest addition
C#, PYTHON and DJANGO
Advertisement