Chapter Three Control Statements
Chapter Three Control Statements
STATEMENTS
and
CONTROL STATEMENTS
Prepared by
Eng Mohamed Ahmed Mohamed
Title: MSC in CSE and BSC in ICT
Python Lecturer at Alpha University
1
CONDITIONAL STATEMENTS (Decision Making)
The basic decision statements in computer is
selection structure.
The decision is described to computer as a
conditional statement that can be answered
True or False.
Python language provide the following
conditional (Decision making) statements.
if statement
if...else statement
if...elif...else staement
Nested if..else statement
2
Example program
i=int(input(“Enter the number:”))
If (i<=10):
print(“ condition is true”)
OUTPUT
Enter the number: 9
Condition is true
4
Write a program to check if a number is Odd or Even
num = int(input(“Enter the number:”))
if (num % 2)== 0:
print (“Given number is Even”)
else:
print(“ Given number is Odd”)
OUTPUT
Enter the number: 9
Given number is Odd
6
Example: largest among three numbers
a = int(input(“Enter 1st
number:”))
b= int(input(“Enter 2nd
number:”)) OUTPUT
c= int(input(“Enter 3rd
Enter 1st number:10
number:”))
Enter 2nd number:25
if (a > b) and (a > c): Enter 3rd number:15
print("a is greater") B is greater
elif (b < a) and (b < c):
print(“c is greater")
print(“b is greater")
else: 9
Nested if … else Statements
10
• Example program
n = int(input(“Enter number:”))
If (n<=15):
if (n == 10): OUTPUT
print(‘play football ’) Enter number : 10
else: Play cricket
print(‘play basketbal’)
Else:
print(‘Don’t play game’)
12
Write a program to find sum of number
num = int(input("Enter a number: "))
sum = 0
while(num > 0): OUTPUT
15
Using else statement with while loops
Python supports t have an else statement associated
with a loop statement.
If the else statement is used with a while loop, the
else statement is executed when the condition false.
Program to illustrate the else in while loop
counter = 0
while counter < 3: OUTPUT
Inside loop
print("Inside loop") Inside loop
counter = counter + 1 Inside loop
else: Outside loop
print(“Outside loop")
16
for Loop and for Loop with else
EX-01: OUTPUT
genre = ['pop', 'rock', 'jazz'] I like pop
for i in range(len(genre)): I like rock
print("I like", genre[i]) I like jazz
EX-02:
genre = ['pop', 'rock', 'jazz'] OUTPUT
for i in range(len(genre)): I like pop
print("I like", genre[i]) I like rock
else: I like jazz
print("No items left.") No items left.
Thanks
Prepared by:Eng
mohamed ahmed