View on GitHub

python-for-kids

Learning and exercise content on Python for Kids

Day 11 - Loop For

In any programming language Loop means doing same thing again and again. When you repeat a task for more than one you don’t write the same instruction again and again. Because that is not the purpose of a programming language. Rather you take an approach like Loop to provide the instruction once and let the program execute it as many times as it needs.

Imagine you have to build a table. Then you think of a set {1,2,3,4,5,6,7,8,9,10} then you multiply this with a number for which this table is to be created, say 5. Then you can do it two different ways.

  1. Dumb way - by repeating
  2. Intelligent way - by Loop

Multiplication table example

# Dumb way
num = 5
print (1 * num)
print (2 * num)
print (3 * num)
print (4 * num)
print (5 * num)
print (6 * num)
print (7 * num)
...

This is solve your purpose. But if we try in a different way, by using collection and loop it would be more elegant. Let’s see.

# Intelligent way
num = 5
allNums = {1,2,3,4,5,6,7,8,9,10}
for i in allNums:
    print(i * num)

Let’s see few more examples

# To print all the items in a Collection
nums = {1,2,3,4,5,6,7,8,9}
for i in nums:
    print(i)

Strings are default array/collection

# in a string print all the letters
myname = "Wriju Ghosh"
for s in myname:
    print(s)

To break a loop upon a condition

# break a loop upon a condition
nums1 = {1,2,3,4,5,6,7,8,9}
for j in nums1:
    if(j == 5):
        break
    else:
        print(j)

range()

When values are sequential then use range

# Start zero till 9. 10 is not included.
for i in range(10):
    print(i)
#Start 2 and till 9. 10 is not included
for i in range(2,10):
    print(i)
# Start from 2, till 20 and take +2 for next (Step=2 - the last parameter)
for i in range(2, 21, 2):
    print(i)
# Using else range in for
for i in range(5):
    print(i)
else:
    print("Done.")

Multiplication table revised

Let’s become bit more smart :smiley:

num = 5
for i in range(1,11):
    print(i * num)

Watch the video

Video link

Day 11 - Exercise

  1. Make a multiplication table for 17.
  2. Make a multiplication table for 18.
  3. Make a multiplication table for 19.

Next: Day 12 - while Loop

Back to Index