You are on page 1of 23

Computa tional Th' k'

d G . m mg
an etting Start d
with Python e
~ ; Introduction
~ , computational Thinking 5.5 Working in Python
:, .
_, python - Pluses 5.6 Understanding First Program/Script
: .)
, ~ python - Some Minuses

,.1 INTRODUCTIO N

The word Python - isn't it scary ? Does it brin


g the image of big reptile that we prefer to see
either in jungles or zoo ? Well, it' s time to chan
ge the image. Now on, you'll remember word
Pytlwn for its playfulness and pleasant productiv
ity. Confused? Well, Don't be - because, now
on you'll get introduced to a new programmin
g language namely 'Python', which promises to
make you a big programming fan :-).
Python programming language was develope
d by Guido Van Rossum in February 1991.
Python is based on or influenced with two prog
ramming languages :
~'> ABC language, a teaching language created
as a replacement of BASIC, and
¢) Modula-3
Python is an easy-to-learn yet powerful
object orien~ed
programming language. It is a very high leve
l programrmng Do you know Python, the
language yet as powerful as many other mid
dle-level not so programming language, was
high-level languages like C, C++, Java etc. named after famous BBC
ln this chapter, we shall introduce you to play comedy show namely Monty
ful _world_ of
Piquant Python [Word 'Piquant' means pleasantly Python's Flying Circus.
StirnUlating
orexcitin tO th · d] So are we ready? And
g ... here we go.
e nun · ' . . . . ortant to know what all it takes to deve
~efore you begin your journey ~th . Py thon, it lop
is n;p any programing language, your device
Com puta tional Thinking' ? This 15 bec a~
l · us gti·ons computational thinking is required
so Utions for problems and to rea ch ~ t effective so1u .
Thinking' befo're starting with Python.
So, let us first talk about 'Computattonal -rn
COMPUTER SCIENCE WIT H PYTHON _ XI

96
COMPUTATIONAL THINKING tr rs can be used for sol ving a varieh,
5.2 ··· · dcni age cornpu ·.-1 b f 'J
·ts power and capab1lihes, mo . lex ones. however, e ore a problem
Because o f 1 • pie or comp d b
. blems from diverse .:ircas, whether ~101 . I . t ·t cou ld be sol ved nee to e understood
o f p1 0 . ) , s tnW1ICJ11 ·
an be tackled, the problem it-srlf and t lt wny. . , solu tion ~ 'iiffi-n6~,_ I
c . . . . f d ) solving or compu Ling a . MIL.U.41 !..'\L.!-4-

\!Vhen thmkmg 15 ocu~ _tn • . t ti mJI thinking. com putational Thinking refers t
for a specific problem, it is the Ct'lmpu ii c • . blcms the collect ive thought proce
0
tational thinking is an .:ipproad1 to solv1n? pro "nd involved in formulating probt:ses
ComPu . l sc,encl', o ms
. ,.,
usmg conceptS an 1 b , d 'd ~;1s from co111 pu er ·
be run
and solution s so that thl)\,
d ~, are
. . t1 , . . oblcms so tha l t1icy C011 represen te In a form th at can b
expressing solutions to 10~L pr effectively carried out e
~ a
on a compu te r. . . ss th at computer.
. . .0 bl m-solvmg pi oce
Computational TI1inkmg 15 a P~ . c ----
includes the following charactenshcs. problem, d a ta o r proce&s in to sm JJ
. ak ' down a comp 1ex a er
¢'> Decomposition. It IS tl1e bre mg ,
more m.anageable parts. . It efers to looking for similarities, patt, ,
·t· n/Data Representation. r t:rr.,
¢'> Pattern recogru 10
and trends in data. . . essary details/ information to focu s only on th '
¢ Abstraction. It is the filtenng out unnec e
important Information.. . . . tl1e common or shared characteristics. Somefunes
■ Generalisation. It 1s identifying .
Generalisation is considered as a part of abstraction. .
. , th d • g step-by-step instructions to solve this problem, or other5
¢ Algonthms. It IS e eve1opm
like it.
ti ·s devised it must be evaluated fo r ib:
Based on above characteristics, when a so1u on I '
effectiveness. Let us now talk about these characteristics one by one.

, De.::cnioos • O'"'
Decomposition is the process of breaking down a big or
complex problem into a set of smaller sub-processes to allow The process of breaking down a big
us to describe, understand, or execute the problem better. or complex problem into a set of
smaller sub-processes in order to
Decomposition involves :
understand a problem or situation
¢/ Dividing a task into a sequence of subtasks bette r, is know n as decomposition.
¢/ Identifying elements or parts of a complex system

Con.sider some examples of decomposition :


❖ Everyday example. Ma king cookies is a complex task that r r1 n be broken down in to sn1 allt'r;
simpler ta sks such as mixing u p the d ough, for min g ~nto shapes via cookie cutters, ,md
baking.
❖ Academic example. Wri tin g an essay is a comp lex task th nt c<-1 n be bro ken do wn into smaller
tasks such as develop in g a th es is, ga th eri ng evid ence, an d crea ti ng a b ibl iograph y p.ige.
❖ Engin eeri ng example. Designing a solution to construc t a brid ge by co nsid ering site
con ditions, technology avail able, techni cal ca p abili ty o f the co n tr actor, fo und a tion, et-:.
❖ Computer Science example. Writing a comp u ter p rogram/ softw are by de terminin g a
well-d efi n ed series of smaller steps (mostly in th e form o f m od ules and fun ctio ns) to so lve
the problem or achieve a desired outcome .
. coM PUTATIONAL THINKING AN D
1er 5 .
~~aP GETTING STARTED
WITH PYTHON
rn Recognitio n 97
p0tte
1- '11- e goalof patt e1n reco gnit ion is t f·
,0
°
d differences amo ng objects. w·t1 mdc om .
mon similarities
ffitin1tW hr&GmW•i:L -
ane
vv
can solve seem ingl y dive rse pr1ob1lproper
patterns identified
Pattern recognition refers t o
.. . ems b . . observing or looking for similarities
pattern reco grut ion invo lves : Ya smgle algo rithm .
,

I
or patterns among and within small,
¢) iden tify ing sim ilar ities or com ma decomposed problems; the
d .. identified patterns help solve more
us to sho rtcu ts. n ifferences that lead comp lex problems more efficiently .
¢) usin g iden tifie d sho rtcu ts,
the patt erns are iden tifi d tlmap ping problem charact . f1
once e , 1ey can be re r en s cs to poss1'ble solu tion
.
.
e exa mples of patt ern recognition.
5001 P esented through appropriate data . Conside
r
❖ Everyday exa mpl e. Wh ile driv ing
on r d . .
So the driv ers look for patt ern s in tra~~
s, swit~hmg lane s prom ptly may cause acci
. dents.
... Aca dem1c exa mp 1e. p atte rn reco gni't c to decide whe ther and when to swi tch lane s .
• · eous i·o · .
1gn , met amo rphi ·c , O r se d'ime ntar y. n 1s reqm red w h en ca tego nzm · · g roe k
s as e1t· her
:. Scie nce /Re sear ch exa mp le Scie nf
• . t d .
theories an d mo d e ls, e.g., · is s an eng mee rs look for patt erns in data to deri ,·e
■ Scientists disc ove red that the p t
. e als of fl owers, flower pisti· ·ls (see
ds arrangements m · the
centre of flower), pmecones etc. grow in
the order of Fibonacci series. Fibonacci serie
series in whi ch ev~ry next number is sum s is a
of previous two numbers, e.g., with first
numbers 0, 1, the Fibonacci series is : O 1 2
1 2 3 5 8 13 21 34 55 ...
■ In 1844, Nitr ous Oxide gas used by
dentists was considered a party drug, sinc
people 'hap py' and relaxed. A friend of Am e it mad e
erican dentist Horace Wells, took too much
the laug hing gas dur ing a stage show, hop of
ing to entertain the crowd. Dur ing the act,
acci dentally cut his leg, but to his surprise, he
he didn't feel a thing! Horace Wel l noticed
pattern of nitrous-oxide-and-feeling-of-no-p the
ain. Excited by this discovery, Ho race Wel
pate nted the use of Nitrous Oxide as the ls
most primitive anaesthetic.
3. Abstraction
Abstraction or Dat a abst ract ion refe
rs to focussing on Abstraction or Data abstraction
information rele van t to a con text /pro blem
and sup pres sing refers to focussing on informat ion \
other details. Abs trac tion invo lves : relevant to a context/ prob lem and \
¢) Rec ognisin g the con text suppressing othe r details. _
¢) Iden tify ing the info rma tion rele
van t to the context
For example, a dog ' s deta iled info rma tion
may include its colour, bree d, size , height,
shape of its tail, skip patt erns , dise ases, weight,
if any and so on
Ad raw mg · t h doe s not nee d details like bree
eac er d, weight, diseases etc. He just nee ds to
focu ·
s on col our , size, tai'l shap e skin patt .
erns etc. as h1s . • d f hi
- , context is draw ing an or s
· h
ab stra ctio n, t e d e t a1·is like bree d, wei ght diseases etc. are unnecessary.
,
.
A vete rina ry doc tor wi·11 h O wev er focus on details like breed, weight, diseases etc. as these
. .
are imp orta nt d etai·1s fo r his context and other details are unnecessary for h.im.

