Introduction to Loops:
Sometimes a programmer wants to execute a group of statements a certain number of times. This can be done using loops. Based on this loops are further classified into following main types:
for loop
while loop
for Loop:
for loops - can iterate over a sequence of iterable objects in python. Iterating over a sequence is nothing but iterating over strings, lists, tuples, sets and dictionaries.
Example 01:
name = 'Abhishek'
for i in name:
print(i, end=", ")
#Output: A, b, h, i, s, h, e, k,
Example 02:
name = 'Abhishek'
for i in name:
print(i)
if(i == "b"):
print("This is something special!")
#Output:
#A
#b
#This is something special!
#h
#i
#s
#h
#e
#k
- Iterating over a list
Example 03:
colors = ["Red", "Green", "Blue", "Yellow"]
for color in colors:
print(color)
#Output:
#Red
#Green
#Blue
#Yellow
Example 04:
names = ['ali','hamza','junaid']
ages = [22,25,30]
courses = ['AI',"ML","DS"]
for name,age, course in zip(names,ages,courses):
print(f'Hello Dear {name}, Welcome in {course} Course class, your are {age} years old')
#Output:
#Hello Dear ali, Welcome in AI Course class, your are 22 years old
#Hello Dear hamza, Welcome in ML Course class, your are 25 years old
#Hello Dear junaid, Welcome in DS Course class, your are 30 years old
Q: What if we do not want to iterate over a sequence? What if we want to use for loop for a specific number of times?
Ans: we can use the range() function.
Range ( ) Function:
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.
The loop starts from 0 by default and increments at each iteration.
But we can also loop over a specific range.
Syntax:
range (start: end: step)
start = from where the range starts (it includes in the range)
end = from where the range end (it does not include in the range)
step = difference /gap between range
Example 01:
for k in range(5): #from 0 to 4
print(k)
#Output:
#0
#1
#3
#4
Example 02:
for k in range(5): #from 1 to 5
print(k + 1)
#Output:
#1
#3
#4
#5
Example 03:
for x in range(2, 6):
print(x)
#Output:
#2
#3
#4
#5
Example 04:
for k in range(1, 12, 3):
print(k)
How it works:
Here: start =1, end =12 and step = 3
# it prints 1,4,7,10 b/c list starts with 1
# Then, 1+3 = 4
# Then 1+3+3 = 7
# Then 1+3+3+3 =10
# Then 1+3+3+3+3 = 13 - but it doesn't print 13 b/c a/c to range string ends at 12.
Output:
1
4
7
10
Example 05:
for x in range(2, 15, 3):
#print numbers from 2 to 30 with the difference of 3
print(x)
#Output:
#2
#5
#8
#11
#14