While Loop Python

The while loop is very similar to an if statement. If condition executes the code inside of it if and only if the condition is true whereas while executes the code inside it until the condition is true and move out of loop when condition returns False.

If suppose you want to withdraw $500 on starting of every month and invest it in some SIP. And you are asked to automate this process on start of every month till your 10th transaction given that you have certain amount in your bank. How will you go about writing a program for that.

You have to call this function ‘invest_in_sip()’ 10 times. But you can do that using while or for loops in following way.

UntitledWhile Condition

month = 0

balance = input(‘Enter your bank balance’)

while month!=10:

if balance – 500 >= 0:

balance -= 500

month += 1

else:

print ‘No money in account’

While loops are generally used when you want to take the values from the user n times. This can be demonstrated as follows –

n = int(input(‘Enter number of times you wish to insert: ‘))

while n:

x = int(input(‘Enter x coordinate: ‘))

y = int(input(‘Enter y coordinate: ‘))

n -= 1

Here when n equals to 0, The condition becomes False as 0 is representative of False.

hhhhIf Condition

month = 0

balance = input(‘Enter your bank balance’)

if month!=10:

if balance – 500 >= 0 :

balance -= 500

month += 1

else:

print ‘No money in account’

If condition will be executed only once whereas while condition will be executed again and again until the condition returns False.

Recommended Post   Let’s make a Calculator

Note : In while condition, if the condition returns False at the starting only, then the content inside while loop will never be executed and the very first statement after the loop will be executed.

The Infinite Loop

This will run the loop infinite times because infinite_var value will be the same every time and it’s value is not changed inside the loop. One needs to use CTRL+C to exit the an infinite loop. This will pass a ‘KeyboardInterrupt’ and stop the program immediately.

infinite_var = 23

while infinite_var == 23:

print ‘Hello! My name is python’

For Loops

loopFor loops are similar to while loop where the initialization also takes place inside the for loop. xrange(n) is used to run the loop n times from 0 to n-1.

for i in xrange(10):

print(i)

Output :

1

2

3

4

5

6

7

8

9

If we want to run a loop from start to end with a difference, then there is a general way to run a for loop.

for i in xrange(start,end,difference):

print(i)

TRY IT OUT

for i in xrange(1, 10, 2):

print(i)

Output :

1

3

5

7

9

For loops can also be converted into while loops as follows:

i = 1

while i < 10:

print i

i += 2

Content Protection by DMCA.com