Python PT 4 Looping
Python PT 4 Looping
CONTENTS
L PING
WHILE Loop
FOR Loop
NESTED Loops
BREAK
.
CONTINUE
.
Loop Control Statements
PASS
WHILE L p
n=1
while n<=10:
if(n%2!=0):
print(">", n)
n=n+1
else:
print("Bye")
FOR L p
The for statement in Python has the ability to iterate over the items of
any sequence, such as a list or a string. Unlike the traditional FOR
loop of C / C++ / Java, Python uses different structure than others.
a=0; b=1
fib=1
for i in range(10):
print(fib)
fib = a+b
a=b
b=fib
WAP: To Print a the Star Pattern using single for loop as
shown below:
*
**
***
****
*****
s=""
for i in range(5):
s+= "*"
print(s)
else:
print("Goodbye")
NESTED L p
FOR LOOP
WHILE LOOP
while expression:
while expression:
statement(s)
statement(s)
Example: Printing Multiplication tables from 1 to 10
for i in range(1,11):
for j in range(1,11):
k=i*j
print(k, end="\t")
print('\n')
If you are using nested loops, the break statement stops the execution
of the innermost loop and starts executing the next line of the code
after the block.
SYNTAX:
break
EXAMPLE: Using break statement
for i in range(10):
print(i)
if(i==5):
break
else:
print(i)
CONTINUE
continue
EXAMPLE: Using Continue statement
n= 0
while n != 10:
n += 1
if n%2 == 0:
continue Affects the statements written after
print(n) continue statement
print()
PASS
The pass statement is also useful in places where your code will
eventually go, but has not been written yet i.e. in stubs).
SYNTAX:
pass
EXAMPLE: Using Pass in order to replace a Statement which
is undecided
num=1
if num<0:
print("Number is Negative")
elif num>0:
pass
else:
print("Number is Zero")