10

LOOPS

by

The Education Machine

[support@theeducationmachine.com]


Loops are used to automate the task which we would like to perform multiple times.

There are two types of Loops in python:

1.) For Loop: Executes a sequence of statements multiple times with the help of iterator variable.

2.) While Loop: While loop Repeats a statement or group of statements while a given condition is TRUE. The condition is tested before executing the body of loop.

As we saw in if-else conditions, every if-elif-else statement/s should be ended with a " : ". Similarly, Loop statements should also be ended with a colon -> :


Syntax of 'for loop' with range() function. Range function is used in for loop to iterate over a series of values. User can give the start position, end position and step value, just like we did in slicing and dicing.

In following code, the user wants to print number from a range of 0 to 5. Loop will iterate in this range and print the output. In range, o is the increment of numbers is 1 (by default) and it skips the last number as shown below:

  for i in range(0,5):
      print(i)

Output:
0
1
2
3
4

To check that loop iterates one by one, we have used time.sleep() function to slow down the iteration by 2 seconds. The output has shown one by one with the interval of 2 seconds.
You can try this yourself and take whatever time interval you want, as shown below:

  import time
  
  for i in range(0,5):
      time.sleep(3)
      print(i)

Output:
0
1
2
3
4

To print a string with range.

  for i in range(1,5):
      print(i,"A"))

Output:
1 A
2 A
3 A
4 A

To print the double of range.

  for i in range(0,10):
      print(i+i)

Output:
0
2
4
6
8
10
12
14
16
18

To print the number ranging from 0 to 50 with increment or step value of 5.

  for i in range(0,50,5):
      print(i)

Output:
0
5
10
15
20
25
30
35
40
45

To print the elements of list one by one.

  l = [1,'Kashish',3,'Gakkar',5]
  for i in l:
      print(i)

Output:
1
Kashish
3
Gakkar
5

To perform indexing in a list using for loop and then multiplying the indexed element with itself.

  a=[1,2,3,4,5]
  for i in a[1:3]:
      print(i * i)

Output:
4
9

To iterate and print the first 3 elements of a list using indexing and for loop.

  a=[1,2,3,4,5]
  for i in a[:3]:
      print(i)

Output:
1
2
3

To iterate the list and printing the elements one by one using for loop and indexing.

  for i in a[:]:
      print(i)

Output:
1
2
3
4
5

To reverse the list and multiplying the element with itself.

  for i in a[::-1]:
      print(i*i)

Output:
25
16
9
4
1

Try to guess the output of the below code:

  for i in (1,20):
      print(i)


1
20



Little Advance Questions

1. print every item from a grocery list and the length of each element using for loop.

  grocery = ['pasta', 'rice' ,'cheese', 'mayonnaise', 'peanuts', 'strawberries']
  for i in grocery:
      print(i,len(i))

Output:
pasta  5
rice  4
cheese  6
mayonnaise  10
peanuts  7
strawberries 12

2. print every item from a grocery list and the length of each element and use string formatting.

  grocery = ['pasta', 'rice' ,'cheese', 'mayonnaise', 'peanuts', 'strawberries']
  for i in grocery:
      print(f"Item: {i}, Length of item: {len(i)}")

Output:
Item:  pasta, Length of item:  5
Item:  rice, Length of item:  4
Item:  cheese, Length of item:  6
Item:  mayonnaise, Length of item:  10
Item:  peanuts, Length of item:  7
Item:  strawberries, Length of item:  12

3. Print the total count of items, not individuals.

  grocery = ['pasta', 'rice' ,'cheese', 'mayonnaise', 'peanuts', 'strawberries']
  count=0
  for i in grocery:
      count += 1
  print(f"You went to market to buy {count} grocery items")

Output:
You went to market to buy 6 grocery items

4. Print the total count of items, not individuals.

  grocery = ['pasta', 'rice' ,'cheese', 'mayonnaise', 'peanuts', 'strawberries']
  count=0
  for i in grocery:
      count+=1
      print(f"You went to market to buy {count} grocery items"))

Output:
You went to market to buy 1 grocery items
You went to market to buy 2 grocery items
You went to market to buy 3 grocery items
You went to market to buy 4 grocery items
You went to market to buy 5 grocery items
You went to market to buy 6 grocery items

5. Print all even and odd numbers between 1 to 10 with a message

  for i in range(1,11):
      if i%2 == 0:
            print(f"{i}: Even")
      else:
            print(f"{i}: Odd")

Output:
1:  Odd
2:  Even
3:  Odd
4:  Even
5:  Odd
6:  Even
7:  Odd
8:  Even
9:  Odd
10:  Even

6. Find length(n) of each element & Print each element n times.

  grocery = ['pasta', 'rice' ,'cheese', 'mayonnaise', 'peanuts', 'strawberries']
  for i in grocery:
    print(i * len(i))

Output:
pastapastapastapastapasta
ricericericerice
cheesecheesecheesecheesecheesecheese
mayonnaisemayonnaisemayonnaisemayonnaisemayonnaisemayonnaisemayonnaisemayonnaisemayonnaisemayonnaise
peanutspeanutspeanutspeanutspeanutspeanutspeanuts
strawberriesstrawberriesstrawberriesstrawberriesstrawberriesstrawberriesstrawberriesstrawberriesstrawberriesstrawberriesstrawberriesstrawberries

7.Calculate how much amount you will get if you do Fixed Deposit.

  p = 100000
  interest = .09
  for i in range(1,10):
      p = p+(p*interest)
  print(f"The principal is {p}")

Output:
The principal is 217189.32794423093

8.Solve this problem by yourself:
Person 'A' took a loan of amount 1lakh with 10% interest rate for 5 years.
Person 'B' took a loan of amount 1lakh with 7% interest rate for 5 years., whats the loss?

  p1 = 100000
  int1=.1
  p2 = p1
  int2=.07
  for i in range(1,6):
      p1+=p1*int1
      p2+=p2*int2
      loss=p2-p1
      print(f"The loss is {loss}")

Output:
The loss is -3000.0
The loss is -6510.0
The loss is -10595.699999999997
The loss is -15330.399000000005
The loss is -20795.82693000001

9. Principal amount is 100000.
For first 3 years, interest rate is 7% and then 8% for subsequent years, whats the final amount you will get?

  p=100000
  int1=.07
  int2=.1
  for i in range(1,6):
      if i in range(1,4):
          p+=p*int1
          print(p)
      elif i in range(4,6):
          p+=p*int2
          print(p)

Output:
107000.0
114490.0
122504.3
134754.73
148230.203

10. Count the alphabet "a" and "m" in string.

  s="My name is Kashish. I live in Delhi."
  c=0
  for i in s:
      if i in ("a" "e"):
          c+=1
  print(c)

Output:
5

11. Exclude the Count of alphabet "a" and "m" in string

  s="My name is Kashish. I live in Delhi."
  c=0
  for i in s:
      if i not in ("a" "e"):
          c+=1
  print(c)

Output:
31

12. I have declared 3 objects, check type of each element of a list using for loop.

  a=b=c=1
  l=[a,b,c]
  for i in l:
      print(type(i))

Output:
<class 'int'>
<class 'int'>
<class 'int'>