0% found this document useful (0 votes)
44 views

Python

Uploaded by

zc9n8s9w2f
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views

Python

Uploaded by

zc9n8s9w2f
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Onl

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

for a concert is calculated as per the given


flowchart.
price
Theticket START

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

Print Ticket Price

STOP

Verma family is as follows:


age of different members of leading private company
Ihe
Verma: 45 years, works for a office
Mr. government
years, Works ina
" Ms. Verma: 40 How much
years concert.
(daughter): 11 want to attend
the
* Ria Verma Verma family
Allfamily members of to attend the concert?
money will thefamily pay 10S
In everyday life, we evaluate ai number of conditions beforetaking a decision,
We check conditions and then choose an appropriate course of action,

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.

The following table lists the relational operators in Python .


Table 7.1: Relational operators
Operator Description Output when relational operators are us
Equal to (Equality)
true false
Not equal to (Inequality)
Less than

V
<= Less than or equal to
Greater than
Greater than or equal to

Let us consider some examples to understand the use of relational operators.

Using Relational Operators with Numeric Values


Assume, the following values for the variables a and b.
a = 10, b = 8

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

In everyday life, we have to often check for


multiple
deciding he
when multiple
action to be taken.

While writing programs, logical operators


logical
are
operatorsand,
used
or, notin Python. condiTheytionsgivearethetn
be tested. There arethree
False.
result as either True or
the help ofsomereal life examples:
logical operators with
Let us understand
IS
the market if it is sunny and car
Iwillgo to
available.
book if either | have done my
Iwill read the story holiday.
homework or tomorrow is a
topic other
will read the book if it is based on any
I
thanwar, ie., not (topic is war).

Table 7.4: Logical operators


Description
Operator
value only if both Conditions are True
and The and operator gives a True the two conditions are Eol.
either or both of
It gives a False value if
gives a True value only if both oreither of the han
or The or operator only if both the conditions
conditions is True. It gives a False value
False.
value if the condition is False and o
not The not operator gives a True
False value if the condition is True.

and any other


In Python, 0 (zero) is considered as False value
qives th
#FY numeric value isconsidered as True value. So, not (0)
result as True and not (1)gives the result as False.

Like Python,another programming language that is widely u


the field of Artificial Intelligence is R. Rwas created by Ross
and Robert Gentleman at the University of Auckland.

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

(fee + 100) <= 3000


Tee
(num*2) (fee/10)
(subject="English") and (fee == 2000)

(num ==200) or (fee != 1000)

Python is widely used in the field of Artificial Intelligence and


#IRL Machine Learning. Artificial Intelligence is the branch of computer
science that enables a computer to think and take decisions like a
human being.

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

A Fig. 7.4 Flowchart of if statement


Let us write aprogram using the if statement.
Program 1:
Write a program that takes age fromtheuser and displays the message "You are an
adult and have the right to cast vote" if the age is greater than or equal to 18.
Code
#Program to display a message if the age is greater than or equal to 18
age=int (input ("Enter your age: "))
if age>=18:
print ("You are an adult and have the right to cast vote")
Note the indentation. Press Tab key to indent.
Output
Enter your age: 30
You are an adult and have the right to cast vote
The above program displays the required message if the age is qreater than or equal
to 18. However, the program displays no output if the age is less than 18.
Let us see how we can handle this situation with the helo of if...else statement.

114
M.else
Statement
statementis a
Kese

betweentwo conditional statement used whern we want the


blocks of code
&ueor
False, depending upon whether the conditton
progra

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

Body of if Body of else

A Fig.7.5 Flowchart of if...else statement


Program 2:
Vrite a program that displaysa message based on the age entered by the user.
Condition Message
=18 Youare an adult and have the right to cast vote
18 You are not an adult and cannot cast a Vote

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

Let us consider some more


