Flow of Control: Loops: Introduction To Programming and Problem Solving
Flow of Control: Loops: Introduction To Programming and Problem Solving
while Boolean_Expression:
Body_Statement
or
while Boolean_Expression:
First_Statement
Second_Statement
…
The while Statement (cont).
Semantics of the while statement:
1. The Boolean expression is
evaluated before the statements in
the while loop block is executed.
• If the Boolean expression
evaluates to False, then the
statements in the while loop block
are never executed.
• If the Boolean expression evaluates to
True, then the while loop block is
executed.
2. After each iteration of the loop block,
the Boolean expression is again
checked, and if it is True, the loop is
iterated again.
• This process continues until the Boolean
expression evaluates to False and at this
point the while statement exits.
Sample Program using
while Statement
Write a Python program to display the
first 10 numbers using while loop starting
from 0.
i=0
while i < 10:
print(f"Current value of i is {i}")
i=i+1
Sample Program using
while Statement (cont).
Write a Python program that reads a number (num).
Find and display all odd numbers and the sum of these
numbers from 1 to num using while loop.
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
for x in "banana":
print(x)
The for Statement (cont.)
The break Statement
• With the break statement we can stop the loop
before it has looped through all the items:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break
The for Statement (cont.)
The break Statement (cont.)
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
break
print(x)
The for Statement (cont.)
The continue Statement
• With the continue statement we can stop the
current iteration of the loop, and continue with
the next:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)
The for Statement (cont.)
The range() function
• The range() function generates a sequence of
numbers which can be iterated through using for
loop
• The range() function returns a sequence of
numbers, starting from 0 by default, and increments
by 1 (by default), and stops at a specified (but not
included) number.
• Syntax:
range([start ,] stop [, step])
Both start and step arguments are optional and the range
argument value should always be an integer.
range() function: Examples
• Using the stop argument
for x in range(10):
print(x)
for x in adj:
for y in fruits:
print(x, y)
Practice Exercise
1. Write a Python program using for
statement that will display all even
numbers from 21 to 59.