You are on page 1of 6

Python 

Loops
Python has two primitive loop commands:

while loops
for loops

The while Loop
With the while loop we can execute a set of statements as long as a condition is true.

Example 1: Print i as long as i is less than 5:

i=1
while i < 5:
print(i)
i = i+1

Example 2:
i=1
while i < 6:
print(i)
print("Hi")
i =i+1
Example 3:
i=1
while i < 10:
print(i)
i =i+2

The break Statement
With the break statement we can stop the loop even if the while condition is true:
Example: 

i=1
while i < 10:
print(i)
break
i =i+1
Example:
i =1
while i < 6:
print(i)
if i ==3:
break
i = i+1
The continue Statement:
With the continue statement we can stop the current iteration, and continue with the next:

i = 0
while i < 6:
   i = i+1 
   if i == 3:
     continue
   print(i)

The Listener Loop
Taking input inside while loop until certain condition is satisfied. Such loop is called 
as listenr loop.

theSum = 0

x = ­1

while (x != 0):

    x = int(input("next number to add up (enter 0 if no more numbers): "))

    theSum = theSum + x

print(theSum)

Python For Loops


Used to perform operations repeatedly.
Example:

for x in "Sanjivani":

print(x)

The range() Function


The range() function returns a sequence of numbers, starting from 0 by default,
and increments by 1 (by default), and ends at a specified number.

Example:

for x in range(6):
print(x)

Example:

for x in range(2,10):
print(x)

The range() function defaults to increment the sequence by 1, however it is


possible to specify the increment value by adding a third parameter: range(2,
30, 3):

Example:
for x in range(2, 30, 3):
print(x)

for x in range(6):
print(x)

Example:

Print 1 to 10 numbers
Example: Print the table of 5 using for loop

num = 5

for i in range(1,11):

print(i*num)

The break Statement


With the break statement we can stop the loop even if the while condition is true:

Example: 

for i in range(10):
print(i)
break

Example:
for i in range (2,6):
print(i)
if i ==3:
break
The continue Statement:
With the continue statement we can stop the current iteration, and continue with the next:

for i in range(6):
   if i == 3:
     continue
   print(i)

You might also like