Consider som e exa mpl es of dec omp osit


ion: . .
• ,
•·• Everyd ay exa mp le. When we tell a story or describe a mov ie to our friends, why don t we
. d ·1 f .
le etai 0 the stor y or movie .
7
desc ribe eve ry sing
(v\' rUTE R )l If N( f WITII l'\Ttl O N XI

98
re port . ,, t.' :-um nhlrt Lt' ,Hhi d b , u ,.., nnl\ lhl'
❖ Acad em ic exam pl e. \\"he n we writ e .1 b1J,.1~
tr,h .·th'Hl.
them e or key aspe cts of the boo~ tt is ~t, -. 1 1 1ur ,, pl,1
engi nL'l' rtll~ "l1 lul m in ' prop n ... ,
11 11
ing exa m p le. \\'he n ,n.. O\ i'n it'\'' ,,n
•:• Engi neer
tlw d,•t.1it ... .
,,·e high ligh t the unde rlyin g appr o.-ic h .rnd h1d1.•
rJm t''nh -.h1.m ~ tlw nu mb1.·r, ,lll d )f'l' 1,1t11r
1 .,
❖ Com pute r S cien ce e xam pl e. A l°\lkulat\1r prng
l:-: l'I .,lglH 1thm pn,g r.im h.h•rn1..•lll h
11 1
func tion butt ons to u~er with out ginn g dl't,1i

!. Gen e ra zc•ro n
or shar ed d 1.:ir.K tl' ris tic~ bl'IWL'l'n two dom J
1nc, 0
Gen erali satio n refer s to iden tifyi ng com nwn r
cou ld be ,1dap t ed or app lit-J lo thl' oth er.
prob lems such that mod els or -~ol~ tion~ L1t one
Con side r follo ,\ing e\.am ples .

❖ Mam mals are ·war m bloo ded, give


Ii n :- birth , h a \'e ha ir, Generalisation refers to 1dent -
efor e, it is
and so on . An elep hant 1s a mam mal. Ther ifying comm on or sha red ch arac-
\,·ar m bloo ded, gin? Ji,·e birth, have hai r. terist ics betw een two dom a1ns
a n d the solu tion or problems su ch that models or
·.• Soli ds diss oh·e faste r ii thev are sma ller
sol ut ions of one could be
is w arm er. A spec ific solid is not diss ol ving
fas t so e ith er
. adap t ed or app lied to the oth er.
its is big in size or the solu tion is not wa rmer

Algo rimm :Jes gn


?
prob lem and how can the step s best be organized
It refer s to \'\-hat step s are need ed to soh· e the
strat egy for solv ing a prob lem and Algori thm
In o ther \·rnr ds, algo rithm s are a step-by-step
design is the de,·e lopm ent of algo ri thms .
and
es a prob lem by wor king on som e inpu t data
An algo rithm is a sequ ence of step s that solv ion
tion ). Algo rithm ic thin king invo lves both creat
prod ucin g a desi red outc ome (effe ctive solu
wing exam ples :
and exec utio n of an algo rithm . Con side r follo
ting an
•! Every da y Exam pl e : ¼' hen a cook
w rites a recip e for a dish , h e or sh e is crea
te the dish .
algo rithm that othe rs can fo llow to repl ica
❖ Aca dem ic Exam pl e : In math
, th e mne mon ic devi ce
orde r of An algorithm is a seque nce of I
PEM DAS help s stud ents rem emb er the
steps that solves a problem by
math ema tical oper atio ns.
work ing on so me in put data and
❖ Eng inee ring exam ple : Whi le cons
truc tin g a buil ding ,
produ cing a desired outcome
is calc ulate d firs t cons i deri ng the heig ht
foun dati on size (effec tive solut ion). Algor ithrr
soi] stren gth. Sim ilarl y, fo und atio n is
of the buil ding and des ign involves both creation ,
laid first and then the store ys abov e it. and execu tion of an algori thm. I

Fou Pnnc:1ples of Com putat , onal Think ing

Deco mpos ition Abst ractio n

What is th e big problem you What information is


3re trying to solve ? Ca n you re levan t to the problem
break ,t down into s malle r, and soluti on? What
more mana geab le parts ? - - can be set aside?
Pattern Recognition Algo rithm s

What simila rities do you What step- by-step solution nr ,


set of ru les can you d1::s1gn
1

see within the bigge r


problem and its parts ? to solve the problem?

Figure 5.1 Four principles of Computational Th inkin g


h ter 5 : COMPUTATIONAL THIN KI NG AND
Cop GETTING STARTED WITH PYTHON 99
Evaluation
nus is the essential part of eve ·
111 ·king Evaluati · ry ty pe of constru cti ve thinkin g including Computabonal
pattern recogrn ion, a strnchon/g - to sec
m · ·t· on abims to_check . .whether a solution reached via decomposition,
ff ·
11
Eva luation ·
· mvo .
1ves th e consideration of :sntton, algori th m design is good and e ective.
enern
¢) Algorithm correch1ess
¢) Requirem ents (meeting co 11 t· d .
s ram ts, es1gn principles, l' tc. )
¢) Performance (usabi lity efficiency speed I ·t 1· b'l't t )
, , , comp ex1 y, re 1a 1 1 y, c c.
Examples:

¢) When we cook, we taste our dishes and then adjust fl avou ri ng accordingl y.
¢) When we carry out a physics experiment, say, to find the relationship between
temperature and pressure, we check our data, investigate why it does not match the
theory, redo our experimental setup, and recollect data points.

S.3 PYTHON - PLUSES


Pluses of Python
TI1ough Py thon language came into being in early ❖ Easy to Use 00 Language
1990' s, yet it is competing with e~er-popular
❖ Expressi ve Lan guage
languages such as C, C++, Java etc. in popularity ❖ Interpreted Langua ge
index. Although, it is not perfect for every type of
❖ Its Completeness
application, yet it has many strengths that make it a
❖ Cross-platform Lan guage
o-ood choice for many situations. Let's see what are
0
❖ Free and Open Source
these pluses of Python.
❖ Variety of Usage / Applications

1. Easy to Use
Python is compact and very easy to use object oriented language with_very simple syntax rules.
It is a very high level language and thus very-very programmer-friendly.

2 Expressive Langua ge
Python's expressiveness means it is more capable to ex_pressing the ~ode' s purpose than many
other languages. Reason being - fewer lines of code, simpler syntax.
For example, consider following two sets of codes :
; ; Inc++ : Swap Values ·# In Python : Swap values
int a = 2, b = 3, tmp ; a, b = 2, 3
tmp =a; a, b = b , a
a= b;
b = tmp;

. . . to un d ers ta nd 7. Need I say more. ? :). This


t and easier d simplest
. is the
which one is compac of Python's expressiveness m the ue course.
examp 1e, you '11 find many more such examp1es

