While Loop
Loop manipulation using 03
pass, continue, break
Use of while loops in python
Syntax of Python While
while expression:
statement(s)
• Until a specified criterion is true, a block of statements will be
continuously executed in a Python while loop. And the line in the
program that follows the loop is run when the condition changes to
false.
Write a script to print “Python” 2 Times
count = 0
while (count < 2):
count = count+1
print("Python")
Loop manipulation using pass, continue,
break
Break Statement in Python
• to terminate the loop or statement in which it is present.
• After that, the control will pass to the statements that are present
after the break statement, if available.
• If the break statement is present in the nested loop, then it
terminates only those loops which contain the break statement.
Syntax of Break Statement
for / while loop:
# statement(s)
if condition:
break
# statement(s)
# loop end
Write a script to print all letters till ‘h’ from
the string “Python”.
s = 'python‘
# Using for loop
for letter in s:
print(letter)
# break the loop as soon it sees ‘h'
if letter == 'h':
break
print("Out of for loop")
Continue Statement in Python
• continue statement is opposite to that of the break statement.
• instead of terminating the loop, it forces to execute the next iteration
of the loop.
• As the name suggests the continue statement forces the loop to
continue or execute the next iteration.
• When the continue statement is executed in the loop, the code inside
the loop following the continue statement will be skipped and the
next iteration of the loop will begin.
Syntax of Continue Statement
for / while loop:
# statement(s)
if condition:
continue
# statement(s)
Write a program to print all numbers from 1
to 10 except 5.
for i in range(1,11):
if i==5:
continue
else:
print(i)
Pass Statement in Python
• The pass statement in Python is used when a statement is required
syntactically but you do not want any command or code to execute.
• It is like a null operation, as nothing will happen if it is executed. Pass
statements can also be used for writing empty loops.
• Pass is also used for empty control statements, functions, and classes.
Write a script to execute pass while printing 1
to 5 numbers after 2 and before 3.
for i in range(1,6):
if i == 3:
print('Pass executed')
pass
print(i)