How to Loop: Looping Techniques

Lists and Sequences

Looping through a sequence

for item in ['This', 'class', 'is', 'awesome']:
    print(item)
This
class
is
awesome

Loop through a sequence using enumerate()

enumerate(['This', 'class', 'is', 'awesome'])
<enumerate at 0x7f8a4df1d480>
list(enumerate(['This', 'class', 'is', 'awesome']))
[(0, 'This'), (1, 'class'), (2, 'is'), (3, 'awesome')]
list(enumerate(['This', 'class', 'is', 'awesome'], start=1))
[(1, 'This'), (2, 'class'), (3, 'is'), (4, 'awesome')]
for iterator, value in enumerate(['This', 'class', 'is', 'awesome']):
    print(iterator, value)
0 This
1 class
2 is
3 awesome

Loop through a sequence in reverse using reversed()

for item in reversed(['This', 'class', 'is', 'awesome']):
    print(item)
awesome
is
class
This

Looping through multiple sequences using zip()

questions = ['sex', 'name', 'shape', 'hello']
answers = ['Male', 'Pau', 'Orange in shape']

for question, answer in zip(questions, answers):
    print('What is your ' + str(question) + '?')
    print('I am ' + str(answer))
    print()
What is your sex?
I am Male

What is your name?
I am Pau

What is your shape?
I am Orange in shape
dict(zip(questions, answers))
{'sex': 'Male', 'name': 'Pau', 'shape': 'Orange in shape'}

Dictionaries

Looping though dictionary using items()

contact = {
    'Ram Kasula': 9840298755,
    'Anu Pau': 98651201503,
    'Kade Hade': 9863331239
}

for name, number in contact.items():
    print(name, number)
Ram Kasula 9840298755
Anu Pau 98651201503
Kade Hade 9863331239

Looping though dictionary using iteritems()

This is depreciated in Python 3

Exercise

  • Print below pattern using nested loop:

    * 
    * * 
    * * * 
    * * * * 
    * * * * * 
    
  • Print below pattern:

    1
    22
    333
    4444
    55555
    666666
    7777777
    88888888
    999999999
    
  • Print below pattern using nested loop:

    * 
    * * 
    * * * 
    * * * * 
    * * * * * 
    * * * * 
    * * * 
    * * 
    *
    
  • Print below pattern using loop:

     *                                                                      
     *                                                                      
     *                                                                      
     *                                                                      
     *                                                                      
     *                                                                      
     *****
    
  • Calculate the individual expense by an individual, total expense and payable amount for each member from below data structures using loop:

    expenses = {
        'Eliza': {
            'Dahi': 280,
            'PaniPuri': 120,
            'Bara': 160,
            'Kulfi': 200,
            'Pau': 50,
        },
        'Binay': {
            'Water': 30,
        },
        'Kshitiz': {
            'Chocolate': 90,
        },
        'Sajal': {
            'Coffee':500,
        },
    }
    
  • Create a dictionary of cubes upto number 10 using loop.

  • Convert the above expenses dictionary keys to list using loop

'''
Print below pattern using nested loop:

  * 
  * * 
  * * * 
  * * * * 
  * * * * *
'''
for num in range(1,6):
    print('* ' * num)
* 
* * 
* * * 
* * * * 
* * * * * 
'''
Print below pattern:

  1
  22
  333
  4444
  55555
  666666
  7777777
  88888888
  999999999
'''
for num in range(1,10):
    print(str(num) * num)
1
22
333
4444
55555
666666
7777777
88888888
999999999
'''
Print below pattern using nested loop:

  * 
  * * 
  * * * 
  * * * * 
  * * * * * 
  * * * * 
  * * * 
  * * 
  *
'''
maxStar = 5
for i in range(1, maxStar + 1):
    print('* ' * i)
for i in range(maxStar - 1, 0, -1):
    print('* ' * i)
* 
* * 
* * * 
* * * * 
* * * * * 
* * * * 
* * * 
* * 
* 
'''
Print below pattern using loop:

   *                                                                      
   *                                                                      
   *                                                                      
   *                                                                      
   *                                                                      
   *                                                                      
   *****
'''
for i in range(1,8):
    if (i == max(range(1,8))):
        print('*' * 5)
    else:
        print('*')
*
*
*
*
*
*
*****
'''
Calculate the individual expense by an individual, total expense and payable amount for each member from below data structures using loop:

  expenses = {
      'Eliza': {
          'Dahi': 280,
          'PaniPuri': 120,
          'Bara': 160,
          'Kulfi': 200,
          'Pau': 50,
      },
      'Binay': {
          'Water': 30,
      },
      'Kshitiz': {
          'Chocolate': 90,
      },
      'Sajal': {
          'Coffee':500,
      },
  }
'''
expenses = {
  'Eliza': {
      'Dahi': 280,
      'PaniPuri': 120,
      'Bara': 160,
      'Kulfi': 200,
      'Pau': 50,
  },
  'Binay': {
      'Water': 30,
  },
  'Kshitiz': {
      'Chocolate': 90,
  },
  'Sajal': {
      'Coffee':500,
  },
}

total_expense = 0
indvExpense = {}

for item in expenses:
    indvExpense[item] = sum(expenses[item].values())
print('Individual expense : ' + str(indvExpense))
print('Total expense :' + str(sum(indvExpense.values())))
payableAmount = sum(indvExpense.values())/len(indvExpense)
print('Payable Amount : ')

for item in indvExpense:
    print(item + '->' + str(indvExpense[item]-payableAmount))
Individual expense : {'Eliza': 810, 'Binay': 30, 'Kshitiz': 90, 'Sajal': 500}
Total expense :1430
Payable Amount : 
Eliza->452.5
Binay->-327.5
Kshitiz->-267.5
Sajal->142.5
#Create a dictionary of cubes upto number 10 using loop.
dictCubes = {}
for i in range(1,11):
    dictCubes[i]=i**3
print(dictCubes)
{1: 1, 2: 8, 3: 27, 4: 64, 5: 125, 6: 216, 7: 343, 8: 512, 9: 729, 10: 1000}
#Convert the above expenses dictionary keys to list using loop
listKeys = []
for item in expenses:
    listKeys.append(item)
print(listKeys)
['Eliza', 'Binay', 'Kshitiz', 'Sajal']