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

Review Python

Uploaded by

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

Review Python

Uploaded by

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

·' ~

:~~~
.• LEARNING IN THIS cHAPTER --------------- . python
• oata Types ,n
" Precedence
• Comments .
of Op
era~.,
LB09uage • typeO Function 1n pYth .
• Featul85 of pyth<>" uter IITypes of Cont on
. pyttlOO on vour comP • input() Function . ro1 Stru
. ,nstaii09 · python • Conditional Stat ti!,'=.
a Wortan9Mo<feSofpyth<>O • operators ,n - ernen~
e vanables f h e steps - Input, Processing, and Output
· slsts o t re
rtorrn in your daily life con · Hav
AnY task that you pe
.
the process of creating a
toy by following the given steps: e~~-~
tried to make aday toy? Let us see
o Takerawday.
0 Mould the clay in to the desired shape .
. t dryforsometime.
0 Fiina·uy, colour the toy and leave ,t o. . 'd d. to thre
e major step s. Raw clay is the Input. Moulding I
So you see that the formation of a toy ,s d1v1 e ,n
,<01
an~ drying ts the Processing; and the clay toy is the Output.

Kids ClaY

INPUT PROCESS OUTPUT


Clay Mouldlng the clay Toys made with clay

Figure 7.1: Formation of a Toy

A computer also works in the same manne F' t


the data and finally it g,· e th r. ,rs ' a computer accepts the data input by the user; then
, , , v s you e outp it pro
program is a stet>-by-step sequence f ut. A.com Puter perform
s all thes e ope rati ons with the help of pro ~r
There are many programmin o instructio ns that help the co .
mpu tert o perf orm the give ks
I
g anguages that you can use t n tas ·
etc.lnyourpreviousdass,youhav .
. .
eal d . own teth epro gram s. For example Python,'CC+·
the previously learned concepts of Python. rea Y stud ied the Pyth
on language. This cha pter will help' you in reca pit
• FEATURES OF PYTHON LANGUAGE
Python is a general-purpose, high-level pr
ogramm1.ng Ian
o Simple and interactive guage Which is:
o Platform independent
case sensitive
0
Object oriented
0
interpreted language
O . . bles without declaration
usesvana
0 e. It was created by Guido Va n Rossum at CWI (Centrum Wiskunde
f tures make Python a pop.ula.r languag
All these ea It can be used for des1gmng Console apps (where text-based appricat·ion .is .involved like inc and C++
.ca) . .
& rnformat 1 · . . •
ktop apphcat1on s, We b apphca t1ons, Mobile applications ' Mach'me 1earning, Robotics, and
Des
1anguage )1 •

·ng scientific computing.. . .


performr designed usin g Python are:
r applications whi ch are
somepopu a I

Google Voropbox Quora


