View on GitHub

python-for-kids

Learning and exercise content on Python for Kids

Day 12 - Loop - While

while loop is similar to for loop which we have discussed here. However, they have some sytactical differences and internal workings. It is a simple form of loop in Python.

We will not focus on the internals but see how the syntax looks like,

Simple while loop

Notice here the number has to be incremented by you. Here we are using n+=1 which means n=n+1. Thus the next n will be +1 of the previous.

n = 1
while n < 11:
    print(n)
    n+=1

Using 3rd variable to terminate the loop

By changing an True value of a boolean data type checking until it is True loop it.

i = 1
blnFlag = True
while blnFlag:
    print(i)
    if(i == 10):
        blnFlag = False
    i+=1

Using break keyword to terminate

You can use break to come out of the while loop as needed. No need to use any other boolean value to do so.

j = 1
while (j < 10):
    if(j == 5):
        break
    else:
        print(j)
    j+=1

In below example it will look for the value 9 and if it is not the case it won’t do anything by using pass keyword. Pass is a statement to simply do nothing.

k = 1
while (k<10):
    if k != 9:
        pass
    else:
        print(k)
    k +=1

The code is available.

Day 12 - Exercise

  1. Try to use while loop to make a Multiplication table for 17, 18 and 19.

Next: Day 13 - Function

Back to Index