Saturday, March 24, 2012

Looping Statement: While Loop

Hello everyone, in this post we will Discuss about Loops.

What is a Loop?

Anything which keeps on repeating, based on a certain condition, is known as Loop.

In Python, Like other Programming Language, we have several looping statements, We will start with the While Loop


>>> x = 1
>>> while x <= 10:
           print "I Am ",x
           x = x + 1

I Am  1
I Am  2
I Am  3
I Am  4
I Am  5
I Am  6
I Am  7
I Am  8
I Am  9
I Am  10
>>>

Explanation: We have initiated the variable x, so the value of x is 1, next statement, while x <= 10: means keep doing the statements you have under while until x becomes less than or equal to 10. But as of now the x is 1, so it needs to execute the statements under the while statement, the print statement is pretty clear, which says print "I Am", x means print I Am x (x = present value of x), so it prints out I Am 1, next statement it find x = x + 1, means add one to the present value of x, so x becomes 2, x + 1(1 + 1) = 2, it returns to the while statement, checks the condition, present value of x is 2, since x is less than 10, it will again execute the statements under the while, in this way when the value of x becomes 11, and it returns to the while statement and the condition becomes false, it skips the statements under the while statements.


Lets Make a small Program

# Program to display the multiplication table of any given number upto 10.
num = input("Hey You! Give Me A Number \nAnd I Will Display The Multiplication Table Upto 10, Faster Than You Can Write: ")
count = 1
while count<=10:
    print num, " * ", count, " = ",  num*count
    count +=1
raw_input("Press Enter To Exit")

Output:

>>>
Hey You! Give Me A Number
And I Will Display The Multiplication Table Upto 10, Faster Than You Can Write: 8
8  *  1  =  8
8  *  2  =  16
8  *  3  =  24
8  *  4  =  32
8  *  5  =  40
8  *  6  =  48
8  *  7  =  56
8  *  8  =  64
8  *  9  =  72
8  *  10  =  80
Press Enter To Exit

Okay Interesting, isn't it?

I hope this is Informative For You, Practice it, And Here is a Task For You:

Question:

Write a Program which would display the Multiplication Table Of Any Given Number, Upto Any Given Point.

Example:
Give me a number to multiply: 9
How Far Should I Show you The Table: 20

and then it should display the multiplication table upto 20.

Good Luck!

0 comments:

Post a Comment