You (D Bittorrent
Dropbox lnstagram Quora
Google
You Tube

ER
• INSTALLING PYTHON ON YOUR COMPUT

( 11P I
www.python.org/download
{ You can download various Python distributes from
-
foll ow ing screen:
After installing Python, you will get the

Sllef Qebl,g 914 32


27 201 8, 04: 06: 47) [MSC v.1
Pyt h on 3.7 .0 (v3 .7.0 :lb f9c c50 93, Jun
i t (In tel )) on vin 32 o:c nat ion .
or II lice nse () :tor mor e in:t
11
II
~ ype II c.o pyri gh t •, cre dit s
11

l
>» I

Figure 7.2: Python Shell

V 6 i WORKING MODES OF PYTHON


:
Python works in two different modes
0 Interactive Mode
0 Script Mode
INTERACTIVE MODE
ent is
rpr ete r exe cut es the sta tem ent s one by one. Aft er the firs t statem
inte
In the Interactive mode of Python, the ents are
nex t sta tem ent . It me ans tha t in the Interactive mode, the statem
executed successfully, it moves to the
instantaneously.
executed line by line giving the out put
• · below·
, To work in the Interactive mode, follow the process given •
3
3 7 > IDLE(Python •7>·
o Click on the Start button> All program s> Python •

0 It will open the Python Shell Window where you will see the Python prompt ( >>>)

Type the following commands in Interactive mode and see the output:
tit Ea ... ~ 27 20111 04:06:47) [MSC v.1914 32 bit
'
Pytbon ,. 1 .0 (v3.7.0:1.bf 9cc5093, JUD
ell I on vi.1132 • •license() • for 110re inforaatio n •
.,.._ ■ .......yr1...,t• •credits or . Lanou11oe '
•i...- - r vu ,
>>> ' °'c-t.hon i s II Hioh Level ProoranJUinO
--•" LanO\lllQe I
<l
•~hon i s II High Le~ Proor_,,g
>>>10 ~
10 ~
»> 145.119
16 . 89 I
>» 19<78' ~
True~
»> 100+200
300
>» I

Figure 7.3: Interactive Mode

print() function
display user.
The print() function can be used in the Interactive mode as well as in the Script mode. It is used to
once it is
defined messages on the screen. Using the print function, we can also show the result of an expression,
11
processed.
a
There are many parameters or arguments that can be passed in the print() function. For example:
file £dit stM!{I Y{mdow Help
Python 3.7.0 (v3.7.0:l bf9cc509 3, Jun 27 2018, 04:06:47 )
1)) on win32
Type •copyrig ht•, •credits • or •license ()• for more info
>>> p rint( 'This i s an example of print function ' )
This is an example of print function
>>> print ( 'The sum of 10 and 20 is ' , 10+20)
The sum of 10 and 20 is 30
>» I

Figure 7.4: Using Print Function

We can use many separators with print() function to format the displayed result. These include:
0 ','(comma):To print the next value after a space.
0 '\n' (newline): To print the new value in the next line.

0 '\t' (tab): To print the next value after a tab space ( 1tab=Sspaces).
For example:
Type • ~opyright • , " credits• or •11cense( ) • for 1110re i nformatio n .
>>> print (l0,20)
10 20
>>> print (lO,' \t ' , 20)
10 20
>>> print (lO, ' \ n ' , 20)
10
20
>» I
Figure 7.5: Using Separators In Python

;:_.. KIPS ,//~ ~,:: ?/.1 ,; ,


Eis an Integrated development environment for editl ,
,,dDL . h Pyth ng and running °',.
10~ tiC expression at t e on prompt and press the Enter k h , , ,hon commands If
~f11E! hi th · ey, t e Interpret · we type an
afit the result. Int'. s case, e interpreter acts as a simple cal I er automatically eval t It d
1aY5 cu ator. It execut ua es an
otSP de if you are eva1uating an expression, it Is not necessary t es Instructlons one line at ti
tniS 1110 ' o use the Print() fu a ~me.
1n ~ _ _....,._ml!!.,.; • ~• • - nctlon. For example:
Py1:hon 3.7.0 (v3.7.0:lbf9ccS0 93 Jun ------ \1
el) l on v1n32 ,
27
2018, Oi:06:i7) [MSc v.191 ,
Type •copyriqbt•, •credits" or "licenae ()" f 1't1!\\'
~t~ i/ 'A\
>» 11+22 or ZIIOre information. :in h\,{tr~;
33 'lll \~t\i~'1to
>» 22-11 [\~ i' ~~'.f.~~C-
11
>» 22/10 1\~\ 11
,. i i ~"\~
,S,"~~~
·~
2. 2
2.2 ·tt'.~:,
..~\'SI~• ~~....
>» 2 ,~r........ ~~
m ,;;;_
44
>>> 22••2
484
»> 10+3-2
..
~~
~ _
·- -
:...:::

11
»>
~ ~ - - - - -- - - ;;
Fi~gu_r_e 7.:
=-6-:~u:-,l:-ng_ l_D_LE_ _ ______ -

5CRIPTMODE
In the Interactive mode, Python displays the results of expressions. In the Script mode, however, Python does not
automatically display results. We use an interactive mode when we write small programs because the output in the
Interactive mode is compressed between the statements and is not suitable for writing lengthy programs. So, to
wnte lengthy programs, we use the Script mode in which we can create and edit the programs. The files created in
the Script mode can be saved for later use.
Writing a Program in Script Mode
To write a program in Script Mode, follow the given steps:

0 dick on the File> New File option.


0 Anew file opens. Write the program and save your file by selecting the FIie >Save option.
o The files in Python are saved with the extension .py.
0 Once your file is saved, you can open the same file by selecting the FIie >Open option and execute the file using
FS key or click on Run> Run Module option.
..J!:~ ~~:11!.'P
prl a t t ' Pyt.aon u • lll Qb l.nd t.&t1V\IAQ•')
prlnt llO)
pruit l l0•2001
pr tnt ll t<H I

()pin... Cbl+O
OpenModule.. Alt+M
• or
Reen~ ►

~ll ;""
~ o..

..
~·-
~
J. - IQ/lonlll t
Cbl+S ~ IWlllll
Cld+Shift+s Wlllt'lllll t
ltll<VlOU O
Alt+Shift•S Ci -
ndow Cld+P

Alt+F4
Cbl+Q
1 1- -
,7: Opening a New FIie Figure 7.8: Saving a FIie
~ - -. type() FUNCTION
ata you are working with, use the type() function. It is used to return th
lfyouwan tto knowwhattype Of d edata
of a value. Look at the following example:

~ = ,.,.o .
,..-, .7 .0.•lbt9cCS0'3 • Jun 27 2011, 04 : 01 : 47)

vi.D32
Type •eopyr1 9hl:•, •crecUU

or
•11etn■ eo • tor aore 1.ntoraa1:1on.

>» l:}•- pt! (100)


<cla.ss •1nc: • >
»> c ype ( ' PytllCI' . r
<class • st:r • > _J..,... Value
I
»> t; ype (10.25)
<class •rloat ' >--~ - --,
» > t ype (Tru e )
<Cla.!!S ' bOOl ' >
(oata Type J

>>> t: ype ( fal.,e l


<clas s ' boal'>
»> type (ll>lO)
<class 'bool ' >
>» I
Ln: 15 Col:4

Figure 7.11: Using Type() Function

■) input() FUNCTION
In the earlier part of this chapter, we have used'=' (equal to sign), which is known as an assignment operator
Python. This operator is used to store a value in a variable. The value stored in a variable can be changed duringt
program ex-ecution. But to make the program user friendly, input() function is used, which allows the usertoent
the value during the execution of the program as required.

Program 1:
'file Edit Bun ~ >>>
a -input ( "Enter
RESTART: C: /Users/
Enter your name:AMIT SHARMA
p r i n t (a)
AMIT SHARMA
>>> I

Figure 7.12: Using Input() Function With String Values


Output

Let us see what happens when you use input() function with integer and float values.
Program 2:
- - - - - - --
'file ~ fgrmat Jun T~ "copyright", "credits" or "license()• for •
a•input ( "En ter t h e first number:" ) >»
b-input ("Ente.r the second number:" ) ll!START : C: /Users/BRASllll/DesktOPI
Enter the f irst number: 90
print ( "The s um o f t he n umbers is:" , a+b) Enter the second nmnber: 78
I
________________ _.)
The sum of the numbe= is : 9078
>» I

Figure 7.13: Using Input() Function to Add Integers


Numbers are Concatena ted

In th e above program, when you enter integer values and try to add them, the values are not added. Rather, the
joined together. Similarly, when you try to multiply these values, you will get an error as shown in the program I
below.
Program 3:
fite ldit FanJ!ll Bun .~ s Wi~ ~• J:ielr,

L
1
: a•i nput ("Enter the first number :-;, )-· · -
= ~npu t (" Enter the :iecond number :" )
--

nt( "Ihe product of che n-ers 1 , , " , ••b)'1


1 - --- lll:l?W1 C:1 / 0Hn/ 1WQa/Duhop/n nt11/nyl.py
Entu th• f1 rat rumber: U
t.nt er t.be ■ e:cond nllllbe..r : t,
t r a ~bac lr: (IIC !!it. re c ent call la5t) :
n .h: • c : / Uaera / BKASIO.R/Oesnop/P YTHON / t r-yB . p y• , l in e 3 , in <.me>d.U e>
print ( •Thr: prOduc:c of t.he number,9 ia : • , a • b )
Typ«!:rro r : c ar, • t aultipl y aequence b y non - 1-nc ot type • au:•
»>
Figure 7.14: Usina lnn11tf\ c ........
- ~ •
variable is a st . bY default a d
pe ns t,ecause the data type of a nng a
·
stnng can neither be added nor
be
· r,ap eg ero raf lo t ' n
trin gin toa n int
fflP . i·e<
1
f.SO, toc on ver tth iss a va1ue, we use th fu netIonsint()andfloat()respectlvely.
ft1P e
if1I' aro4:
pregr !IH Sl b.1t II nt•l > I on vi.nu
T •
~ COS ,~19 bt•, • c ~ t • • or •11c tn•e 11• f
or 110u
>>>
st nuat >er : " ))
_.ui :;( iJIP" t ( "t:n ter tbe f1.r
>oo r.=< ,r: " I 1 ~~ ~.11&5 U=T~t
=
. .::.: .T :C1/ U•e r•/ •u•• ,._,•0.•lr top/ P~
--.- ~••
t,o'1D I: 11.ap ut ( " £nte r 't.he
pr i.nt ( "T?-.e prod -Jct of tl:e
seC<
nu:b er.!! ts:• , ••b) l~~ h e fir" t n\Uliber , 56
Entt ,r tth
Ent er
-- -
Tb e s e con d huab ,u-: U
I >>>
" P l"Odu ct ot th e n\Ulil)er,, l a, Hoe

gers
Figure 7.15 : Inp ut Ya lu• ••• Inte Out put

I OPERATORS IN PYTHON
t L
s dat a types in Python is clear
the concept of variables and variou o you. et us perform some arit
hmetic and
NoW rations on the variables.
iogi'31ope Wh t .
of tw o numbers say 20 and 30 se
her asks you to find the pro du ct a w1 you do? Yo uw illm ulti ply the
11
ult 60 0. , , .
uw illg ett he res
1fateac ·e 20 *30 an dyo
numbers,,..,
calculated as foll ow s:
so,if a::20and b=30, the n the pro du ct wil l be Operators

- 0 * 30 =600
c::a * b-2 ltip ly these two
the above exp res sion, is a sym bol , wh ich is used to mu
'*'
In
sum of these c= a* b
if you use '+', you wil l ge t the
numbers. Similarly, in place of' *',
numbers, i.e., 20+ 30 = 50.
rat ion s (Arithmetic, Relational, and
aperators are used to pe rfo rm dif fer en t ope ve Operands
me ani ngf ul result. For example, in the abo
Logical) on operands and giv e a
led operators,
s like '+', '*', an d'= ', which are cal
exp ressions, we hav e use d sym bol
are called operands.
. f ~
and variables like a, b, and c, wh ich
ed in the following table:
vide s diff ere nt typ es of op era tor s to wo rk wit h. These are list
Python pro
Examp\e

data. These
ope rat ors are use d to per for m arithmetic operations on the
Arithmetic These
Operators can be fur the r classified as:
ary - a=10, a=-10
a single operand. Unary + and Un
o Unary Operators: They wo rk on
two operands:
o Binary Operators: They wo rk on 30+20=50
a values.
o Addition ( +): To fin d the sum of the dat 100-30=70
data values.
o Su btr act ion (-): To fin d the difference of the 10*2=20
du ct of the data values.
O Mu ltip ly( *): To fin d the pro 10/4= 2.5
imal for m.
ber s and give the result in dec
O Division (/): To div ide the num
result in
ide the numbers and give the
O Int ege r Div isio n(/ /): To div 10//4=2
inte ger for m. 10%3=1
.
num ber s and give the remainder
O Modulus (%): To div ide the 3**4=81
O Exponential (** ): To fin d
the pow ers of the numbers.
>>> ------ -
USTAaT : C:/IJH.ra/llllUQaJou -----...
ter tbe firn nuaber : ftopf !!'.!nia. ,
1
tntez- tbe eeconcs nUlllber: 15 tn.o.,
The aaa of ~e maber• la: : 35
1be difference bet.ween tbe nuabera la : 5
The product. ot Ule nuabera: ia: : 300
Program 5: The qao Ueiit or tbe n . - r e la : 1. 33333U33
Tbe an.aver f'o r the lnt.ec;rer dlvtsi.on la : 333333 3
1
Tbe cube o f the t1rat t t ~ r U : e o oo
>» I

Figure 7.16: UslngArtthmetlc Operators Output

.
'String operators wo_rk on the string values. These operators are of two
String
aperators types:
>»'KIPS'+ 'Learning'
• Concatenation ( +): It is used to join two string values. »>Kl PSLeaming

>»KIPS*4->
0 Replication (*): It is used to repeat a string for a number of times.
>»KIPSKIPSKIPSKIPS

, Program 6:
a -inpu t ( "En te.r the fir:st string : • )
b-inpu t ( "Enter the second string : " )
print( ffl'wo :strinqs j oined together:" , a+b)
p rint ( "The replication or the string : • , a *6)
1 :1ype •c:opy._.o.gu~ , •c._~~s • Or
>>>

Enter the second string: litemoon


Two s t rings j oined together : GoodAftemoon
......cense O " tor 110re lilfi,-

llSl'llT: C :/Osers/llH&SDR/Desln:op/PYT!!c:w/
Ent er the first s t ring: Good

Ihe replication o! the string : GoodGoodGoOdGoOdGoodGooc!


I >>>

Figure 7.17: Using String Operators Output


Assignment This operator is used to assign a value to a variable. a=290
operators ( =)
The value 290 is
assigned to the
variable a.

RESTART: C: /Users/BB

a - 100
i•1op/Pr OH/try12.py
Program 7: b-200
c-a+b
p rint (c)
I

Figure 7.18: Using Assignment Operators


Output
Relational These operators are used to show relationship between two operands. They
Operators
compare the values assigned to the operands and give the output in a Boolean
expression. These are:

•0 Less than:<
Greater than: >
a:::100
b:::30
0 Less than or equal to: <=
a>b True
0 Greater than or equal to: >= a==b False
0 Not equal to: !=
0 Equal to: ==
~
., , .-----r---Iilfi~5~a~~~
. -•. :;~~~- - -~ii-;;-;~"----·-----·
100
---- - .1
1 t,-200
print (a<bl
~ "oa»YUot,t•, • ond1t1• or "l1C41M• o • for
»>
1
I
....od'l'aro 8:
r, -i,·
I
pri;nt (a>l00)
pr1.nt ( ~ )
p r i.nt {b>-23-1)
Tru•

... ..
hho
t nae
\
aunar, C1/UHr1/IIUW/o.1nop;
I
pr Ult (a ! -ti)

Figure 7.19 Ualng Relational Operators


. t..,.e

Output
, These operators are used to combine two or m0
They provide the result \n the form of True or F ~ cThond1tlonal statements. 1•28
1 se. ese are of three ty
• and: Gives the result 'True' If all the specified di I pes: b=78
con tans are true.
a<ioo and b<a➔ \ \
True and False ➔ ~
0 or: Gives result 'True' If any one of the specified conditions Is true. False
a<ioo orb<a
1 0 not: It reverses or negates the given condition. If the condition Is True It True and False ➔
evaluates to False, and vice versa. ' True
not a<ioo ➔ not
True ➔ False
i >1-onvin3T ___ - - - ·- -
.-100 type •copyr1Qht.•, •crGit.1• or •11ce.n1e () • f I
>>> or acre
,11-200
' pr1.nt(a<l> and b>a)
print: (a>100 o::c b>a)
\ True
IIESTU.T : C' /UHu/~QJ.JDunop/ tn\
True
print (a<"tl and b>100)
PrOgram 9: print (b>-234 or b>100) \
True
True
: pri.nt(a!-b) True
1\
p::ci.nt( not: (a>100))
j True
»>

Figure 7.20 Using Logical Operators


Output

Let us observe the use of various operators in Python programs:

I) PRECEDENCE OF OPERATORS
The precedence of an operator refers to the order of priority in which the operators are eva\uated in an express\~
In case, two operators with the same precedence are the part of an expression, then assoc.iativit')' is taken \nto
consideration. The Associativity of an operator determines the direction of operators from which s\de (.e\ther \ett to
rightorviceversa)the expression should be resolved.
Precedence of operators

Operators .._........... Desalpt\on


0 Parenthesis
** Exponentiation
+x, -x + Unary, -Unary
*, I, I I,% Multiplication, Division, Floor Division, Modulus
+, - Binary Addition, Subtraction
<, >, < =, > =, = =, != Relational Operators
not and or Boolean/Logical operators
--~~ t ors in an expression.
~,~~ BODMASruletoeva Iuate the opera
U
Remember. se ddltlon Subtraction)•
.., __.,ets Off Divide Multiply A
(BODMAS: .,.-cn,.ft

a> COMMENTS IN PYTHON ogram with the purpose of making the COde .
that are added to a pr . easier to
Comments are the statements II 1gnorecommentsduringtheexecut1onoftheprograrn.1fy
nderstand. compilers and ,n. terpre tersge nera y . h . oUadc!
u gram Python wl 11 no t show the text written mt e comments m the output. Althn. .....
...""Wl
comments to your Python pro , d d fr m the users' perspective.
comments are optional, they are nee e o
two types of comments: . .
In Python, there are .
t e created by beginning a hne with the hash(#) character and
• g1e Line Comments: Single line commen s ar
0 Sm are
maticall terminated at the end oft he I'me. ,
auto Y • gram may need to explain things in more details, which may excAM
Multili ne comments: Sometimes your pro .
'
one line. Such comments are ca 11 ed mu ltTne comments. we can provide multi·1·me comments m. ...~
a program by
II
adding a delimiter("'"') at the beginning and the end of the comment.
For exampfe:
»> #This is a program used to calculate the simple interest.
>» """Program to enter the rate of interest, principle and time period.
Use these variables to calculate the simple interest and
Print the same. """
Remember: Single line comments appear in red colour and multiline comm
ents appear in green colour.
• TYPES OF CONTROL STRUCTURES
In a computer program, statements are generally executed in a sequential mann
er. However, at times, the userm
need to change this order of execution by repeating or skipping the execution
of a few statem ents, subject to aglv
condition. In such a situation, the flow of execution is altered by the use of Contr
ol Statement s.
Before proceeding further, we must understand the different types of const
ructs/statements in programming ti
govern the flow of the control of a program.
There are different types of statements that control the flow of a program. These
include:
OSequential Statements· In Sequent' I
· ia cons t ruct, t he statem ents in a program are executed in a sequen
manner, where one statement is follo db th
. we Y e ot her, with no possibility of branching off to another action.
, For example, to calculate the area f •
/ calculate its d . 0
a rectangle, first, enter the length and bread th of the rectangle, t,
area an print the result.
Program 10:
81 iiit
l•lJlt (input (~Enter the len th
- ~-.
b-int (1nput ( "l'.nter t he b 9 or t he r cct4n9l e: " )) Type •copyr ight• ~- .-;~-;; ,;- o~ - •11ceu e
ar•l•t> re4dth or the rectang le : " )) >>>
pr1n t(" Thc 4ree ot th RESTAllT: Cc/OH ra/Due ab l'baJ Nr/~t
.e rectano le is :~ , ar) nti al •t•teme nt• .
~ter th.e len,;it.h ot the rectang le . 20
..... ter tbe bread~k t
Th .e ar · ...... 0 t.he reci;an gle· : 40
>>> ea of the rectang le ia : aoo
Figure 7.21 : Program to Calculate~ - --_..,.,..,. - ... == ...._,_,. ._ i

,, Ge nm ,,,
, . oal statements: In programming
language
c~'tt to a specific location depending on the ou s, conditional statements cause the program control to
0
l
1 tcome of the condltlonal express\o
trat'~ l)etween the two altema~iv n. Every decision Involves a
es 'Yes' and 'No' result. If a condlt
t~ ts is executed, otherwtse, the lona\ statement Is true, then one set
other set of statements Is execut of
st~ y divisib\e by 2 then it is ed. for example, If a number Is
an even number, otherwise It Is an
,~ statements in the coming section. odd number. You will be studying
more
~ -~ atements: These statemen
ts repeat a set of statements for a
1td3tJ:~ iti on is true. When the giv specific number of times as long as
1 en condition becomes fa\se, the con the
~ - . n stops. for example, the tro l com es ou t of the loop, and the
loop wi\l be repeated for 10 times
~ - You will learn more about the till the som e of the 1Onatural numbers ar
se statements In the next chapter.
c0MomoNAL STATEMENTS
f the statements are generally execu
ria~ ; execution, either by repeating or
ted sequentially. However, at times,
skipping the execution of a few
the user may need to chan
statements, subject to a glvl
ttaS (1(ief ch situations, the task can be perfo
...Aiti()ll. In SU rmed by the use of Control statemen
cOI"''- • sta tem ts.
ents che ck the con dition and execute the statements accord
conditi 1
'Ot witona h imple example. Suppose, you wa ingly. Let us understand tli\s
nt to withdraw some money from
cancePt as ney only if you enter the co the ATM. You w,1.1 be a\Iowe d t o
~ themo rrect PIN number. Look at the plan
of action based on the condition:
• I p.,dlllon
If correct PIN is entered
\\ Plan of Action
You can withdraw the money
l
If incorrect PIN is entered You cannot withdraw the money
ou can
follow one plan of action if the con
Thus, observe t hat Y dition is true, otherwise, the other
followed. Let us analyse it with the plan of action is
help of a Flowchart.
. •cton·al representation of the flow
Aflowchart ,s a P' of steps or a procedure to solve a pro
blem.
.
START
i----·
Goto the ATM
and enter the PIN
i.
Cannot withdraw the No Is the Yes
Withdraw the
money Correct money
PIN entered?

STOP
Figure 7.22: Flowchart Olspla
ylng the plan Action Based on
a Condition
. ' ' ' ' .'''''"-'\.\.\.\.\.\.\.\.\
. t element is the condition, based on which th
~
-~- t, the most ,mportan • d. • e decisi
In the conditional statemen the evaluation of this con 1t1on. Let us und on is b
depends on erstand as~d
The execution of the statements the "aN .
0
· below:· ~ ~-~~-..., .---- 14
conditional statements gtven

. ed to evaluate only one


This statement ,s us rse of action if the a=int(input("Entera number:"))
if rtorms a cou
condition. It pe · therwlse It skips the b=int (input(" Enter another numb
er:"))
condition evaluates to true, o if a ==b:
statements. print ("The numbers are equal")
Syntax: Output
Enter a number: 34
if <condition>: Enter another number: 34
statements set The numbers are equal

Program
The if... else control structure is used when either
if...else a=int (input(" Enter the first number:"))
of the two different actions are to be performed
b=int (input("Enterthe second number:"))
depending upon the result of the conditional
if a>b:
expression. It works with two blocks: if and else.
print(a, "isgreaterthan", b)
In case the conditional expression evaluates to
else:
true, the statements in the if block are executed,
print(b, "is greater than", a)
and if the result is false, then the statements in
the else block are executed. Output
Syntax: Enter the first number: 456
if <condition>:
Enter the second number: 234
statements set 1
456 is greater than 234
else:
statements set 2
if ...elif...else Sometimes we need to work with multiple Program
conditions. In this case, only using If-else a=int (input(" Enter the first number:"))
construct does not serve the purpose. The lf-ellf- b=int (input("Enterthe second number:"))
else st atements provide a compact way to if a>b:
perform multiple tests on a condition. print (a, "is greater than", b)
Syntax: elif b>a:
if <condition>: print(b, "is greater than", a)
statements set 1 else:
elif <cqndition>: print(" Both the numbers are equal")
statements set 2 Output
else:
Enter the first number: 548
statements set 3
Enter the second number: 548
Both the numbers are equal
ndftio In the
we can aJso check multiple co ns P-rogram
. er:
followmgmann er:''))
a=fnt{input("Enterfirst numb
mber:"))
if <condition>: h=lnt (Input ("Enter second nu
st.atements set 1 C= lnput ("Ent er your choice of operator.")
.
1f c== '+' :
ellf <condition>: prlnt("Th e sum of the numbers Is:" a+b)
. '
statements set 2 eltf C: : 1. ' ;

elif <condition>: Print ("The dIff erence of the numbers Is:" a•b)
. I
elif Cc::'*' :
statements set 3 ers Is:" ' a*b)
print ("The product of the numb
elif <condition>: el,f C==-'/' :
ers Is:" , a/b)
statements set 4 print ("The quotient of the numb
else :
else:
print ("Wrong operator input" )
statements set S Output
Enter first number: 1oo
Enter second number: 50
Enter your choice of operator•
0
The product of the numbers is :500

ve.
gu age which is simple and interacti
O Python is a high-level lan otics,
b ap pli cat ion s, mo bil e applications, desktop applications, rob
O It is used to design we uting.
and perfonning scientific comp t mode.
n wo rks in tw o differ en t mo des, Interactive mode and Scrip
O Pytho y.
en ts are ex ec ute d lin e by lin e giving the output instantaneousl
·I In Interactive mode, the statem wh ich are ex ec ute d as afile and can be saved for lat
er use.
d ed it pro gra ms
I Script mode is used to create an
sion .py.
o The files in Python are saved with the extenin an identifier, such as a variable, is known as its data type. The data type
red
o The type of data value that can beutestotha t tells what kind of data it can hav
e.
var iab le is an att rib execution.
of avalue or a
res the value s wh ich can be changed during the program
0 Avariable is astorage loc
ation tha t sto
(A rith me tic, Re lation al an d Logical) on operands and give
0 Operators are used to pe
rform different operations
and String
meaningful result.
ed in Py tho n: As sig nm en t, Arithmetic, Relational, Logical,
0 There are five types of
operators us
easier to
operators.
ded to a pro gra m wi th the purpose of making the code
0 Comments are the statem
ents that are ad
ation
understand.
en ts cau se the pro gra m co ntrol to transfer to a specific loc
0 ~n programming languages,
Conditional statem
conditional expression. ecution of statements In a progra
m.
ependlng on the outcome of the tha t co ntrol the flo w of the ex
O There are three types of co
nstructs in a program
l, and Iterative.
These are: Sequential, Conditiona ents.
0 if... else, if... elif... else are the three types of conditional statem I
If'
~\ \, ,
\\ \\ ~ ,.KIP~

You might also like