3. Interpreted Lang uag e 'led language. This means that the Python
. d lan age, not a compi .
gu
Python is an mterprete nd executes h de line by line at a time. It makes Python an
. . . t e co
installation mterprets a ·t ble for beginners to advanced u sers.
easy-to-debug language and thus sm a
COMPUTER SCIENCE WITH PYTH ON YI
100

4 · Its Completeness
.
V\fhen you install Python, you get cvcr
ylhm g you need to d o rea I wor k. .You do not need t
L
:tm"ri1l~ad and install addi ti onn l librorics ; nil . l' . .
type s of required fun chd~na ityfuis a:a11able
°

through vano us mod ules l)f Pyth on stnn do
rd hbrary 1. For exam pie for 1verse nctionality

sud1 as emails, web -pnges, dnt::lbnscs, GU I dcvc . , . d


lopm cnl, network conn ections an man y mor
eYerythi ng is availuble in Python stand ard e,
library. Thu s, it is also called - Python follo
''Batteries Inclu ded " phil osophy. ws

5 . Cro ss-p latfo rm Lan gua ge


Python can run equally well on va riety of
platform s - Wind ows, Linu x/U NIX, Mac
supe rcom pute rs, smar t pho nes etc.? Isn' t intosh,
that ama zing ? And tha t mak es Python
cross-platform lang uage . Or in other wor ds, a true
Pyth on is a portable language.
6 . Free and Ope n Source
Python lang uage is freely available i.e., with out
any cost (from www . pyth on.o rg)_. And not only
it free , its sour ce-code (i.e., complete prog is
ram inst ruct ions ) is also available, i.e.,
open-source also. Do you know, you can mod it is
ify, imp rove/ext end an ope n-so u rce softw
are!
7 . Variety of Usa ge/App licat ions
Pyth on has evolved into a powerful, complet
e and usef ul lang uage ove r thes e years. Thes
Pyth on is bein g used in man y diverse field e days
s/applications, som e of whi ch are :
¢) Scripting ¢) Rap id Prot otyp ing
¢) Web App lications ¢) GUI Prog ram s
¢) Game developm ent ¢) Data base App licat ions
¢) System Adm inist ratio ns

5.4 PYT~O~ - SOM E MINU SES (SO HUMAN


LIKE)
Al thou gh Python is very pow erfu l yet Minu ses of Pyth on
simple
lang uage with so man y advantages, it is ❖ Not the Fast est Lan gu age
not the
Perfect Programming language. There are some ❖
areas Less er Libr a ri es than C. Java. Ped
where Pyth on does not offer muc h or is
not that ❖ Not Stro ng on Typ e-bi ndin g
capa ble. Let's see wha t these are:
❖ Not Ea si ly Con \'erti hl e
1 . Not the Fastest Lang uag e
Python is an inte rpre ted lang uage not a fully
compiled one. Pyth on is fi rst semi-co mpi led
an inte rnal byte -code, whi ch is then exerted into
by a Pyth on inte rpre ter. Fully com piled lang
are faster than their inte rpreted counterparts. ua ges
So, here Python is little wea ker thou gh it offe
fas ter deve lopm ent times but executio n-tim rs
es are not that fas t com pared to som e com
languages. p iled

2 . Lesser Li braries than C , Java , Perl


Pyth on offers libra ry supp ort for almost all
com puti ng programs, but its library is still
compete nt with lang uage s like C, Java, Per\ not
as they have larger collections ava ilab le. Som
in some cases, these languages offer better etim es
and multiple solutions than Python.
1 If you install Python through Anaconda Pytho
n Distribution it loads most libraries and packages
Python even has versions that run on different langu with Python.
ages such as Java (Jython) , .NET (IronPython) etc.
Chapter 5 : COMPUTATIO NAL THI NKING AND G
ETTiNG STARTED WITH PYTHO N
10 1
3. Not Strong on Type-binding
Pytho n interp reter is n ot very t
· . . s rong on catching 'T ~ •
declar e a vanab le as mtege r but \ t , , ,. .
. ype-m,smatch 1c,sues. For exam ple, 1£
. . . a er sto, e stn n rt I you
pm-p omt 1t. J
.. . .
t> va ue in ·1t, Python won't comp
lain or
4. Not Easily Convertible
Becau se of its lack of synta x Pytho n .
flip-si de too: it becom es a d . d l S an easy lan guage lo progra m in . But this ad
van tage has a
rogra mmin g langu age Tl . i~a bvant age when it comes to transl
P 11 s is eca use atin g a progr am into anoth er
. · most ot}-. • I
,er an guages h ave stru ctured defin f:'d syntax.
Smee most other progr ammi ng Ian h
. guages ave strong-syntax, the translation from Pvtho n to
ano th er langua ge woul d reqm re the u t
. ser o care full . ,
and then imple m ent the same struct ure into otl y exam me the Pytho n code and ils struct u re
·
,er progr ammm g 1anguage ,s syntax.
So, now you are famil iar with what 11 p th ff
.
users are grow mg by leaps and bound s. Y on o ers. As a free and open-source langu age, its
a

As per Febru ary 2013 popul arity index, Pytho n was 4th
most popu lar progr ammi ng langu age 3 after - Java, PHP
and C#. That is the reaso n, it's part of your syllabus. Python is an interpreteo ,a, g~c: g'::
Toget her w e'll make it playf ul Pytho n ;). th at is, all the comma'1d5 -you \ • ' : e
are interpr eted and e-<ecutec o,e
by one.
5.5 WORKIN G IN PYTHON
Before you start work ing in Pytho n, you need to install Pytho
n on your comp uters. There are
multi ple Pytho n distri butio ns availa ble today .
~) Defau lt instal lation availa ble from www .pytho n.org is
called CPython installation and
come s w ith Python interpreter, Python IDLE (Python GUI) and
Pip (package i11stal/~r).
¢) There are many other Pytho n distri bution s availa
ble these days. Anaconda Python
distribution is one such highl y recom mend ed distri bution
that come s prelo aded ,,ith
many packa ges and librar ies (e.g ., NumP y, SciPy, Panda librar
ies etc.).
~ Many popu lar IDEs are also availa ble e.g.,
Spyde r IDE, PyCh arm IDE etc. Of th6L\
Spyd er IDE is alread y availa ble as a part of Anaco nda Pytho
n distrib u tion.
To install any of these distri butio ns, PLEASE REFER TO APPE
NDIX A. We shall karn tu work
with both these d istrib ution types [but my perso nal favou rite
is A11nrn11rla ;) - not tlw rt>ptil t:> , th e
Pytho n d istrib u tion :))
Once you have Pytho n installed on your comp uters, you are
ready to work on it. You c,m "''ork
in Pytho n in follow ing different w ays :
(i) in Interactive mod e (also called J111111 ediatc Mode) (ii) in Script mode

