Python
Python
UsingConditional
Statements in Python
#RoadMap
P Discussthe significance of conditional staterments
Explainthe use of relational and logical operators
0P programs to implement using if, if..else and
Create conditional constructs
0 if.elif..else statements
Input age
NO
Is NO Isageæ10?
agez18?
YES
YES
Do you work NO
in a
government
office?
YES Ticket Price=0
Ticket Price=200
Ticket Price=75
Ticket Price=100
STOP
For example,
If the weather is not sunny, then Iwill go shopping.
If my homework is done, then I will watch a movie.
check
While writing programs, conditional or selection staternents help us the
and choose aset of statements to be executed. They help us control
of flow of a program, 1.e., some portions of the code are executed only if directconidoinftions
certain
conditions are met.
Let us begin by learning about the relational and logical operators. These
help us form conditions which are used with conditional statements. operatorS
RELATIONAL OPERATORS
Relational operators are also known as comparison operatorS as they are used te
Compare two values. When we use relational operator, the output is either
True or False.
V
<= Less than or equal to
Greater than
Greater than or equal to
Table 7.2 and Fig. 7.1show the results of relational operators when used with
variables a and b.
110)
72. Results of relational operators with a=10, b=8
Table
>>> a=10
|>>> b 8
Expression Result |>>> a 8
a b False False
>>> a f b
a!= b True True
>>> a<b
<b False False
>>> a<-b
a <= b False False
>>> a>b
a>b True
True
a b True >>> a>-b
True
relational
A Fig. 7.1 Using
numeriCvalues
operatorswith
comparison betweentwo
can
use relational operators with string values also. The "Sunflower".
We valuesis case sensitive, i.e., "sunflower" is not the same as
string operators with
Ldiscuss the use of == (equal to) and != (not equalto)
will
Here, we
stringvalues.
Values
Using Relational Operators with String
"Morning",
Assume x="
y="Night"
inequality operators when used
7.2 showthe results of equality and
Table 7.3and Fig.
and y.
with variables x >>> x="Morning"
|>>> y="Night"
Table7.3
Result >>> x==y
Expression False
X == y False >>> x!=Y
True True
x=y
A Fig. 7.2 Using relational
operators with string values
the assignment operator whereas == is the
We must carefully note here that = is
elationalequal to operator.
Compares value in
Variable a with the
Assigns value
value 2 for equality
2 to variable a
a==2
a-2
LOGICAL OPERATORS conditions before
112)
singLogicalLOperators
Assumeage-12, sportscricket"
|
15
and Eia 7.3 show the
able
nge
andsports results of logical
oble
75
operators when Used with variables
agem12
>>> sportserickes"
Expression P> age>10 and sportsfootball"|
age>l0and sportgme Result False
>3> age>10 or sports football"
age>l0or
(sports
sportsm "foot
cricket")
ball"False
football" True
True
>>> hot (sports
False
cricket")
False
Fig. 7.3 Using logical operators
#SnapCheck.
Find the output of the
following if the variables subject, fee and num have
heenassigned the following values:
subject
-"English", fee = 2000, num = 100
subject!= Hindi"
Expression Result
CONDITIONAL STATEMENTS
discussed earlier, conditional statements help us check conditions and choose a
voCk of code to be executed. Let us learn to use conditional statements in Python.
113)
if Statement
of code
statement is a conditionalstatement that is used to execute a block
ITdepending upon acondition. They help to controlthe flow of the program and hence
are also known as control statements. The body or block of staternent(s) under the
if staterment is indicated byindentation. The
Syntax: indented line. Thee
body starts with an first
unindented line marks the end.
if condition:
statement(s)
Ifthe condition is True, then the block of statement(s) is exeCuted.
"
statement(s) is not executed
" If the condition is False, then the block of
understood using the
The flow of control when if statement is used can be
flowchart:
fol owing
False
Condition
True
Body of if
114
M.else
Statement
statementis a
Kese
foondition:
Block of statement(s)
executed when
statement(s) condition is True
Block of statement(S)
se
statement(s)+ executed when
condition is False
is
.Ifthe condition True, then the block of statement(s) under if is executed.
. Ifthe conditionnis False, then the block of statement(s) block under else is
executed.
Theflow of control when if...else statement is used can be understood using the
ROwcharttshownnin Fig. 7.5.
False
Condition
True
Code
age
PrOgram to display a message based on the
ge=int (input("Enter your age: "))
E age>=18:
the right to cast vote")
Print ("You are an adult and have
else:
cannot cast a vote")
Print (You are not an adult and
115)
Output cast a vote
14 cannot
Enter your age : adult and
You are not an use of if...elso
Output
capital letters
Answer by typing in located: AGRA
which Tai Mahal is
Name the city in
You guessed it right!!!
Code
square based on user's choice
#To display area or perime ter of a
side=int (input ("Enter the side of a square: "))
to
choice=int (input ("Enter 1 to find area and any other number
find perimeter: ") )
if choice==1:
print ("Area= ",side*side)
else:
print ("Perime ter= ", 4*side)
116)
the side of a square: 4
#SnapCheck.
programto
according accept
to the the
Witea
message
follo percentage
wi ng fromthe user and
display a
Percentage conditi ons.
>-80
<80
Message
"Good Performance'
"Work Hoard"
elif..else Statement
Therearesituationsthat require multiple Ifmother gives me more than 100, Iwill
buy a cake. If she gives me money lesS
tobe
onditons checked. This may lead to than 100 but more than 10, I will buy a
naTyalternatives.
chocolate else Iwill buy a candy.
example,considerthe
ar
seudocode:
following
CHOCOLATE
EMoney>100 THEN
Buy a cake
ISE IF money>10
THEN Ooo
Buy a chocolate
BLSE
Buy a candy
True False
Condition
of elif
Body of if True
Code
display the product to be purchased
# Program to
(input ("Enter the money received: "))
money=int
if money > 100:
print ("Buy a cake")
elif money>10 :
print ("Buy a chocolate")
else:
print ("Buy a candy")
Output
Enter the money received: 15
Buy a chocolate
118
#SnapCheck
Execute the
following piece of code. What would be the output if the input
given bythe user is as follows:
numl=20, num2=30,
condition (fruits"appla'
will the
2. For which of the following options
evaluate to FALSE?
b. fruit="apple" gty5
a. fruit"mango", qty15
d. frui t nango",
C. fruit-Mapple", qty-100 qtys
options willthe condition (fruit "apple and
3. For which of the following
qty >10)evaluate to TRUE? b. fruit="apple" gty5
a. fruit="mango", qty=15
d. fruit="mango" gty5
C. fruit="apple", qty=100
score entered by the user is 15?
4. What output willbe displayed if
1f sCore == 100:
print ("You win")
elif score>=50:
print ("You did well")
elif score>=25:
print ("You should practice more)
else:
print ("You do not know the game")
1. operator.
2. is an example of logical operator.
3. The != operator helps us check for
4. if..else is a
statement.
5. We use
statement to check for multiple conditions.
(120
Anawer
se of ons.
isthe
/Wma,
tis OcOnditionat
relational ond ogicot operetoes?
Lplain
the, staterment?
e use of if..else
statement
OpenForum
onthe1
discusS/on
mportance of Conditionol Consttucts ini
intheclass. Prcgrornrir con te
DIY
LobActivity
bxecutethefollowing statements on the Python prormpt and write the Outputin the
spaceprovided,
Statement Output
Write a program to take the number of hours from the user and display the charges
to be paid.
122
ScreenShot
thefollowing co
code and answer the questions that follow:
Consider
grade)
print("Your grade is: ",
#HyperLink
critical thinking.
promotes
centuryskill. It asked to code some
LifeSkills
bea necessary21st Students can be understandingthe
considered to communication. After programs based on
Coding is collaboration and MathematicsandScience.
Mathematics,
creativity, problemsof numbers in
simple real-life and
even/odd
integers developed.
concepts of
concepts can be
these