programsto
understand the
statement
user.
Program 3: entered bythe
check the answer
Write a programto
Code the user
answer given by
check the letters")
# Program to i
capi tal
typing in Mahal is 1
print("Answer by
the city in which Taj 10cated: ")
city=inputt("Name
if city=="AGRA" : right!!!")
("You guessed it
print
else:
print ("Wrong Answer")

Output
capital letters
Answer by typing in located: AGRA
which Tai Mahal is
Name the city in
You guessed it right!!!

Program 4: square depending upon the


perimeter of the
Write a program to display the area or
choice entered bythe user.

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

Dd area and any


16 other number te tind perimeter: 1

#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

When multiple conditions have to be checked in a program, we can chain the


onditions using if..elif (elif means else..if). We may use else statement at the end to
Rciíiy the action to be taken if none of the conditions are True.
Sintax:

tcondition: Block of statement(s) executed


when if condition is True
statement(s)
elif condition: Block of statement(s) executed
when elif condition is True
statement(s)
se: Block of statement(s) executed
when none of the conditions are True
statement(s)
used can be understo
if..elif..else statement is
The flow of control when
flowchart shown in Fig. 7.6.
USing the
false
Condition
of if

True False
Condition
of elif
Body of if True

Bodyofelif Body of else

Flowchart of if. elif.else statement


A Fig. 7.6
statement.
program that uses if...elif...else
Let uswrite a
Program 5: to decidethe productto be purchased depending uponnthe money
Write a program

entered by the user.

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,

# To perform Operation based on the operator


m)int (inputEnter the first number: "))
m2int (input (Enter the second number: "))
op=input("Enterthe operator: ")
if op4r
print (sum=" ,num1 +tnum2)
elif op=="-":
print ("Difference=", numl-num2)
elif op=="*":
print ("Product=",num1 *num2)
elif op=="/":
print (Quotient=", numl/num2)
else:
print ("Not a valid
operator")
#Bo

Operators that Conditional Statement:


Relational Operators: helps us check
make comparisons and statement that
are used to A choose a set of
as the result.
False value conditions and
qive a True or executed.
Operators: Operators that are statements to be
Logical conditions and give
used to combine as the result.
False value
a True or

THR O)WBACK ==, !=, >,>=, <,


<=
relational operators:
Python has six operators: or, and, not statement are used to c
logical if...elif...else
Fython hasthree if..else statement and executed.
statement. block of code to be
ne if choose a
Conditions and
#LetUs Tweet

A. Tick( )the correct answer.


1. Find the odd one out

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")

a. You win b. You did well


C. You should practice more d. You do not know the game

B. Fill in the blanks using the words given below.


Inequality if..elif...else relational conditional or

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

print (12 21)


print(10 10)
print(jupiter"!mars")
print("venug ! v e n u s " )
True)
print (True and
True)
print (False and
True)
print (Fal se or
print (False or False)
print (not True) != 88)
"venus" or 99
print ("mercury"
that helps street children.
an organisation Bhas 55
collected funds for paid 50. Class
2.1Two classes havestudents, Each child in Class Ahas program to find out which
ClassA has 48 has paid R45. Write a
Class B
students. Each childin funds. fromthe user.
more rectangle
class has collected
length and breadth of a
the user is 1 otherwise
3. Write a program to accept the choice entered by
rectangle ifthe
Display the area of the rectangle.
perimeter of the
display the
4. Write a to calculate the fare for a bus trip
program
from Delhi to Shimla on the basis of the following
Conditions.
Fare Amount
Condition
Age Below 5 Years No Fare
Between5 to 10 years 500/
More than 10years 650/
Ihe program should take the age of the passenger from the user and
the fare accordingly. then dispay
Project
AShopping mall offers the followingdiscounts to the customers.
Bill Amount
Discount
More than or equal to 5. 000 but less than 10,000 500
More than or equal to 10,000 but less than 15, 000 750
More than 15,000 71000
Write a program totakethe bill amount from the user and then display the
resultant amount to be paid by the customer.
Note: Resultant Amount = BillAmount - Discount)
2. An Internet Service Provider company charges its customers accordingtothe
number of hours they have used the Internet.
Number of Hours Charges
Less than 10 hours 7300
10 hours to 20 hours 400
More than 20 hours 500

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

marks=int (input ("Enter marks : "))


if marks>=90:
grade="A"
elif marks>=80:
grade="B"
elif marks>=70:
grade="C"
else:
grade="D"

grade)
print("Your grade is: ",

variables marks and grade?


in
the
t data type ofthe value marks are 76?
Whatis a student if the
1.
grade will be assignedto assigned the grade"D"?
woulda student be
2. What condition
LInder what

#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

You might also like