5.5.1 Working in Default (Python Distribution


The defau lt distributio n, CPyth on, come s with Python interp
reter, Python lDLE (GUI based )
and pip (pack age installer). To work in interactive as well
as script mode, you need to open
Pytho n IDLE.

j, Source : https:/ /sites.google.com/site/ pydatalog/pypl/PyPL-PopularitY-o


f-Programming-Language.
102 COMPUTER SCIENCE WITH PYTHON - XI

5.5.1 A Worki ng in Interactive Mode (Python IDLE)


Intera cti ve mode of working means you type the com mond - one commo nd at a time,
and the
Python execu tes the given comm and there and then and gi ves you output. In interacti
ve mod e,
you type the comman d in front of Python command prompt >» . r or example, if you type
2 + 5 in
fron t of Python prompt, it will give you result ns 7 :
nm1111,111d rx11r, •\,iv11 p,i1v1 irl'f£'
Result murnru >>> 2 + 5 ◄
bvPnlwn ---- . 7
To v-.rork in interact ive mode, follow the process given below :
(1) Click Start button ➔ All Programs ➔ Python 3.6.x ➔ IDLE (Python GUI) fsee Fig.
5. l (a)I
Or
Click Start button ➔ all Programs ➔ Python 3.6.x ➔ Python (comman d line)

Python 3.6
,. IDLE(Python 3.6 32-bit)
I' Python 3,6 (32-bit)
'ft Python 3.6 Manuals (32-bit)
,. Python 3.6 Modul~ Doa (32- Click here to open IDLE,
Python's own interactive
◄ Back
environme nt.

I - fJ I ' LJ.

Figure 5.1 (a) Starting Python Shell.

(ii) It will open Python Shell [see l] J Pytho n 3.6.5 She ll


Fig. 5.l (b)] where you'll see .Eile f_dit Shell Qebug Qptions ~ in dow .t!elp
the Python prompt (three '>' Python 3.6.5 (v3.6.S:f59 c0932b4, Mar 28 2018, 16:07:46) [MSC v. 190(.1
32 bit (I ntel)] on wi n3 2
signs i.e. , »> ).
Type "copyright", "credits" or "lice nse () " for more information .

(iii ) Type comman ds m fron t of >»I -=----1 Python command prompt


(See >» )
this Python prom pt and In interactive mode, you can
Python will immedi ately give type commands in front of ii
you the result. [see Fig. 5.l(c)]
Figure 5.1 (b) Python's interactive inte rpreter - Python She ll.

.A Python 3.6 ~ Shell


The interactive interpreter U• f.ti' Shtll 11..tbug Qp1ion1 W.1ndaw 1:i•l11
of Python is al so ca lled I Python 3.6 .S lv3 .6.5:f59c 0932 b4, Mar 28 20 18, 16·0 7.46 ) (M~C v 1900 32 bit {I ntel) ! M w.nJ~
Pyth on Shell . It e "~o;v'1 ght", "credl}ts" 01 "llcense ()" for mo1e lnfo,mo1th>n.
2

This way of giving =5 13


>, , See, various comm ands
>> s
name or expression in typed on prompt >>> and
13
fro nt of »> is called ,» .. 20 Python immediatel y
5
displaying. 33 returned the output.
1 >> >
IL _
_ __
- - --
l n lO ( c 4
-
Figure 5.1 (c) Interactive com man ds and thei r out put in Python Shel l.
ter 5 : COMPUTATIONAL TH INK
ING AN D G
(haP
ETTI NG STARTE D WITH PYTH ON
103
for exa mp le, to pri nt stri ng "He\\
Pyt hon pro mp t ( >>> ) 0
,,
on th e screen, you nee d to type the f
foll ow ing in fro nt 0
>» pri nt ("H ello ") .J
And Pyt hon inte rpreter will imm edi
d T d· atel ct· .
the con:rnan .' 0 15~ 1ay, you Y isp1ay slnn g Hello below
exp res sio n [Fig. 5.l( c)l m fron t of jus t nee d to me ntion nam e or lntera c.tt<Je mod e proves
the pro mpt. very usdu l for testing cooe ,
Figure 5.l( c) sho ws you som e sam you type the com mari ds
ple com ma nds tha t we typ ed in
Pyt hon she ll and th e out put retu one by one and g'?~ the
rne d by Pyt hon inte rpr eter .
re:.ul t or erro r one by one .
S.5.l B Working in Script Mode (Py
thon IDLE)
What if _Y 0 u wa nt to sav e all the
com ma nds in the form of pro gra
out put lme s tog eth er rath er tha n m file and wa nt to see all
san dw ich ed bet we en successive com
mode, you ca1mot do so, for : ma nds ? Wit h in teracti ve

¢) Inte rac tive mo de doe s not sav


e the com ma nds ent ere d by you in the
form of a p rog ram -•
~>The out put is san dw ich ed bet we en the command line
s [see Fig. 5.l (c)] .
The solu tion to abo ve pro ble ms is the
Script mode. To wo rk in a script mo
the follow ing : de, you nee d to d e

Step l : Create Mo dul e / Scri pt / Progra


m File
Firstly, you hav e to cre ate and sav
e a mo dul e / Script / Pro gra m file.
ins tructions : To do so, follow the se

(i) Click Start button ➔ All Progra


ms ➔ Python 3.6.x ➔ IDLE. (Fig. 5.2(
a)]
(ii) Click File ➔ Ne w in IDLE Pyt
hon Shell. [Fig. 5.2(a)]
(iii) In the Ne w win dow tha t opens,
typ e the com ma nds you wa nt to
pro gra m (or script). [Fig. 5.2(b)] sav e in th e form oi .:i
For ins tance, for the sim ple Hello
Wo rld program, you 'll nee d to typ
e foll ow ing line :
pri nt (" He llo World ! ")
"7i, P,1kinM
Fi,t Edit ShED Debug Options Wind
oM HEip
You can disp lay as w ~II as prin
t
valu es in interact ive mode, but
for
Op6l . Ctrt~ script mode, print( ) com man
d is
RKmt File. preferably used to pri nt resu lts.
Open Module... Ait+M
Class Brow~er Alt• (
Path Ero..,.<:.Ef
,.t, *Untitled" To see
Save fil, Wc-r'K ng in f)1f10,1 IDLE
Ctrl~S f dit FQrmet Bun Qp1jons Window tletp
Sm As... Ctrl• Shift· S in action
Sa.e Copy As... Alt· Shift• S
print{ i
Pnnt WindOYt Ctrl~P
Clo~e Alt+F4
fot ( trl+Q
Ln: 2 Col: 21 Scan
QR Code
(a) File ➔ New command in Pyth on (b) Type commands in new blank file (scri
Shell pt mode)
Figure 5.2

Pyth on GUI Shell IDLE lets you save th e en tire session (commands followed by their results
. • - as it appears on screen) but that
is not the Python program /scn.pt cont · · only the instructions .
amin g
co•1iP UTE~ sc•ENCE \".i'iH P! T!--' C', - ,\
104
(iv) Click File ➔ Sa v e and then save the file with an e,tension .py. The Python program.-:; has
.py ex tension [Fig. 5.2(r)J. For instan ce, we g,n L~ th 0 name to our program as Hell o.py.
-----==------
- ~ •l)ntitw,d""
--------- ---- j -... s- ol..J
ill!] Edit ~ Run Opt,cru Wut~ Help C I... . .,
N- Wiruf1""' Ctrt•N 0
Ope, .•. Ctrt•O
Rl'Cent Fill!S
Olh
Opim Module._ A!t• M
Class Browser Alt• C •ec~Pltct1 tfttlrucl•
Path BrawsEr l S l',1hen '1 ,,'011 1,11

Savo tho Python


Sa'nAs... progro m/scnpt file
San Capy As._ ToolJ with .PY extons10n
• Munc

Ctrl•P .._ Ptctu m


Print V, indow
B ~id~•
Close Aft•F4
wt

ff you forget to give .py


• Hld•Fold=
extension, Python won't be
able to run your script

Figure 5.2 (c) Save file wit h .py extension with File ➔ Save command (Scri pt mode).

Now your program would be saved on the disk and the saved file will ha ve .py extension.

Step 2 : ~un M odule I Script I Program File


After the program/scr ipt file is created, you can run it by follo wing the given instru ctions:
(i) Open the desired program/scr ipt file that you created in previous Step 1 by using
IDLE's File ➔ Open command.
If the program / script file is already open, you can directly move to next instruction.

(ii) Click Run Run Module command [Fig. 5.3(a)] in the open program / script file's ,•,indc,,,-.

You may also press FS key.


la Hello.py - C;/Use,vEdup/AppData/... §-==- 0 _

( iii) And it- will execute all the


commands stored in
File E"dit Fonnat (R'.wi) Opti-;;;;s - Window Help

Python Shell ' • I .,


.----- -------i1
Click at Run ➔ Ru n Modulil
command
~•b
A
to rtln the openec I
module / program I script
that you had opened and
r
tint( ., ~: l1 \'!,11 , Chee: Mo~ule
■ ffltf -, 1 • "t..T ~ ,
I

I
program scnpl.

show y ou the complete Ln- Z Col. l1 I

output in a sepa rate Python


Figure 5.3 (a) Run ➔ Run Module co mmand (Script mode)
Shell win dow. (Fig. 5.3(b) ]
~ Python 3.6 5 Shell
Elle £.dit She!I liebug Qpbom 'li)ndow .ti&lp
Python 3.6.S (v3. 6.S:f59c0932b4, Mar 28 2018, 16:07:46) {MSC v.1900 32 bit (Intel)! on win.32

> > j
/ Type "copyright", "credits" or "licen se() " for more Information .

= RESTART: C:\Users\Edu \AppData\L


This is the output produced _ 32 H8 11
by the Python when you · \ o.py
.,

I>,:, I
Hello Word ! applied Run Module
command.
(You can see complete

I module in previous figure)


Ln· 6 Col
.I
41

figure 5.3 (b) Output of a module-run is shown in the shell window.


Chapter 5 : COMPUTATIONAL TH INKING AND GETTIN G STARTED WI TH PYT HO N
105
As you can see that with sciipt d . f f a
. n-io e, you ca n store all comm and s togethe r m th e o rm 0
rnodul: / _program / scnpt and can get all output lines toge lhc r. (N o more command-output
sandwich.mg :).

s.S .2 Working in Anaconda Distribution


Anacon~a dis~bution con:1es with man y preloaded packages and libraries. You can w o rk in it
in both mteractive and scnpt modes. An aconda di stribution provides the followin g tools that
you can use to work i.n. Py thon.

¢) Jupyter notebook. It is a web based, interactive computing environment.


¢) Spyder. It is a powerful Py thon IDE with many u seful editing, in teracti ve testing and
debugging fea tures.
Let us learn to work with both.

S.5.2A W o rkin g in Jupyter Notebook _


In order to work i.n jupyter notebook, you need to first launch it using Anaconda Navigator- as it
has come preloaded with Anaconda distribution.

J. Launch Anaconda Navigator


. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . - ........... . ... . .........

1 From the Navigator window, click on Launch below jupyter notebook tile.

,,,
A~NaW19 1tor

,_,, ,-,.NACONDA ~ 1\\ 1,_:;t,lC'P 0 x;il

~ Application s on bu , 1,ootl .. Cha nnels

• E.nvironmen~
0 0

fii Project< (b~u) JUpy t l'f

Jupyterlab notebook
1'll Learn\rg
.n e .. t e nslt.l e e n, lronm ent for ln::eracti-- e Y.. eb•bu ed lnte ract;, e camputlno
not e b oo ► endro nm ent. Edit and r u n
and r e producibt e co mput.ing bu ed on t he
J•J O:te r No t.ebcoi •nd :.rchl te c ture hu m.ln·r u d, bl e do c;; ,, hlle de , cri oln g t he
d.sta 1n1l SI L Click here to launch
jupyter notebook.

0 0

qtcons.:,Le
• l< 5.:1 1t r,rlt1 • fll\ r t ~ n 0 • ■ I.JP n e l'lt
P,.Qt GU , Chtt Sl..t P~ft.1 11\hn « fii] 1Jf 1U
fn.1Aonm e nt Po., , , tut P rhoJn \U! ,,tt\
p,,-ei,,c,r multilll"I« ~ lt,tl g ,1,1 ltn i mu
ed , Uh.ld • d llin o , 1,,[ ■• ·t • tU tl/\ ,J
h ,g "UQhc,ng , gr1pr,ic,I ~ Utlpi ar,d l'ne te
d•lluQQl!'l'iJ • rd lnt1a ,pt .'.t11;in t u tu U
Click hare to launch
spyder.
Fee1etc

D
...

Figure 5.4 Lau nchi ng applicatio ns from Anaconda Navigato r.

. . . . . . . .. . .. . . . . . .. . .....
lso be installed separately, without Anaconda also .
Please note that jupyter not ebook can a
COMP UTER SCIE N CE WITH PYTHON - XI
106
·
Since jupyter notebook 1s a w eb ba sed comp ul1·n g en v11· .o n m c nt , it w ill be laun ch ed in a
,,veb browser.
Your w eb browser wi ll n ow sh ow y o u notebook dashboard (see be low)
Ii Cl !!!I ~3:-ti

C CD loca 1-c,s:

Ju p y t er This is notebook _ o;;Ct,l


dashboard

Fies
Li:, -::·ac ~

P,'thon 3

J months ago
-ext f ,112
:, hours ago Fod er
6 months ago

Figure 5.5

4. On the notebook dashboa rd, click at dow n-arrow n ex t to New b u tton and select
Python 3 to create a n otebook for executing Python 3.x co d e. (see fi gu re above).

5. In a n ew tab, it wi ll open a n ew n o tebook where you can w ri te and n m you r cod e.

= ,nl ~

<(,

JUpyter ~
Name of new
notebook

Before wri ting python


code, make sure it Is
+ ij R,,- ■ C ~►
showing Code here

Code cell you can


type python code here

Figure 5.6
[hopte r 5 : CO MPUTATIO NAL
THINKING AND
GETTING STA RTED WITH PYTH
ON 107

Inte ractive Mo de

cti vc cod e celJ and click Run . (see


6. To run Py thon cod e m iJ1tera mode, ty pe cod e in
below)

U"titft d3
,
C <D loca lrost

Jupyt er Unt1tled3
, Ju py ter Un titled3 To run the code in
current code cell ,
click here
r •

It will show the output


below the code and
start a new cod e ce'I
prin t "he llo" hell o below it
Write code in the
code cell
In [ : .

7 new code cell

Figure 5.7

. .... . ... . . . ... . .... ....


. . .... .... ... . . . ... . . . ... . ....
... ... ... ... ... .. ... . .. .. . ....

Scr ipt M ode

7. To run a scr ipt : in a cod e cel l.


cod e of a Py tho n scr ipt - a gro up of Python commands -
(a) Write the ).
No w clic k on its nam e to give it a new nam e (see below
(b)
I_J = ,@l~ l'
U,,:,tl ec'.! X
X

Click here to give


C name to your
python script • C (!') lo-: a hc-si
Ju pyter
•lll"ruS '.E:O

.,,' ~ .
Rename Notebook

• na,.,e
Specify name to
Enler 3 ne t, nol~bool
Q M R•Jn ■ C ►► cc"t your python script
()

••• ~- ,,r t1 r I

I··,
pri " : ("ne_l:: ,:or ld" )
Py•~cr· )
pri rt( I a, progra~~1-g ir

A python script
having multiple
python commands

Figu re 5.8
COMPUTER SCIENCE WITH PYTHON - XI
108
(c) Click on SJ VC icon first lo saw ii.
(d) Click Run to run your script.

Hc.1111 ,c u tr JI

Jupyter scr,pt 1 py I'


• lrC ;

e;' f 1' + M Rn ~~►

l, l r r •t ,
l=.J
,>r t ( e Jo 1,orlcl'')
'( I m i.,1'cgrarr.Mi g in h the,
t,ello ,1orld
I am progr awmi ng i n Pyt hon

1'1 [ ; :
Figure 5.9

(e) You can check in the notebook dashboard, which is open in another tab ; it will
show you the name of your currently saved script.
c::, @I

_ f-ome X Untnlc X script.. X

C CD localhost
*
"It--<-;

Ju pyter _ogcut

. ;

D\ CE'CS 3 months ago

seconds ago To create a ne\-.


3 hours ago notebook, use com~ ar j
File ➔ New notebook.
!fl ' rt II': 1 ,i:;,nl 3 hours ago
Figure 5.:o

5.5.28 Working in Spyder IDE


Spyder is a powerful interactive development environment for the Python lcm guage with
advanced editing, interactive testing, debugging and introspection fea tu rC's. In fac t, Dat::iCamp
community recommend s Spyd er IDE as the most preferred choicl' ~ ou t of top 5 Python
development environments recommended by it. Spyder IDE comes prclo;-idcd with Anacond a
distribution. It is m y personal favourite for working on
P y thon.
To launch Spyder IDE :
(i) Launch Anaconda Navigator
(ii) Click on Spyder tile in Anaconda navigator (refer to
Fig. 5.4) [Al ternatively, you can directly click at
Start button ➔ Programs ➔ Anaconda (folder name) ➔ Spyder

As pe! URL : https://WWW-datacamp.com/community/tutorials/data-science-python-ide.


6
S . COMPUTATIONAL THINKING AN D Gfll
,~ p1er
I,,
0
· lf'..C: ',! /,Q T(O W t11 f•v"',;1 >► 4 109
r Interface
, yde
)P once the spydcr is loaded, vou wi11 !\{' , fO 11
owmr, int.-rf.u ,.
l Th' · t~tt-o.n c.crsate
, ~"~'; Ulf'Yr-.J.; ·•S ,n front
of In{ Jpr!lffla• 1 M often
th..M r,.., f>J. II t~ O\l't( l
Ml
•• •

••
,, ct
Python 3.6 .4 lt«•eccnd~, Ire -:e• •-••, , . ," --~-
18.2 1 : 59 ) [~SC v. 1908 32 Dlt 'lr•e • .
Type " copyri g,,t •, "c red1h" or 'L ·rs~ · • · , a,:,r•
info rca ti Of\ .

Editor pane I Python 6 . 2 .1 ·· An e nhanced !rter•~•i,e • 1~"'?"

To create scripts, In [ l ]· prid (


wor1< here hello

I n [ 2 ]: \ !Python Consok>

To work in interacilve fT'IOOe ':f':Je


command(s) here c."ld rt Wt !J"'e
the output below the com""".an(!
Permissions: RW
log '== ==-=.,,,.,,.- -=.....----''
w ...

Figu re 5.11

Interactive Mode
To work in interactive mode in Spyder IDE, type your cornmand(s) in the !Python console
pane of spyder window. It will give you the output of the command there itself. ~ i:p.m·
above where we typed command :
pr int( "Hello")
in the IPython console pane and it gave us the result below it.

We favour ANACONDA PYTHON DISTRIBUTION for these simple reasons :


(i) it is free and open source ;
(ii) it comes preloaded with many packages and libraries,
(iitl it offers }upyter notebook (preferred choice for bloggers) and spyder IDE like toolkits to
write and Pyt hon scripts and code interactively .
I pe rsonally use Anaconda Navigator and work with Spyder IOE mostly and also on
jupyter notebook sometimes.

Script Mode
To work in script mode in Spyder IDE, type your script' s commands in the editor pane.
¢) To start a new script file, click File ➔ New File .. .
¢) To save current script, use command File ➔ Save or File ➔ SaveAs.
¢) Python scripts have File extension as .py.
COMPUTER SCIENCE WITI I PYTI ION XI

110 ~
• S1, e fol t
« CS P),thon d (20181 ► Chap Ol
(Fii;'l
Ctrl• N Create new script fil e N,: fc,l<J,r
IJ Nev. fife...
tfo,,nfoad1
., • I 11 JI ► t '
Ctrl -,. Q Recent Placts ,. HW
• Open...
1c,at<h .. 01~ • Shon,
Open last closed Ctrl .. Sh ift+ T
O~en recent L,bra nes

J .,
l
• Documents
Sa.c (trl•~ Music
-t • - · • Save commands Make sure to select
Save as type by
S.,ve as... Ctrl +Sh ift+ S 1 • •
clicking this arrow, as:
S.,v e copy as... .--- : ~ Horneg ro up
Python flies
Revert ,_--._ __,,... : "' Com puter
• ♦♦ ..., Local D,sk (( :) .,
To see •~ Fil e na me: HW.p>I

Working in Spyder IDE Saveas t)p ~


in action
• Hode Folders

Figure 5.12

Scan ¢)Please make sure to select file type as Python Files.


QR Code
After you have typed your script (and saved it), you can run your script by:
¢) Clicking at Run icon (see below) on the toolbar
Or by dicking at Run ➔ Run command
Or by pressing shortcut key FS.

( • £;:,<titr '~ !.6


~ 1I
-
- I
f t fd~ ~urr~ Sc~• e rcJt<U !colJ t,... l::lelp

!.:&:lr•t:~~~ ~ ;:~•
::: ~ ., D Run you r script by • ' Q.

clicking here

Here ·, oJ can get help of a;1


obJe-ct b, pr,:,ss,nc Ctrl + I 1n

]..•
frort c,f 1t, <:ither e,ri th<- Ed •c.r
or t.re Console.
9

•• ti)(

•• C::. ec.r- 114


Type com mand s for •• 10;2i:s9i.[MSCv~i9e0-32-bi/ (i~~.iij'' ·- -·
...c-•
your script here and •• Ty pe " copy ri g ht • , "cre a i ts " o~ "lice,,u • fer
save it using •• infor .. at i on.
File ➔ Save or • •• ! Pyt hon 6. 2.1 ·· 4r • ~h anct-d I nt er , ct i v• Dyt o~ .
Flle ➔ Save As
commands
• ♦ [ l l: 1 (

•• ne l lo

Please make su re to click ~


• I n [ 2 ]· r- unfi h (

in !Python console before H•llo worlo


I • • proarau-i ng i n P yt ► o~ The out put of
you run your script. So as
to have cu rsor in IPyth on Ir f 3 ) · executed script
console.
E~•t.t -1,nt! au.,
ter 5 : COMPUTATIONAL TH IN KING AND
(hoP GETTING STARTED WITH PYTHON
111
Now that you are familia r w itl diff
1
discuss ion of Python . Althou • erent ways- of wo rk.mg m
. . .
Python, we can proceed with
. g 1
1 you can wo k our
Anaconda Distribution and Spyder IDE. r on any of the~~, my personal favouri•te 1·s
3 Writing and Comp iling Pvthon Pr
5. 5· ogram wllti Cc rr1rnor,d I 1ne 1n l n1J1
1
To create and run a Python pro .
. . gram on Linux platform , yo u n('Cd lo do ~hi e; :
(1) Wnte your progra m code in a text edi tor.
(ii) Save your progra m with .py extension.
(iii) Compile and run on the com mand prmv.pt b · · ·
Let us see how. y givin g appropriate comrna n d .
11

Typing Python program in a Text Editor


There is a variety of choices for text editors when it comes to Linux. There
are comma nd line
editors like nano, vim, emacs etc7. ; Or you can work with the GUI editors like
Sublime Text, atom,
brackets etc. This really is the ch oice of the user.
But here, we will be workin g w ith Sublime Text 3.
Let us see, how we can w rite a simple Hello World progra m in Sublime Text
and compile and
run it using the termin al. (Please note that Sublime Text editor must be installe
d on the machin e
before you can use it).

Coding in Text Editor (Sublime Text)


(i) O p en Sublim e Text. Press the super key (windo ws key) and search for
Sublim e Texl
You will find an option to open sublim e text. Click on the icon and it
will appear .
(ii) Create a New File. Either use comma nd File ➔ New or press Ctrl +N on
the keyboa rd.
(iii) A new u ntitled file w ill open. Write the hello world code :
print( ' Hello World")
- ..... :-----~
_ _......-~-:-----~-- ........
~ ~•~

.· -JDesktopJhello .'py.• - S~bllm.~1Te,xt-(~NREGISTE'RED)


File Edit Selection Find View Goto Tools Project Preferences Help

◄ ► hello.py •

printi· Hello World ·~

j
(iv) Save the file w ith proper ex tension.
For this, use com mand File ➔ Save or
press Ctrl + S fro m the keyboa rd .
In the Save dialog that appear s, w rite
the name of the file and give an
extensi on .py. We h ave nam ed the file
as hello.p y.

, Vim and emacs have their GUI version as well.


SCI E: NCE WITH PYT HON - XI
COMPUTER
112
- I nd Running the (ode u~rng the T0rrrnnol
<... 0111p1 ,ng a d promp t will appear.
1 A comni JJ1
(il Open Lhc tem1innl. r~"" Ctrl +Alt + T from llw keybo,Jrl .

(/.i} Gt1 the> foldL'r where \'~)U ~"' l' d tlw t1k . .
.
l ( th ' f,rompt J
n I pres" enter .
(iii) Type Lhl' fr,llowing l''omnu nu.i •
111 I rnn o l
I.

I • ' I'
(
.
1
J run our program hello.py :
That 1s Wl' should t\'J)l' h)lhnv m ~ comtr1iln c.1 1<l 1.:•omni
r •· •'"

eduplllar~FLASH: - /o.skto p
FiltEdit \'tew Scarl"h Terminal Help
:dupl lh r@FL ASH : ~S cd Desk~ ---
up\\\ar iFLAS H : -/ D~ s kto ~ python hello. Y ~

(ii: ') lt will compile and run your progra m . You ·11 . , . the ou tpu t of tht'. progra m in the
w 1 sec
termin al " -indow .

·-:-~ eduplll ar~FlAS H: ,-JDesk top ~t:,o


File Edit View Search Terminal Help
uplllar iFLASH : - $ cd Deskto p/
duplllar@FLASH : ~/Desk top $ python hello.p y
ello World ~ -
dup\llar@FLASH~ ktop $ I

5.6 UNDERSTA\ DIN G FIRST PROGRAM/SCRIPT


Let us create our first progra m - a simple "Hello World " progra
m. (We are using Spyder IDE
fo r this. You can use any of the above mentio ned option s.)

To create this,

J. Start Spyd er IDE or any other editor of your choice .

2. Start new file (File ➔ New File) and type the follow ing text
in the ed itor ,\'indo,,· :
W"'ly F1rc;t Program
print ( "i,ello World ! ")

3. Now save your scrip t w ith a desire d name.


r.. Make sure to select Save as type as Python Files.
■ Give .py extension to your python progra m fil e.

You can use the command ed. Alternatively, open files (press Windows key and
search for files .) Go to the correct folder.
Right click in the empty space and click "Open in Terminal".
9 There is no concept of extensions in Linux however, sublime text uses these
extensions to identify the fo rmat and highlights
the syntax accordi ngly. You can externally set the syntax format as well. But
we are not covering that.
te r 5 : COMPUTATIONAL THI NK ING
Ch aP AND GED ING
STARTED WITH PYTHON 113
3.6) _ _ _ __ _
_n __
~1J SP1-:__ (Pytho

~ Edit Search Source Run Dm u


file I -

[j NEWfile... Ct rl +N
i!j X
o pen... Ctrl +O
~
Open last closed Ctrl• Shift-,. T

Open recent ► )

t < I
Ctrl+S
... S3 e
(trl • Alt•S
S3 e ?II
I , Here ,oo can get
6 P• int ( 1
Ctr1 +Shift+ S ) '1elt> of any ob}ed
:.., Save as... - - - - r,,,,._,,,, . ._
Save copy as ... 8 '--" nrcibe- ""'u;l b~ ,,elp
-:..,
Revert Type code fo r ~cr =o
~ you r progra m ~ UllWl!!! l ~

here Pytho n 3.6 . 4 ! Anaco nda, Ir


(defa u lt , Jan 16 2018, 10 :
v.190 0 3 2 bit ( l rrt e l J )
Type • copyr i ght • , •c~ed it!
nlice n s~ • for mo-~ irlOf"Vlc

!Pyth on 6. 2.1 -- A~ e~~~ c

I nte r a cti v e Pyt-o -.

In [ 1):

Permissions: RW End-of-lin~ . CRU Encoding· UTF-8

] or by click ing Run ➔ Run com man d O !'


Now run y our scrip t by click ing Run icon [ ►
by p ress ing FS. (Firs tly, click in !Pyt hon cons ole wind ow)
. . ... .. . . .. . .. .. . . . .. .... . . ..... . . .
.. ... .. .. ..... ... . . . ..... . . . . . . . ... . .
'

ow pane (see belo w).


5. It will show y ou the outp ut in the cons ole wind

( & S::,yder (Pytho n 3-.6)


Qebug C2 nsoles f roj«ts I ools Y)ew .l::1e1p
f ie _Edit ~ arch Sou~ e Bun
+
i:; @ ► ~~ •r.<e: Ml c:C-:c-=~ ■ iil ~
~ -- »

~ ra, =- ~ x
&.l'Or -E:~V •ont' tf\'l.p y
C: 'f'-N.py - 0.
l

.\
..••••
Here you can get
I • • "

]
• l

vwble explore.- ' R e explcref ~


prir ( ) B X
lPython como!t
.!' 0.
D Coo90!e I/A. U
8 •• ••
•♦ In [1 ): runf ile (
··:1- --- -~ ~- ---~ll--- -)- --,
The outpu t of
executed script
I n [2] :

IP·;IN>n console K'?tory IOQ


1,lemor-• 74 %
• CRLf Encoding: UTF-8 .. .
Line: 8 Colu mn· 1 . --~--
End-of -lines_ _ - - - -
Perm ,ss,om · RW
TE R SCI EN CE WITH PYTHo ~~
co MPU
/
114

An al ysing Script and Ou tpu


t typed.
No w car efu lly look at the scn· l th nl you
p ~
Yo u typ ed two line s : ti M\, r 11•s t Pt nor ctn! "
;, lA )
pt•i nt ( hC l 1o ~•1or i,
" J

.
But Py th on gav e you JU 1' 1c's out pu l as :
SI one 11 •
He llo wo rld I
. b is a com m en t in Py tho
1 n . Th at is, it is
Th e rea son bei ng tha t any h.nl'"' Jy1 l be ins w ith a # s~m o
t.~ g . Py thon will comp lete ly ign o re all the lines starnn
for the p rog ram me r ,s 111
. f
·orm al!on onl y , g
wit h a 4.

Unders1onding print( )
. . t() fun ction 1°. Yo u can use
To print or display out pu t, Py th 3 pri nt( ) as
on .x Prov1des pnn
pn ntt <.ObJects to be pri nte
d> · · ·)
e.g. , wh en you wr ote
------ . "ff ,,[/o H'orld !'' i., the
Str111g
~ ~
prin t( ) object tu be printed
stat em ent 1
pri nt ( "H ell o Wo rld !")

it printed :
Hel lo World!

Similarly, to print other strings


you may give someHung like.
. .
. - - - - - - String obje
prin t( ) ct ·,\fr name i~ M,~ 1,
sta tem ent 2 pr int (' My name is Mi sha ') to be pri111ed.

it will print
t~y name is Misha

Carefully look at both the print(


) sta tem ent s giv en abo ve. Co
than tw o different string va lue uld yo u no tice an ything other
s? No ?
Carefully notice that the first
string is enclos ed in double
enclosed in sin gle quote s . quote s an d the secon d str mg is

...---
pri nt ( "H ell o World ! " )

pr int ( 'My name i s Mi s ha ')


..----
~o th these str ing s ~re valid in Py
thon. Y_ou can enc lose yo ur str
single quotes, bu t Jus t ens ure tha ing s in eit he r d ou ble qu otes or
t op ern ng an in
Yo u can no t hav e a str ing like d clo sin g qu ota tio n m ark sh ou ld
be of sam e type.

' Hey th ere " ..-- - Lrwr! O{'(' /Wlg and clo ,iu~ Ouutclliu
mart, do 1101 11wrth 11

10 In Python 2.x, print is a statement


, not a function.
L THINKI NG AN
r 5 : COM PUTA TI ONA D GETTING 5TARH Q
i;noPte WITH P(THON 115
foll owing are some valid pr.in t() statemen t"
. , io , ) ·
pri nt ( The Golden Rat
Prin t( "ha s same l ett e r s as'' )
pri nt( 'The God Rela tio n·)

Wi th tlu s we hav e come to tlw end o( .


th is chap ll•r I~'' I qu1rkly revise what we have lear nt
· lVi
so far.

PYTHON INT ERA CTIVE MO Dt


-- - - - - Progress InPy1 hon 5.1
,. 1-f - - - - - - - - - - - -
.:tart P1/fho11 (Anaconda Nnv ioa/' or nnd ti·,en Spyder ID E
_, -
L\
or any other ID£ of 1/0Ur cho1ce1

Please ch eck the pra ctic al ~ ., • -


( Scie nce with Pyth on and f ill ci~~
.
pon ~n t- b?o k - Prog res:; i,., C:r
ere in PrrP 5 . 1 und er ( r;op'e~ :
pra ctic ally do ing it on th e co mpu
ter .
ah~~

, /P- - - - - - - - - - - - - - - - -
WO RKI N G IN SCR IPT MO DE
Progress In Python :

IDE or any othe r IDE of your choice.


Start Anaconda Nav igator and then Spyder

~ •e
pon ent- boo k - Pro gress in ( 0 ,,-- 0
Pleas e che ck the pra ctic al com
( Scie nc e wi t h Pyth o n and fill it ther
e in PriP 5 .2 und er C ha p•er 5 a
pra ctic ally doin g it on the com p
ute r.
fter

LET US REVI SE
solurions
l Thin king refers w the collective thou ght processes invo lved in formulating problrms and
Computationa
be effectively carr ied out by a com purer.
so that they are represented in a form that can order co understand
process of brea king dow n a big or com plex prob lem into a srt of sma ller sub-processe s in
The
mpo sition.
a problem or situation better, is known as deco and within sma ll,
lool<ing for simi larities or paccems among
Pattern recognition refers to observing or iently.
help solve more complex prob lems more effic
decomposed problems; the identifi ed patterns lem and suppressing
ssing on in forma tion relevam to a comexU prob
Abstraction or Data abstract ion refers to focu
other details. such that
n refers to iden tifyin g com mon or shar ed characteristics between rwo domains or problems
Generalisatio
or applied to the othe r.
models or solutions of one could be adap ted ucing O desired
is a sequ ence of step s that solves a prob lem by working on some input data and prod
An algorithm algorithm .
n involves both creation and execution of an
outcome (effective solution). Algorithm desig
coMPUT ER SCIENCE WITH PYTHr
..J ► •

11 6 a~ 1991.
m 1 rbn
1 ' y •
\Ii RO\SIJ11f fr
•• P>thon "•as drvrloprd ,.,,, .dc;uuln ,..~n :, ,ros~•platform :> ee and open ~urcr:
• Pylhon offer~ follov.'mq a van1og< :> <omJtlt'l <'
:1 easy ro u~e ::, e\r~r{'.l,sl\ff' :., Nor strong on Type-b1ndin!J
• J V iJ v,•rl I!>•
•: Pvlhon oli.o has thr..t'' 1,m11011om, 11h1 :'111~ th,111 c ' a • if) Script mode.
, I • .;> f 1-S'>t'I ' r,,o(/f' (
:, Not the fo'>tr!-I an~utl~~ . (iJ /ltf" rncI IYt' ' \ c,o ndw,c hed berween com
In Pvrhon, onr cw1 wm /. ,n rwo dlfI• ,, nt wnyi. . I ,,rnr]rtlfll cmd rtlv, , oufpur , ma'1f1;
❖ · j ,n fmlll I> {1
,. .h .. m0dr do(•, ,1t1t ~ \'<' ' ·1111111uirn ~
-: lntt.: ram d fJeCcompiece ourpur
Jntrrnccit , mode ,~ !-UttiJMr fm 1r,1111q c(,cIr uri th<' proqram!I lat1 r an
,,(}gram\ and tfwn r
< St npt mvJr ,s US l ful for m-atmg I
• r vrhon rs on intc'rprrrrd lariguagr SI II
. 15
l5o called Python ,e .
P;thon 's ,ntcructive incerprf'tcr a

S"o lvt~ Problt,w\S 4


= iHUlt is computatio11al thinking? . k.
l1'ke a computer - in binary
. , (b) T/1111 mg
(a) Giving instructrons to a compute1 I oblems
h t
(c) Using a set of techniques and approac es o
help to so ve pr

SoluboP . (c)

2 Vvhy do we need to think computationally?


(b) To help us solve complex problem~ i~:l... . _ e:::i~:
(a) To help us to program
(c) To help us to think like a computer
Solution. (b)

3 Which of the following is NOT a computational thinking technique ?


(a) Decomposition (b) Pattern recognition (c) Coding
Solutior.. (c)
4. Which of the following is an example of thinking computationally ?
(a) Planning out your route when going to meet a friend
(b) When going to meet a friend, wandering around until yo11 fin d tliem
(c) When going to meet a friend, asking n paren t to plnn you r route _{t>r _11011
SoluLun. (a)
5. Which of the following is NOT an example of co111p11tatio11nl tl,i11ki11g ?
(a) Letting the bossiest friend decide where you slio11ld nil go
(b) Considering the different options cnrefully before rfecidi11g 11Jh111 f/, e licst one
(c) Discussing with your friends how much ti111c nnd 111oncy you l,nvc before clwosingfrom a s110rtli~t
places
Solution. (a)
r,_ What is a complex problem ?
(a) A problem that, at firs t, is not easy to solve (b) A problem that, at fi rst, is not ea5y to u11do·~f 111 ' l
(c) A problem that, at first, is not easy to solve or to understand
So1ubon. (c)
S . COMPUTATIONAL TH INKING AND GETT
Chapter . ING START ED WITH PYTHON 117
,An Odeveloped Python Prog ra111 111;11t'0 Ln 11gungc?
,,.yvr1 .
,. 0lution. Guido Van Rossum in 1990s d
5 . .
1
· eve oped rython prog r~1mmi11g language'.
ls python an Ob1ect Oriented langruisc ?
8
· Solution. Yes, Python is an Object Oricmtcd 1
nnguagc.
9. 'Python is an i11terp~eted l~igh level la11g11agc'. Whal dors it mean to you ?
S0 tution. 'Python 1s a high level Iangua , . . ·
h d · ge mea ns it 1s programmer-fri end ly ,.e., easy to program
and compre en .
,p thon is an interpreted language' me . I·t . .
Y . ans requires an interpreter (not com piler) to execute its
code Jine by lme - one statement at a time.
P_vtlion programming language got its name from which show.
10.
Solution . Py~·1an _prog:amming language was named after a British TV show namely ':vionty
Python's Flymg Circus .
What does a cross platform language mean ?
Jl.
Solution. ~ cross_ platform language means it can run well on variety of platforms like Windows,
LinuxfUrux, Macmtosh etc. etc.

l~- Python is a Free and Open Source language. What do you understand by this feature ?
Solution. It means - to download Python, one needs not pay anything, because it is Free. An d i~s
source-code is also available, which can be modified/improved etc., because it is open-source.
13. What is the difference between interactive mode and script mode in Python ?
Solution. In interactive mode, instructions are given in front of Python prompt (e.g., >» or In[ 1:
prompts) in Python Shell. Python carries out the given instruction and shows the result there itself.
In script mode, Python instructions are stored in a file generally with .py extension and are executed
together in one go as a unit. The saved instructions are known as Python script or Python prt1~...-,am.
14. What will be the output of following code :
#This is a sample program
#to output simple statements
#p rint ("Such as")
print ( "Take every chance.")
print(" Drop every fear.")
Pick the correct output from thefollowing choices and give reason. T/Jis is a sample prosr,1111 Ii> 1utp11t si111plc
1

statements
(a) such as (b) such as (r) suc/J as

Take every chance. Take every chance. Take every chance.


Drop every fear. Drop every fear. Drop every fea r .
Solution. The correct output is (c).
Reason being : the code lines beginning with a # si~ ar_e com~ent:,· l11ey a~.e ju~t for info~ation and
ignored by the Python interpreter. Hence, the thir~ Im_e #prmt ( Such as ) ~di also be ignored by
Python interpreter. Thus, the Python interpreter will give output of onl y prmt( ) statements.
15 'vV11ich of the followi ng are not valid strings in Python ?
(a) "Hello" (b) 'Hello' (c) "Hello' (d) 'Hello" (e) IHellol
Solution. Strings (c), (d) and (e) are not valid strings in Python.

You might also like