Page 315 - Artificial Intellegence_v2.0_Class_9
P. 315
The if…elif…else Statement
When there are multiple conditions in a program then it is handled by using elif statement. It means if the
previous condition is not True then try this condition written next to elif. If one condition is True then the
statements below it will be executed and the rest of the conditions given using elif will be ignored. In case all
the conditions written with elif are not True, then the statements written just below the else statement will
be executed. The syntax of the if…elif…else statement is as follows:
if (condition1):
Statements 1
elif (condition2):
Statements 2
elif (condition3):
Statements 3
...
else:
Statements executed when all above conditions are False
Where
• if, else, elif are keywords.
• condition1, condition2 and condition3, …., can be any expression.
• statements1, statements2 and statements3 are always indented can be single or a block of statements.
Program 5: To input two numbers and an operator from the user. Display the result calculated based on the
operator entered.
Algorithm Flowchart
Start START
Input N1, N2, op
if op is same as that of '+' then Input N1, N2
Display N1+N2
Otherwise, if op is same as that of '-' then Is
Display
Display N1-N2 op = "+"? Yes N1 + N2
Otherwise, if op is same as that of '*' then
Display N1*N2 No
Otherwise Is Yes Display
Display "Wrong operator entered" op = "–"? N1 – N2
Stop
No
Source Code:
Is Yes Display
N1=int(input("Enter first Number :")) op = "*"? N1 * N2
N2=int(input("Enter second Number :")) No
op=input("Enter an operator(+, –, * only) :") Display
"Sorry! Invalid Operator"
if op=="+":
print("The addition is", N1+N2)
STOP
elif op=="–":
Introduction to Python 313

