Review Python
Review Python
:~~~
.• 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
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
•
l
>» I
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
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
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
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:
()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.
■) 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
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
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 :" )
--
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
.
'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
>>>
llSl'llT: C :/Osers/llH&SDR/Desln:op/PYT!!c:w/
Ent er the first s t ring: Good
RESTART: C: /Users/BB
a - 100
i•1op/Pr OH/try12.py
Program 7: b-200
c-a+b
p rint (c)
I
•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)
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
»>
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
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
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~