Loading, please wait...

Loops

LOOPS IN PYTHON

The loops are iteration for a range of something i.e from starting point to a limit given by user, which increases efficiency of code and helps us in writing less code saving time and energy.

 

The loops helps to do many task in programming language and makes the programme to be a light weight.

 

1. For Loop:

primes = [2, 3, 5, 7,11]
for prime in primes:
print(prime)

 

 

2. Break Statement

To break out from a loop, we can use the keyword "break".

for i in range(1,15):
if i == 3:
break
print i

 

 

3. Continue Statement:

Skip the rest of the statements in the current loop and to continue to the next iteration of the loop.

for i in range(1,20):
if i == 3:
continue
print i

 

 

4. While Loop:

As long as the condition is met the loop needs to execute the condition.

mobile_brands = ["Moto", "Apple", "Lenovo", "Honor"]
i = 0
while i < len(mobile_brands):
print mobile_brands(i)
i = i + 1
while True:
answer = raw_input("Start typing...")
if answer == "quit":
break
print "Your answer was", answer

 

 

5. Nested Loop

A nested loop is a loop inside a loop.

for x in range(1, 55):
for y in range(1, 55):
print '%d * %d = %d' % (x, y, x*y)