COMPUTER
SCIENCE i
ython |
Textbook for
Class XII
* Programming & Computational Thinking
* Computer Networks
* Data Management (SQL, Django)
* Society, Law and Ethics
SUMITA ARORA
AQ
2
- DHANPAT RAI & Co,www.worldvideweb.com
Preface
Quality of education depends a lot on the curriculum imparted. Since Computer Science is a rapidly
evolving field, CBSE constituted a committee to look Into existing Computer Science curriculum and
Fecommend a curriculum that is modern, relatively light, teaches timeless concepts like computational
thinking, is upto international standards and focuses on problem solving skills than [ust the syntax.
The new syllabus of Computer Science (083) Is the outcome of the recommendations by the curriculum
review committe. The objectives of this new syllabus are laudable — focus on clear understanding of
concepts, applications of concepts, problem solving skills, develop computational thinking etc.
This book has been written keeping all this in mind. This book adheres to the CBSE curriculum for
Computer Science (083) for Class XI, Based of the syllabus, the book has been divided into four units.
Unit 1: Programming and Computational Thinking (PCT-2)
Unit 1 has been divided into ten chapters (chapters 1-10). It covers Python programming through
revision tour, Python functions, Libraries, File handling in Python, Recursion in Python functions, Data
visualization using PyPlot, Data Structures in Python. This unit also covers basics of determining
algorithm efficiency.
Unit 2: Computer Networks (CN)
This unit has been divided into two chapters (chapters 11-12). It cavers computer networks’ basics such
as types of networks, cloud technology, loT, wired and wireless networks, client, server networks,
network devices, modulation techniques, collision in wireless networks, IPv4, IPvG, TCP, other protacals
and network tools.
Unit 3: Dato Management (DM-2)
This unit has been divided into four chapters (chapters 13-16). It covers SQL revision, more on SQL
commands, developing a minimal web application using Django web framework, and Python database
connectivity with MySQL databases.
Unit 4 : Society, Low and Ethics (SLE-2)
This unit has been covered in one chapter (chapter 17). It covers many topics and issues related to
society, law andl ethics, such as 1PR, plagiarism, digital rights and licencing, privacy laws and cyber crime,
I act, e-waste management, challenges online and gender and disability issues.
Apart from the text book, we have also provided a practical book ‘Progress In Python’ that contains
additional practice exercises, Although the text book contains sufficient number of practice questions
‘and exercises, yet the additional practice of exercises given in the practical book will make the
foundation of programming and other concepts even stranger.www.worldvideweb.com
Syllabus
Distribution of Marks
‘Unit No. Unit Name Marks
A Programming and Computational Thinking 2 0
2 Computer Networks 1S
3 Data Management—2 15
Society, Law and Ethics—2 10
5. Practicals 30
100
Total
Unit 1 : Programming ond Computational Thinking (PCT-2) (80 Theory + 70 Practical)
4 Revision of the basis of Python
4 Functions: scope, parameter passing, mutablefimmutable properties of data objects, pass arrays to
functions, return values, functions using libraries : mathematical, and string functions,
“+ File handling: open and close a file, read, write, and append toa file, standard input, output and error
streams, relative and absolute paths.
Using Python libraries: create and import Python libraries
4+ Recursion: simple algorithms with recursion: factorial, Fibonacci numbe
search,
4 Idea of efficiency: performance defined as inversely proportional to the wall clock time, count the
number of operations piece of codeis performing, and meastire the time taken by a program, Example:
problem, and understand! how the efficient one takes less time,
recursion on arrays: binary
take two different programs for the san
lot: Line chart, pie chart, and bar chart,
4 Data visualization using V
4 Datasstructures: lists, stacks, que
Unit 2: Computer Networks (CN) (30 Theory + 10 Practical)
+ Structure of a network : Types of networks: local area and wide area (web and intemet), nev
technologies such as cloud and lol, public vs private cloud, wired and wireless networks; concept ofa
client and server.
4 Network devices such asa NIC, switch, hub, route
4 Network stack: amplitude and frequency modulation, collision in wireless networks, error checking
and the notion of a MAC address, main idea of routing. IP addresses: (v4 and v6), routing table, rouler
DNB od wth UBls TCP : basic idea of retransmission, and rate modulation when there iS cont
y oad netw otocols: 2 iF " ve a hi
{analogy to 2 road network), Protocols: 2G, 3G, 4G, WHF. What makes a protocol have 2
; Basi netioek tools: traceroute, ping, ipconfig, nslookup, whois, speed-test. 4
Saou pe HTTP (basic idea), working of email, secure communication : encryplion ef
ates (HTTTS), network applications: remote desktop, remote login, HTTP, FTP, SCT 9°" «
POPAMAP, SMTP, VolP, NFC.
| vi es
and access point.www.worldvideweb.com
Unit 3: Data Management (DM-2) (20 Theory + 20 Practical)
> Write a minimal Django bo and writes the
ne BO based web: Mication that parses a GET and POST request, wt
elds to a file- at file and CSV file Et "
Interface
. Python with nm SQL database,
* SQk- commands: aggregation hunctions having, group by, order by.
Unit 4: Society, Law and Ethics (SLe-2)
a S (10 Theory)
atellectual property rights, pla i ,
ly &, Plagiarism, digital rights management, and licensing (Creative Commons,
Geta Ach pen wnt ode pa EM eng
+ Privacy laws, raud; cyber-crime, i ‘ i
rane oe & “ a Cybercrime, phishing, illegal downloads, child Pomography, scams; cyber
Technology and society:
2 =“ nology and society understanding of Societal issues and cultural changes induced by technology.
waste management : proper disposal of used electronic gadgets.
% Identity thett, unique ids, and biometrics,
* Gender and disability
ssues while teaching and using computers,
PRACTICAL
Unit No. Unit Name Marks
1 Lab Test (10 marks)
Exthon program (60% logie + 20% documentation + 20% code quality) 7
Small Python program that sends a SQL query to a databose and 3
displays the result. A stub program ean be provided
2 Report File + Viva (9 marks)
Revert file: Minimum 21 Python programs. Out of this at least 4 7
Programs should send SQL commands to a database and retrieve the
result; at least 1 program should implement the web server to write
user data to a CSY file,
View voce : (based on the report file) 9
3. Project + Viva (11 marks)
Project (that uses most of the concepts that have been learnt) 8
Project viva voee 3
Programming in Python
4% Recursively find the factorial of a natural number,
Read a file fine by line and print it.
4 Remove all the lines that contain the character ‘a’ in a file and write it to another file,
4 Writea Python function sin (x, n) to calculate the value of sin (x) using its Taylor series expansion up tot
terms. Compare the values of sin (x) for different values of 11 with the correct value,
+ Writea random number or that generates random numbers between 1 and 6 (simulates a dice),
+ Write a recursive code to find the sum of all elements of a list.
4 Write a recursive code to compute the 1 Fibonacci number,
4 Write a Python program to implement a stack and queue using a list data-structure,
4 Write a recursive Python program to test if a string is a palindrome or not.
viia
ta plot the function y = * using the pyplot or matplotiib libraries,
mi to
rite a Python Prone at secepls user inputs, performs some aperation on them,
ee graphical appbeation that semaple, write a small calculator. Use the tkinter lige 84 then
Create t Bit pul bn the screen. For © _
weiter ronan the urllib hbrary. = ome
2 Or error a Joanusing the numpy &F PY —
Compute EA 10 phishing emails and find the most common wor
$ Takea sample o
SQL ond Web-Server
Delo Managemen! on ‘and average of the marks in a student marks table
+ Find the min, m2) 2 try in the table (customer ID,
She tou? number of customers from each country Customer nam
ee Oe the (student ID, marks) table in descending order of the marks.
ee importing the MySQL module.
vith Python by i -
3 ga a est (POST), and write it to a CSV file,
er to parse a user reques ) :
4 Write a Django based web server
gia something that is tangible and useful. This should be done in
i oject is to create
Ba fataitedeke and should be started by students at least 6 months before the submission
groups of 2 to to solve. Students are
im here is to find a real world problem that is worthiwhil
Sesame joa Witenes Gadel ther about the problems that they are facing. Far example,
ila business is finding it hard toereate invoices for filing, GST elaims, then students can do.a projet ta;
takes the raw data (list of Iransactions), groups the transactions by category, accounts for the GST tay
rates and creates invoiees in the appropriate format, Students can be extremely creative here. They can
use a wide variely of Python libraries to create user friendly applications such as games, software for
and mobile applications. Of caurse to do some
their school, software for their disabled fellow shudent:
of this projects some additional leaming is required; this should be encouraged. Students should know
how to teach themselves
Ifthree people work on a project for 6 months, at least 500 lines af code is expected, The committee has
also been made aware about the degree of plagiarism in stich projects. Teachers should take a very strict
Jook at this situation, and take very strict disciplinary action against students who are cheating on lib
asignments, or projects, oF using pirated software to do the Everything that is proposed ean be
achieved using absolutely free, and legitimate open source 7
www.worldvideweb.comwww.worldvideweb.com
Contents
1 Python Revision ‘Tour
11 Introduction
12 Tokens in Python
121 Kevuveds 2
122 Mentifers (Names) 2
123 LiterateVatues 3
Operators &
125 Punctusors 4
13 Barebones of a Python Program
1A. Variablesand Assignments
LAL) Dynanie Tying 6
142 Mullple Assignrents ¢
15. Simple tnput and Output
1.6 Data Types
17 Mutableand immutabteTypes
1.8 Expressions:
18.1 Eeulusting Arithmetic Operations 13
18.2 Enchuating Relational Expressions
183 Eeulusteng
Logical Expressions 1p
184 Tape Casting (Lapltet Type Corsvrsion) 16
185 Mut Library Functions: 16
1.9 Statement Flo Controt
1.10 TheifConditionals
1.10.10 if Cortona Staterznt 19
1.10.2The ifetse Comitoral Stator 20
1.10.3 The ssf Conta! Statement 20
110ANested if Staterents
1.10 5Storing Condition
1.41 Looping Statements
LILA The for Loy 23
1AL2 The white Loop 2
1.12. Jump Statements break and continue
The break Statement 25
The continue Statement 26
1,13 MoreonLoops
LAB. Lavp elie Statement 27
1132 Nested Lops 28
a:
10
2
4
18
19
2
aEe
python Revision Tour-II
‘21 Introduction
= inython
” irings!
, 22 set mS
322 Traersing a string 3S
223 Siring Openers 38
224 Siring Stic 17
225 string Functions #2
23 Ustsin Python
231 Creating Lists 46
332 Liss Strings 47
233 Lis Operations 18
2a List Manipudation 50
335 Making True Copy ofa List 51
236 List Fanchon. 51
24 Tuplesinython
2A Creating
142 Taples os Lists 58
243 Tuple Operations 57
244 TopleFanetons and Medios 52
25 Dictionaricsin Python
251 Cheating « Dictionary 6
252 Acecsing Elenents of Dictonary 61
253 Charcterstic of « Dictionary
254 Ditinzry Ofer
255 Detimary Functions en Methals 65
26 Sorting Tochniques
261 fable Sort 20
262 Insertion Sort 71
pponted 38
res 55
3 |] Working with Functions
85-140 31. Introduction
32. Understanding Functions
321 Calligttswvrhing/Using a Function $7
322 Python Function Tyres. 85
33. Defining Functions in Python
peal Srsctureofs Paton Program 91
ow of Execution ina Function Call
ments ond Parameters. 9
rameters
551 Pestonat Renn
Resied Argunsen
352 Default Ary ‘ied
Peal Arcuments 99
253 Kesoord
34
35 Passing pa
55
Gy
0
85
86® Returning Values From Functions
IST Returning Multiple Valucs 105
37 Composition
3.8 Scope uf Variables
341 Name Rewlution (Reaing Scope of a Name) N12
3.9 Mutable/Immut:
able Properties Of Passed Data Objects
29 Mutahdtytmnn
Using Python Li
44 tntroduction
42 Whatisatitrary?
ily of Arguments Parameter and Funct
Calls 7
ny
braries
Ml - 172
ART Whats e Matute ? nap
43° Importing Modutes ina Python Peopram
ABT Urpvting Entire Moule 1
A432 bepwrting Select Objects from a Malle HP
43.3. Patton's Preessing of ingwit rule
44. Using Python Standard Lib
rman 17
y's Functions and Modules
Python’ Busitn Functions
442 Working sth Some Sta
45 Creatinga Python Libran
451 Stracture ofa P
in Library Matus 19%
age tet
452 Prvesure for Creating Packages Io
45.3 Using Importing Pt
Libraries eo
le Handling
, 173-200 $1 Introduction
52 DataFiles
53 Opening and Closing Files,
S31 Opening File 1
S42 Ching Hele 1
5A. Readingand Writing Fites
54.1 Reading from Fite
542 Writing onto Files 189
SA} The flash) Function 187
BA Removing Whitespace after Reading from File 1;
SAS Significance of File Pvanter #1 ile Handling 139
Standard Input, Output and E
6 Recursion
6:1 tetreduction
Bee 62 Recursive Function
63 Move Recursion Works
G4 Recursion in Python
fal) Sime Rearte Cals 215
642 Binary Sech 218
3 Rewer Bary Seach 222
65 Recursion tteration
| |
102
107
107
“41
142
M5
173
174
174
v7
190
201
202
205
212
2237 Idea of Algorithmic Efficiency
5 1 Introduction
ia 32 What is Computational Complexity?
73 Estimating Complexity of Algorithms
73:1 Big-O Notatiwn 234
7.32 Guidelines for Computing Complerity 236
7A_ Best, Average and Worst Case Complexity
8 | Data Visualization using Pyplot
251-295 8.1 Whatis Data VISUALIZATION?
82 Using Pyplot of Matplotlib Library
821 Installing and lryynting matplethty 2
8.22 Working with PyPlot Matiels: 253
83 Creating Charts with miatplothb Library's pyplot Interface
83.1 Line Chart 259
832 Rar Chart 265
833 The Pie Chart 225
84 Customizing the Plot
84.1 Anatomy ofa Chart 250
$42 Adtong a Tite 231
S43 Setting X and ¥ Labels, Limits and Ticks 281
BAA Adting Legends 285
$45 Soomg aFiguie 257
85 Comparing Chart Types
9 Data Structures ~ 1: Linear Lists
297-332 9.1 Introduction
9.2. Elementary Data Representation
93
Different Data Structures
D3 Lincar bs
93.2 Stacks 299
93.3 Queues 299
934 Linked Lists 209
935 Trees 300
4 Operations on Data Structures
95 LnearLists
9.6 Linear List Data Structure
Arrays. 299
96.1 Searching ina Linesr List 302
26.2 Insertion im a Linear Lis! 304
283 Deletion ofan Element fmt a Sorted Linesr List 30
9.64 Traversal of a Lincar List 310
9.65 Sorting a Linear List 311
9.6.6 List Compretiensions 314
97 Nested/Two Dimensional Listsin Python
9.2.1 Tuo Dimensional Lists 320
a+
233
234
234
239
281
252
259
200
288
297
297
298
300
300
300
31910 Data Structures ~ II: Stacks and Queues
333-368 10.1 Introduction
102 Stacks
102.1 Implementing Stack in Python 336
1022 Stack Apptications 339
103 Queues
103.1. Implementing Queues in Python
1032 Yntinsinae
2033 Queue Applications 353
11 Computer Networks —
369-386 LI Introduction
112. Computer Networks An Introduction
M21. Compnents ofa Computer Network 371
11.3 Types of Networks:
HAY Tapesef Netwrts Basel on Ges
phic Spread 372
M32 Typesof Netivets by Compynent Rates 374
BIAS. Type of Netuvris Reed on Communication Channel 375
114 Network Devices/Hardware
TL NIC (Netwvrt Interfase Card) 377
M42. WiFi Card 37
M43 Hub 37
mad
M45 indge 379
M46 Router 179
MAT Gatewey 379
hATS
MAS Acces Point 179
1S The Cloud
ILS. Types of Clowls 181
116 Internetof Things (1oT)
116.1 Enabling Technolgies for LOT
11.6.2 Devices that cam form Io 382
1163 Challenges and Risks 153
12 | Computer Networks - IT
387-430 12.1 Introduction
12.2 Modulation Techniques
1221 Major Types of Mxtulation 388
13 Collision in Wireless Networks
3.1 Hoa CSMAICA Works 391
12.4 Error Checking (Error Detection)
125 Main Idea of Routing
126 TCP/IP
126.1 Network Congestion and Retransmission in TCP 402
a aii BD
333
334
347
369
370
372
377
381
387
308
390
393
398
40113
431 - 456
127 Addresseson a Network
127.1 The Domain Name and DNS 408
128 Cellular/Wireless Connectivity Protocols
129 Basic Network Tools
1281 FING 408
1292 TRACEROUTE ifr Linu) or TRACERT (for Winds) 4.79
1295 NSLOOKUP 407
1294 INONFIG Comment 410
1295 WHOIS Commend 411
12960 Spend Tot at
12.10 Various Protocols Used on Networks
1211 How HTTP Works - A Basic Idea
1212 Working of Email
I2I3_ Secure Communication
ADB NTIS air
2 Secure Seles Layer (SSL) 417
1214 Network Applications
MySQL SQL Revision Tour
131 Introduction
132, Relational Data Model
133° MySQL-A popular Relational DataBase Management Syst
INST MySQL ene SOL stn
IN32 Common MySQL Data Tyres 4
134 Accessing Database in MySQL
135 Creating Tables in MySQL.
136 Inserting Data into Table
137 Making Simple Queries Through Select Command
Scating AME
Sctevting Particular Kises 4
lar Cedar 4
Sdeing P
Liminating Retertant Data (with Leyaved DISTINCD
Selecting From All the Roser - ALL Keyed 417
Virwang Stracturr fe Table 47
Performing Simpte C
tomy $8
Ung Cures Aliser 619
Conditun Based ona Range 438
13720 Conattaon Based om a List 43
INT AT Contitim awd on Pattern Matches 435
sr, ULL 419
138 Creating Tables with SQL Constraints
IST SQL Comatracats 440
INS2 Applying Table Constraints 44
ee
Searching be
436
440139
Viewing a Table Structure
13.40
Inserting Data into Another Table
13.11 Modifying Datain Tables
1312. Deleting Data from Tables
13.43 Altering Tables
13.4 Dropping Tables
13.45. squjoins
13.6 Indexes in Database
14 More on sau.
A7-N7 yy Introduction
V2 Ordering Records in Result - Order | ‘by Clause
N21 Resting SQL Sct Onder By Clase 457
Ordering Dato Multirle Columns 459
Ordering Data on the haves of an Exyrescion $59
N24 Sywerfving Custom Sot Onder 460)
W43 Aggregate Functions
U4 TypesofSQL Functions
145 Grouping Result - GROUP BY
HS Noted
NS? Ms
153
4.
ups ~ HAVING Clause 46)
vt Group Lapressions auth GROUP BY 469
15 Creating a Django based Basie Web Application
477-30 454 introduction
152. Whats Web Framework?
153, How Web, Websitesand Web-applications Work?
184. Introducing Django
155. Installing Dyan
15.5.1 drstalong Dusngoin Virtual Environment 41
156 Activating Virtual Env
Django Basics and Project Structure
IST What are Projet and Ap in Django ? $86
1572, Understanding Django Prout Architecture 490
158. Steps toCreatea Hasic Django Web Application
15.9 Creating Models, Views and Templates
1581 Creating A
159.2 Creating Templates 433
onment
wets 432
1593 Creating Views 434
15.9.4 Creating URL. Comps 495
15.10. Writing Dictionary Data to CSV and Text Files
15.11 Practically Processing Getand Post Request
|
444
44s
AAS
4AS
446
447
a7
448
457
457
462
465
465
477
477
478
480
480
464
485
oT
492
498
49016 Interface Python with MySQL
S11 - 524 14.1 Introduction yt
162 Connecting to MySQL fromPython .
1821 Steps for Creating Datatune Connectivity Apptications 512
163 Parameterised Quertes
164. Performing InsertandUpdate Queries
17 | Society, Law and Ethics
525-580/ 17.1 Introduction
172 Ethical Issues
T7221 Intelintual Property Righis 526
1722 Paguram 526
IL Digi Pnperty Rights
173 Open Source Philosophy and Saftware Licences
ILL Termintogy 528
1732. Philosophy ef Open Swurce 529
1733 Defintaons 539
IL34_ Licenses and Domains of Open Source Tethnology 532
Ww
7s
6
177
178
= vs
17.10
an
waz
way
Appendix
AL-A.18
Privacy
Online Froud
Gyber Crime
Computer Forensics
Cyber Law and IT Act
Technology and Society
7.91 Eaomomic Benefit
E-waste Management
I2UO1 EA¥asie Diya! Prvess 540)
0
T2102 Refit of eWavte Recycling 541
entity Theft
Gender Issues while Teaching/Using Computers
VALI Gerder tssues 540
Disability sues while Teaching and Using Computers
Appendix A: Utiity of Module's _name_
Appendic 8: Working with A Useful Python Library-Tkinter
Appendix C: Django installation on Ubuntu Linux
Appendix D: Creating (data) Models for Djangoapps
Appendix E: Insalling MySQL Python Connector
Appendix F Project Creationand Distribution
ee)
su
su
519
521
525
526
528
534
534
536
538
538
$39
540
SH
543
545
AL
AQ
AG
AO
Anll
www.worldvideweb.com
Python
Revision Tour
Tn Wis Charter
22 Introduction
18 Expressions:
12° Tokens in Python 1.9. Statement Flaw Control
1a
Barebones of a Python Program 1.10 The if Condvonats
24 Vanables and Assignments 111 Looping Statements:
25) Simple tnput and Output 112. Jump Statements — break and continue
16 Data Types 213° More on Loops
uw
Mutable and immutatte Types.
INTRODUCTION
You must have enjoyed learning Python in class XL. Python
by Guido Vom Rossin in early 1990s, has become a vory popular Programming language
among beginners as well as developers. The journey of Python that you started in clase X1 will
Continue in class XI as well, In class XI, you shall learn more about Python and some advanced
concepts, Before we start swith never topics and concepts in Python, Its revise all that you
have learnt in class XL. And this chapter will be doing ju », take you to the revision
tour of Python that you learnt
Programming language, developed
he sam
your previous class.ww.worldvideweb.com
COMPUTER SCIENCE WITH PYTHOr _ ey
2
na
1.2. TOKENS IN PYTHON
The smallest individual unit in a program is known as a Token
or a lexical unit.
The smallest indeidual unit in
| program is tnown a 37
Python has following tokens : ‘nfettcet oie hen at
() Keywords (if) Identifiers (Names) _ (fi) Literals
(ip) Operators (v) Punctuators
= A sazple Python progran
for a1,in range(1,<2
A 4 "
punctuators
x
. ff aX2 =p a
beywords teal
prints SS
Be knees
ertfers
Figute 1.1. Some tolens in a Python program.
Let us revise our understanding of tokens.
3 1.2.1. Keywords
Keywords are predefined words with special meaning, to the A heyiaeh te» Wd hn
language compiler or interpreter. These are reserved for special meaning reserved by
special purpose and must not be used as normal identifier programming language.
names.
Python programming language contains the following keywords =
False assert del for in or while
None break elif from is pass with
True lass else global lambda raise yield
and continue except if Ponlocal return
as def finally impor not try
1.2.2 Identifiers (Names)
Identifiers are the names given to different paris of the progearn
Functions, lists, dictionaries and so forth.
The naming rules for Python identifiers can be summarized as follows : f
© Variable names must only be a nom-keyword word with
Po spaces in between.
riables, objects, classes,
© Variable names must be made up of
ip of only letters, tt
numbers, and underscore (_), Ce hc ont lores
n ff
© Variable names cannot begin with a number, although eater an
they can contain numbers,The following are some
The following are sume invalid identifiers :
valid identifiers :
DATA-REC contains speaal character - (hyphen)
yftte OATES 777 (other than A 7, a+z.and _ (underscore) )
F
aoe aS 29cLcT ‘Starting with a digit
HK FILEL3, 1 4
721029 HT3 1K break reserved heywor
7 My.file contains special character dot (.)
1.2.3 LiteralsValues
Literals are data items that have a fixed/constant value.
Python allows several kinds of literals, which are being given below.
(i) String Literals
A string literal is 4 sequence of characters surrounded by quotes (single or double or triple quotes).
String literals can either be single line strings or multi-line strings.
© Single fine strings must terminate in one line 14, the closing quotes should be on the
same Tine as that of the opening, quates. (See below)
© Mult
ine strings are strings spread across multiple lines. With single and double quotes,
each line other that the concluding line has an end character as \ (backslash) but with
triple quotes, no backslash is nevded at the end of intermediate lines. (see below) :
>>> Text = "Hello world” <—___
>>> Text2 © “Hello\
oes
Morld* Mattie sing
Single tine seing
Text3="**Hollo«
Worla!** No fuckatnh needed
In strings, you can include non-geap
characters through escape sequences. Escape sequences
are given in following table :
Escape What it does Escope | What it does
___ sequence [Non-graphic character] __| __sequence. __[Nongrophie character)
Ny | Backslash (\) \e Carriage Retum (CR)
v Single quote (') \t Horizontal Tab (TAB)
uv | Double quate (") Vue Character with 16-bit hex value
| xxx (Unicode only)
\a | ASCII Bell (DEL) \Urmnx, Character with 32-bit hex value
| xwecere (Unicode only)
\b ASCII Backspace (BS) \v ASCII Vertical Tab (VT)
\t ASCII Formfced (FF) \o00 Character with octal value 000
\n New line character \xhh Character with hex value hh.
\Niname} | Character named name in the
Unicode database (Unicode only)COMPUTER SCIENCE WaT PYTHON — 54
(u) Numeric Literals
Numeric literals are
numeric values and these can be one of the following types
{o) int (signed integers) often called just integers or ints, are positive or negative whole
numbers with no decimal point :
The integer literals can be wrilten in :
© Decimal form : an integer beginning with digits 1-9. ¢.g., 1234, 4100 etc.
{© Octal form : an integer beginning with 0a (zero followed by letter 0) e., 0035, 0077 ete,
Here do remember that for Octal, 6 and 9 are invalid digits.
mal form : an integer beginning with Ox (zero followed by letter X) e., 0x73,
rs for hexadecimal numbers are 0-9 and
© Hexadeci
OxAF ete. Here remember that valid digits/ette
AF.
(b) Floating Point Literals. Floating point literals or real literals floats represent real numbers
and are written with a decimal point dividing the integer and fractional parts are numbers
having fractional parts, These can be written in fractional form eg. “130, 75, 7. ete, or in
Exponent form e,, 0.1765, 3.£2, GEM etc.
(c) Complex number literals are of the form a+ bf, where a and bare floats and J (or f) represents
JL, which is an imaginary number). «is the real part of the number, and b is the imaginary
part.
= (ii) Boolean Literals
‘A Boolean literal in Python is used to represent one of the two Boolean values i.c., True (Boolean,
truc) or False (Boolean false), A Boolean literal can either have value as True or as False.
(iv) Special Literal None
Python has one special literal, which is None. The None I
value.
Python can also store literal collections, in the form of tuples and lists ete.
| is used to indicate absence of
1.2.4 Operators
Operators are tokens that trigger some computation / action when applied to variables and other
objects in an expression.
The operators can be arithmetic operators (4, -,*, /, %, **, //), bitwise operators (&, °, |), shift
operators (<<, >>), identity operators (is, is not), relational operators (>, <, >=, <=, ==, !=), logical
operators (and, or), assignment operator (=), membership operators (in, not in), and
arithmetic-assignment operators (J, , N=).
8h he, *
1.2.5 Punctuators
Purctuators are symbols that are used in programming languages to organize sentence
structures, and indicate the rhythm and emphasis of expressions, statements, and program
‘structure.
‘Most common punctuators of Python programming language are :
"THVOEIII@, FosChop 1+ PYTHON FEMISION TOUR .
1,3 BAREBONES OF A PYTHON PROGRAM
A Python program may contain various elements such as evnments, statements, expressions ete.
Let us talk about the basic structure of a Python program,
{* This progean shows a propran’s components
¥ DeFinit Jon of functson Seevou() Follows
Comments & def See¥ou) :
tpn wich @) Print ("Time to say Good Bye 11")
+ Function
Main progean-code follows now
ae ass
severe - :
be a-106 .
, SS erin
print (a+3) “ a 7
if bos? ® colon means it’s ablock
eww Print ("Valve of ‘a was more than 15 initially”) Inline comments
Sadentetion ovrmment Fepaning
lie indented tne. ese :
nthe make of a ine)
‘* print ("Value of ‘a was 15 or less initially.")
——* SeeYou()
anc ell —
fc 4 cal ling above defined function SeeYou()
AS you can see that the above sample program contains various components like :
© Expressions, which are any legal combination of symbols that represents a value,
© Statements, which are programming instructions.
© Comments, which are the additional readable information to clarify the source code,
Comments can be single line comments, that start with # and multi-line comments that
can be either triple-quoted strings of multiple # style comments.
© Functions, which are named code-sections and can be reused by specifying theit names
(function calls)
© Mock(s) or suite(s), which isa y
2 function. All statements in
up of statements which are part of another statement or
He a block or suite are indented at the same level
VARIABLES AND ASSIGNMENTS.
Variables represent labelled storage locations, whose values can be manipulated during
program run.
InP, le, just assign to its name the value of appropriate type. For
example, to create a variable namely Student to hold student’s name and variable age to hold
student's age, you just nved to write somewhat similar to what is shown below :
Student ="Jacobt
Age = 16
hon, to create a var1.4.1 Dynamic Typing
Dynamic Typing vs. Sta!
1.4.2 Multiple Assignments
COMPUTER SCIENCE WITH PYTHON a
Python will intemally create labels referring to these values as shown below,
«[>}-—]
ln Python, as you have learnt a variable is defined by assigning to it some value (ofa particu
type such as numeric, string etc). For instaney, alter the statement :
X=10
We can say that variable x is referring to a value of integer type.
Later in your program, if you reassign a value of some other type to variable x, Python will ot
complain (no error will be raised), ¢4
DET
xe10 IY
print(x) A variable pointing to a value of
2 certain type, can be made to
X= Hello world point to a value/object of
prant(x) Aitferent type. This is called
Dynamic Typing.
Above code will yield the output as :
ww
Hello world
So, you can think of Python variables as labels associated with objects (lit
feral values in our ease
here) ; with dynamic typing, Python makes a label refer to new value
with new assignment
(Fig. 1.2). Following figure illustrates it
new (Qe)
X= “Mello woria~ * +
+{_intsx0
Figure 1.2. Dynamic typing in Python variables
Typing
Dynamic typing is different (rom Stalic Typing, In Static typing. a data type is altached with a
¥ariable when it is defined first and itis fixed. That is, data type of a variable cannot be changed
in static typing whervas there is no such restriction in dynamic typing, which is supported by
Python.
Python is very versatile with assignments, Let’s see how.
1. Assigning same value to multiple variables. You can assign same value to multiple
variables in a single statement, ¢y..
asbec=10
1 will assign value 10 to all three variables a, be.=
He values 10 multiple variables. You can even assign multiple values to
iables in single statement, ¢:
X,Y, 2=10, 26, 30
Chopler 1: PYTHON REVISION TOUR
2 Assigning multipl
multiple v;
Tt will assign the values order urse, ie, first variable is given first value, second variable
the second value
and so on. That means, above statement will assign value 10 to x, 20 to
¥ and 30 to =,
Ifyou want to swap values of x and y, you just need to write as follows :
May, x
In Python, assigning a value to a variable means, variable's label is referring to that value.
val=3
val 6
[for statenent
val = 3)
| Mor statesent
0 | val = 6)
val
Memory adgiess (3000) Momory adress {3048} sionng
jonng value Sis assigneda value G is assigned a label as
bel as val {lor statement val = 6).
Val {for statemont val = 3] Now val no longor is referencing
to memery locaton 3000,
Literal values are having a fixed location and variable
fhames reference them as labels,
Vanable val stores values at same location
(memory-address) and changes values
stored in it
{a) In traditional programming languages
Uke CiC++ etc.
i
(2) In Python programming language
Figure 1.3 Mow vaviables ae stored in traditional programming languages and in Python.
1.5 SIMPLE INPUT AND OUTPUT
In Python 3.x, to get input from user interactivel
function input) is used in the following manner :
‘ou can use built-in function input( ). The
vortable_to_hold_the_value = input (
)
For example,
ane = input ("what is your name 2")
The above statement will display the prompt as :COMPUTER SCIENCE WITH PYTHON ~ yy
ffers two functions j
a value af String type. Python ot tions fn)
iro tesed with inp to ont the values ected hough Input isin)
and float() to be
float types. You can: ,
e ¢ value using input( ) function.
: i “ihe ia int Yor float) function with the read lve to change the type of input valug
© And then use f
to int of float respectively.
ii ingle stey fe, AS 2
You can also combine these two steps in a single step too,
« int( input( ) )
Or
«varfable_naze> = Float( input( «prompt string>) )
Function ini(} ound input)
converts tha read value into int type
and function float) around input)
In (20): age = int
inputs
wrat ts your ope? 16 function converts the read value into
float typo.
tn (23)
outa]: Mo
s(eares)
2} tyre
2): ine
While inputting integer valucs using int() with input(), make sure that the v
must be int type compatible. Similarly, while inpulting floatin
inpult), make sure thal the value being entered must be float
be converted to int or float, hence it is not comp.
‘alue being entered
1S point values using float() with
ype compatible (
‘abe’ cannot
Output Through print ) Staternent
The print ) function of P
ython 3. is a way to send output to st
normally a monitor,
andard output device, which is
‘The simplified syntax to use print( ) function is as follows :
Print(*objects, [ sep=*? op })§
“objects means it can be one or multiple comm:
‘9 separated objvcts to be printed.
Let us consider some simple examples first ;
print ("hello") #a string
print (17.5) # anunber
Print (3.14159°(r+n)) E the result of a calculation, which will
# be performed by Python and then printed
# out (assuming that Some number has been
# assigned to chi ri
print (I\’a, 12+5,"years old, ) =n
"sultiple coma separated expressionsze
www.woridvl
hoplet | + PYTHON REVISION TOUR
The print statement has a number of features :
© it auto-converts the
automatically conv
first ev
lems to strings ic, sf you are printing a numeric value, it will
ert i into equivalent string and print it ; for numenc expressions, It
wales them and then converts thy result to string, before printing.
© It inserls spaces between items automatically because the defaull value of sep argurment
(separator character) is space’ ),
Consider this code :
Fur dive anny obs wk mo
Print (*Hy*, “nane", "is" att) juve in ther are being print.
will print
fu the capt oes anmnatlly pace ised in
FR ie cae tap car a ae
‘You can change the value of separator character with sep argument of print()as per this:
The code:
Print ("Hy", "mane", "is", *anit.", sep=
will print ee
Myscotane 48. camig, @-———— TB ie te print agua i tes
sae pc ap charaster, while
© it appends 9 newline character al the end of the line unless you give your own end
argument, Consider the code given below :
print ("My name is amit.*)
print("I an 16 years old")
A print) function without any
value or name or expression
My mane is anit. eed
1 an 16 years old
Itawill produce output as :
you explicitly givean end argument with a print) function then the print() will printthe tine
and end it with the string specified with the end argument, and not the newline character, eg.
the code
print(*Mynane is Amit. *, end = $)
print("Lama6yearsold.~) +"
will print output as: a r
Mat int) endl he ine ith
sharaster. whi
re tad fever
hy name is Anit. $1am 1G years old. newline net bine wn rita fren how ial
1.1 Write @ program to input a number and print its cube.
nun = float(input( ‘Enter a number: *))
fum_cube = nun * num * num
print("The cube of’, num, "is*, num_cube)COMPUTER SCIENCE WITH PYTH(
Pe 10 oto
1.2. Write « program to Input a number and print its square root.
jegam num = Float (input(‘Enter a nunber: *))
nun_sqrt «nun ** 0.5
print(‘The square root of*, num, "45", num_sqrt)
ramon pase nnvrioure? _ Progiess In Phan 1.1
ee
This ‘Prif” session is aimed at revising various concepts you learnt in Class Xl,
Pleose check the practical component-book ~ Progress in Computer
Science with Python ond fill i thera in PuP 1.1 under Chapter 1 cftor
practically doing it on the computer.
poraicee
1.6 DATA TYPES
Data types are means to identify type of data and set of valid operations for it, Python offers
following built-in core data types : (i) Numbers (x) String (ii) List (ie) Tuple (v) Dictionary,
B (i) Dota types for Numbers
Python offers following data types lo store and process different types of numeric data :
(a) Integers
© Integers (signed)
© Booleat
(b) Floating-Point Numbers
(0) Complex Numbers
(a) Integers. There are tv types of integers in Python :
(i) Integers (signed). 11 is the normal integer representation of whole numbers. Python 32x
provides single data type (inf) lo store any integer, whether big or suall.
It is signed representation, i, the integers can be positive
as well as negative.
(i) Booleans. These represent the truth values False and True, The Boolean type is a
sublype of plain integers, and Boolean values False and True behave like the values 0
and 1, respectively.
Numbers. In Python, floating point numbers represent machine-level double
precision floating point numbers (15 digit precision), The range of these numbers is limited by
underlying machine architecture subject to available (virtual) memory.
(Q Complex Numbers. Python represents complex numbers in the form A + Bj. Complex
numbers area composite quantity made of two parts : the real part and the imaginary part, both of
Which are represented internally as float values ({loaling point numbers).Chopter 1 PYTHON REVISION TOUR
You can rel eve the two components ‘using attribute
references. For a complex number
real part,
© cimag gives the im
complex value,
Table 1.1. the Range of Python Numbers
© areal gives the
iginary part asa float, not as a
Integers
Se unlimited range, subject tn available (virtualy memory only |
| Bouteans tiny
_ tes Tru (1), False (0)
Floating point | any untimitt ran
rene W unlimited 1
subject to available (virtual) memory on.
unde
acting arebitecture.
Compter
Same as floating point numbers because the real and
numbers eli
imaginary pauty are represented a flaate
(il Dota Type for Strings
Allstrings in Python 3.x are
represent ow
i
sequences of pure Unico
character from every langu:
rs, and 5
characters. Unicade is a system designed to
age. A string can hold any type of known characters
H characters, of any known scripted language.
Following are all legal strings in Python = Sh CS
letters, num:
“abed” . "1234", +g)
apy”
Valid string Indices ate 0, 1,
2... upto fength-1 In forward
direction and ~1,-2,-3...
squence of charocters and each character _~fength In backward dection,
can be individually accessed using its index.
(ii) Lists
A Python string isa
A List in Python represents a group of comma-separated values of any
square brackets eg,, following ate some lists :
(1,2, 3,4, 5)
Ca ]
[Neha’, 102, 79.5)
datatype between
In list too, the values internally are numbered from 0 (zero) onwards ie, first item of the list is
internally numbered as 0, second item of the list as 1, 3rd item as 2 and so on.
(iv) Tuples
Tuples are represented as group of comma-separated values of
Values of type fist are mutoble
any date type within parentheses, following aresome tuples: Ley ehangeatle — one cn
p= (1, 2, 3,4, 5)
a= (2, 4, 6, 8)COMPUTER SCIENCE WITH PriFion _ 5
{v) Dictionaries ; /
The dictionary is an unordered set of comma parated key value pais, within (1, eth
requirement that within a dictionary, no two Keys can be the same (ley there are unique kaye
within a dictionary). For instance, following are some dictionaries :
13,'0:4, 0: 5)
ari,ter2,
5)
poo vowels = (at 21, "e 2, [23,0 14,"
>>> vowels{'a'] “Shik
2 125A Sat
and are the heys of dictionary nnvel;
fe nae for tise Leys tespeutivey
Following figure summarizes the core data types of Python.
Core Data Types.
Naber None Sexionces Moopings
-—t—_i =< |
Integer Floating Complex. String Tupie Uist Dictionary
I pont,
Boolean
1,7. MUTABLE AND IMMUTABLE TYPES
The Python data objects can be broadly categorized into few = mutable and immutable types, in
simple words changeable or modifiable and non-modifiable types.
Immutable Types
The immutable types are those that can never change their value in place. In Pyt
a int nuondvry, Badans, strings, laps
‘on, the following
types are immutable =
In immutable types, the variable names are stored as re
you change the value, the variable’s refe
explanation for sample code
rences to a value-object. Each time
‘nce memory address changes. See following
on below 2
Pes
aeP
res
P=10
re?
qer
© Initially these three statements are execuled :
p=s
. ‘All variates having same lu refererice an! the ame
q 2 4 talaeebect Ke. pag. #4 al ference same integer
reChopter I: PYTHON REVISION TOUR
Each integar
value Is an
immutable
object
Figure 1.4
© When the next set of. statements execute, ie,
prio
re?
qer
then these variable
‘names are made to point to different integer objects.
Fagure 2.5,
Mutable Types }
— Python frontloads some commonly
Mulability means that in the same memory address, new used valies. in. memory. Each
value can be stored as and when you want. The types that do 2ble referring to that value
hot support this properly are immutable types ee See
The mutable types are those whose values can be changed in Yariables/identtiers can refer to a
e Only three types are muta i value. Internally Python keeps
place. Only three types are mutable in Python. Bee
Thew are : lists, dictionarics and sets. Variables are referring to a value,
To change a member of a list, you may write
chk = (2, 4, 6]
Chk[1] = 40
[twill make the list namely Chk as [2, 40, 6].7 COMPUTER SCIENCE With,
1,8 EXPRESSIONS
An expression in Python is any valid combination of eperators, literals and wnriay,
type t arithmetic expressions, string expressions, pigy
exprssions in Python can be of any
logical expressions, evmpound expressions ete, .
s foating:
ic operators,
eapressions,
Arithmetic expressions involve numbers (inteys a
point numbers, compler numbers) and arithme tas conpnaton a i
65225" 3- 8708 fopraratahs:
Iles of any valid composed of one or re
operation.
An expression having literals and/or vari.
type and relational operators is a relational expression, /
example, these are valid relational expressions :
xy zeeq, xcyoz, xewylez
nd/or variables af any valid type and log
these are valid! logical expressions :
wv, yenay
al operators is g
An expression having literals
logical expression. For exam
aorb, bandc, aandnotb, notcornoth
operators + and *, when combined with string operands and
Python also provides two strin
integers. form string expressions.
Following are some legal string evpressions :
wang™ + “then” would result into ‘andthen’ = concatenation
2 tang" #2 Fyould result into ‘andand’ = replication
1.8.1 Evaluating Arithmetic Operations
Toevaluate an anthmetic expression (with operator and operands), Python follows these rules;
© Determines the order of evaluation in an expression considering the aperator precedence,
in the form of
© As per the evaluation order, for each of the subseypression (generally
coperator ey, 13% 3)
ands or arguments,
# Evaluate cach of ity ope
# Performs any implicit conversions (e.g, promoting, int te float or bool to int for
arithmetic on mixed types). Fer implicit conversion rules of Python, read the text
given after the rules
= Compute its resull based on the operator,
a Replace the subeupression with the computed result and carry an the expression
evaluation.
Repeat till the final result is obtained.
Ina mixed arithmetic expression, Python converts all operands up to the type of the largest
operand ({ype promotion). In the simplest form, an expression is like opt operator op2 (8
{ both arguments are standard numeric types, the following coercions are
aly or p** a). Here,
applied : : " aie
© Mf either argument is a complex number, the other is”
converted to comple ; type conversion 9
© Othenwi if either argument is a floating point conversion performed oy the
number, the other is converted to floating point ; erie serene
© No conversion if both operands are integers.Chopler I: PYTHON REVISION TOUR
Table operator precedence
[Operator ra Description
0 Parentheses (grouping) stones
. Exponentiation
- Biwwise nor
Vositive, negative (unary + ,)
Muluplication, division, floor division, remainder
te Addition, subtraction,
& Bitwise AND
” Hitwise NOR
1 Ditwise OR
q) and (qe y) (il) (acs N) and (N<= 1)
1.8.3 Evaluating Logical Expressions
While evaluating logical expressions, Python follows these rules :
(i) The precedence of logical operators is lower than the arithmetic operators, so constit
arithmetic sub-expres
applied, eg,
25/5 0r 2.0 + 20/10
So, the overall result will be 5.
be first evaluated as; 5 0r 4.8
(ii) The precedence of logical operators among themselves is not, and, oF.So, the expression
2 or band not ¢ will by evaluated as :
Similarly,
pand q or not rwill be evaluated as:
following expression
(aor (band (not ¢) )) ((p and q) or (not ny)
(i) Important. While evaluating, Python minimizes intemal work by following these rules :
‘thon only evaluates the second argument if the fist one is false jy
a4 (a) In or evaluation, Py
(6) Inand evaluation, Python only evaluates the second argument if the first one is trey
Example 13° What will be the output of fl
(5.€19) and (19 5) of (3 ¢ 18) and not 818
Solution. False
ing expression ?
1.8.4 Type Costing (Explici
Aneaplicit type cunversian is user-defined conversion thal forces an expression tobe of specific
type. The explicit type conversion is also known as Type Casting.
Type Conversion)
Type casting in Python is performed by type>( ) function of appropriate data type, in the
following manner :
(expression)
where is the data type to which you want to SUNG |
type-cast your expression. omversi
The exzlcit conversion of an
For exomple, if we have (a = 3 and b = 5.0), then operand ta a specific type is
Ant (b) called type casting.
will cast the data-type of the expression as int.
1.8.5 Math Library Functions
Python’s standard library providesa module namely math for math related functions that work
with all number types except for complex numbers.hopes 1 + PYTHON REVISION TOUR
In order to work wath functions of math module, you need to first import ito your program: by
giving statement as follows as the top line af your Python script :
Amport math
Then you can use math hbrary’s functions as math. «
Table 1.2. Some Mathematical Functions in math Module
fs Pi ~
Functle rototype le
No. 2"| (General Form) Description Example
1 feel] math ceil{num The cetit ) function reiums the | mathcvil(1.03) pives 20
ff arnt integer nt es tha ra, | math ecil(-103)_ gives -U
sqrt | math sat (num) The sqitt } function returns the | math sqrt(81.0) gives 90.
sqjutare root of num. Hf num <0,
7 |———___ Jomain error occurs. |
a [exp | mathexpiany ‘The exp() function retums the | mathexp(2.0) gives the value
natural logarithm ¢ raised to the | of
|— arg power
4. | fabs math fabs (num) The fabst ) func
5
returns the math fabs(1.0) paves 1.0
sf um math fabs(-10) gives 10.
as abyolute vals
‘The floart ) function returns the | math floor (103) gives 10.
largest integer not greater than | math floor(-103) gives -20.
6. | lox math log, (num, [base]) | The loge } function returns the | math log(1.0) gives the natural
natural logarithm for mm, A} logarithm for 10,
domain ertor occurs if nant 8] pyath tog(1O24, 2) will give
egative and a tangs error eu) 7 pithy of 102A to the base 2.
if the argument num iy zen, | °F
7 | AoglO | mathtog10 (rum) | The toga» function returns | mathlogl0(1.0) gives base 10
2010 fogorithin for men. | lagarithim for 1.0,
A domain error occurs if nim as
and a range error
if the anya
lis 2010,
8. | pow | math pow (base, exp)
pow( funtion returns base | math,pow 0, 0)
raised to exp power fey. tise exp. | 9°
es value of
A domain error occurs if busr =O] math.pow (40, 2.0) pives value
and esp <0, oho flue cand ore at no) Bites
| fag is nat integer i _
% an) The sint 9 function wetums the | math sin wal)
Sine uf arg. The value of arg | (tut és a number),
i _ rust be in radians cate
10, | cos | mathcos(arg) The cost } function returns the | matheos(val)
cosine of arg. The value of arg
(vs is. number),
must be in radians
Ti. | tan math.tan(arg) ‘The tan() function returns the | math tan(val)
tangent of arg. The value of arg | (val is a number)
must be in radians,
math.degrees(3) The degreest } converts angle x | math degrees (3.14) would give
- _| from ratdians to degrees. ws _
mathradiansx) ‘The radians() converts angle x | math.radians (179.91) would
from degrees to radians. give 24w.worldvideweb.com
COMPUTER SCIENCE vaTH pry
)~ =, DATA HANDLING
ProaresslnPrhen 4
This ‘Pril” session Is aimed at revising various concepts you learnt in Class XI.
Science with Python and fill it there in PrP 1.2 under Chapter | ofter
practically doing « on the computer.
‘¢ Please check the practical component-book - Progress in Computer )
perteace
LeT Us REVISE
——————
& A Python program can contain vurious components like expressions, statements, comments, functions, blocks ang
indentation.
Blocks ore represented through indentation,
Prnton suppers dynamic typing ie. @ voriable con hold values of different ‘ypes of different times,
The taped is used to ebeorn op from user 5 I always terurm 0 ring pe of value
Output ts generated through print} (by culling print function) statement.
Operators are the symbols (or beywords sometimes) that represent specific ©
Arerpreasions composed ef one or more operations. tsa ulid combunation
Types of operotors used in on en
arithmetic expression.
pperations.
ooo ooed
of operctors, Iterals and variables,
‘Preston determine its type, For instance, use of arithmetic operators makes it
Expressions con be arithmetic, relational vr logical, compound ete
In Implicit conversion, all operands are converted up to the fe of the largest operand, which is called ype
Promotion or coercion
The explicit cunversion of an operand toa specific ype is called ype casting and it is done usin
functions that is used a3
oe
ype conversion
<*9P6 conversion function » ( cexpression>)
1.9 STATEMENT FLOW CONTROL
In a program, statements may
be executed sequent
Program
n ally. selectively or iteratively. Every
6 language provides constructs to SUPPort sequence, selection or iteration
A conditional isa statement set whichis executed, on the:
a statement set which is executed repeatedly, until the
1. Compound Statement
A compound statement rej
r of statements executed as a unit. The compound
Statements of Python are written in a specie Patter as shown below :
basis of result of a condition. A loopis
end condition is satisfied,
“Compound statement header > ;
«indented body containing Bultiple simple and/or ‘Compound statenents>gy
PYINON RLVIION TOUR
osonr |
‘The conditlonals and the loops are compound statements, ic, they contain other statements,
For all compound statements, following points hold :
© The contained statements are not written in the same column as the control statement
rather they are indented to the right and together they are called a block.
© The first line of compound statement, i, ils header contains a colon () at the end of t-
For example :
unl = int(input ("Enter numberi"))
nun « Ant (input ("Enter number")
Af mumd «mum 2 ¢————— The cud (4) ne ref ener on
reset 8 comp Hemet
ts num2 * nun2
tatele Ihe cosines saterens wuhin fore
leaders othe night
print(num2, num, t)
2. Simple Stotement
Compound statements are made of simple statements, Any single execulable statement is a
simple statement in Python,
3. Empty Stotement
The simplest stateinent is the emply statement ,, a statement which does nothing. In Python
an empty statement is the puss statement.
It takes the following form :
pass
Wherever Python encounters a pass statement, Python does nothing and moves to next
statement in the flow of control
1.10 THE IF CONDITIONALS
The if conditionals of Python come in multiple forms : plain if conditional, if-else conditional
and if-elif conditionals.
1.10.1 Plain if Conditional Statement
An if statement tests a particular condition; if the condition
evaluates to Irie, a course-of-oction is followed ic. a
statement or sct-ol-statements is exccuted, If the condition is
filse, it does nothing :
The syntax (general form) of the if statement is as shown
below :
4 cconditional expression»
statement
[statements]COMPUTER SCIENCE Wit Pr HO4y
For example, consider the following code fragments using if conditionals :
Af grade
print ("Congratulations! You did well")
fab:
print ("A has nore than B has")
print ("Their difference 1s", (a-b))
1.10.2 The if-else Conditional Statement
This form of if statement tests a condition and if the condition evaluates to true, it carries
statements indented below if and in case condition evaluates to false, it carries out sta
indented below else.
The syntax (general form) of the if-else statement is !
as shown below : Test Fase ;
Expression HEE 6 body of abe
Af cconditional expression? : ? "a
statement |rve
[statenents]
else: | Body of if
statenent
j [statements]
For example, consider the following code fragments using if-else conditionals =
Ma 0 8 a coon it bse a
print(a, “is zeroor a positive number") healer us usilas ese
The statements im flock and ee are
elses indented
print(a, “is a negative number")
1.10.3. The if-elif Conditional Statement
Sometimes, you want to check a condition when control reaches else, i.c., condition test in the
form of else if. To serve such conditions, Python provides
‘The general form of these statements is :
clif and if-elif-else statements,
| AF = 100 :
print("datsman scored a century")
elif runs >= 50:
print ("Batsman scored a fifty")
else:
print (“Batsman has neither scored a century nor fifty")
Af nun <0:
print(nus, "is a negative nuaber.
elif nun«=0:
Print (num, “Ls equal to zero.*)
else :
print (num, “1s a positive number.
1.3 Write a program that inputs an integer in range O - 99 and then prints if the integer entered isa 23.
digit number,
num = int (input ("Enter a nusber (0. .999) : ))
if nun ¢ 0:
print (“Invalid entry. valid range 1s 0 to 999.")
elif nun< 10:
print ("Single digit nusber Ls entered”)
elif num < 100:
print ("Two digit nunber is entered")
elif nun <= 999:
print ("Three digit nunber 4s entered”)
else:
print (“Invalid entry. Valid range 1s ® to 999.")
Sample runs of this program are given below
Enter a number (0,999) : -3
Invalid entry. valid range is 0 to 999.
Enter a number (0..999) : 4
Single digit nunber is entered
Enter a number (0..999) : 100
Three digit number is entered
eecenenen ee
Enter a number (0..999) : 10
Two digit number is entered
ee
Enter a nunber (0.999) + 3000
Ll) Invalid entry. Valid range is 0 to 999.COMPUTER SCILNCE WaTH PINON - 54
1.10.4 Nosted if Statemants
Sometines yo may need to test additional conditions. For such situations, Python also
aupporte neatedsi( form of lf. A nested ifs an ifthat has another if in its ifs body or in elitty
body or in th
Consider the fullawving, example code using
x= dat (input ("Enter Lest number 2"))
¥= Lat (input ("Enter second number :”))
= Ant (input ("Fater thied number :°))
o's body.
jed-if statements =
min= mid= max = None
Afscyandx cr:
[ifyer:
min, ald, naxx, ¥)%
else: be
min, ald, maxx, 2,9
if aeaterent inside another if
(Nested is)
olify cx andy cz:
Mfxezi
ain, mid, max=y, x2
= jase
min, mid, max*y, 2) x
min, mid, max=2, x59 |
else:
ain, mid, max =z, ¥, X
print ("ushers inascending order :*, nin, mid, ox)
1.10.5. Storing Conditions
Sometimes the conditions t
your progeam more readable,
name and then use that named conditional in the if statements,
yy used in code are complex and repetitive. In such cases to make
vou can use named conditions i.c, you can store conditions in a
Consider the following, example code :
. b,c=2,3
aStore condition ina nane called all.
all» ame land b= 2and¢==34—__ ;
test varlable, eeewel
4 all:
print(*Condition ful filed")
Hse it again.
{f all:
print ("Condition fulfilled again.”)PO ‘
|
\ 1: PYTHON REVISION TOUR
{| 7
Using nested if statements, we can rewrite the previous program as follows :
1.4 Wrltea programm that inputs an Integer in range 0-999 and then peints Ifthe Integer entered is a 1/2/3
digit number, Use Nested if suaiements.
pum = int (input (“Enter a number (8..999) : "))
4 num <0 or nua > 999:
print(*Invalid entry. Valid range 1s 8 to 959,
else:
AF num ¢ 10;
print (“Single digit nunber ds entered”)
else:
if num < 100:
print (“Two digit number is entered”)
else:
Print(*Three digit number is entered”)
‘The sample run of this program is just the same as previous program.
1.11 LOOPING STATEMENTS
Python provides to kinds of loops : for loop and while loop to represent counting loop and
conditional loop respectively,
1.11.1. The for Loop
The for loop of Python is designed to process the ilems af any sequence, such asa list ora string,
one by one.
The General Form of for loop
The general form of for loop is as given betow :
for cvariable> in «sequences :
statements_to_repeat
For example, consider the fallowing loop :
for element in [10, 15, 20, 25] :
print(elenent +2, end =" ')
The above loop would give output as :
1 1? 22 27
© The above-given for loop executes a sequence of statements for each of the elements of
given sequence [10, 15, 20, 25}.
© Tokeep the count, it uses a control variable (clement inabove case) in that takes a different
value on each iteration. Firstly value 10, then the next value of sequence, 15, then 20 and
lastly 25.COMPUTER SCIENCE WaTH Pry,
bac)
The ronge( ) based for loop
For number based lists, you can specify range( ) function to represent a list as in :
for val Sa range(3, 18) =
print (val)
nerate alist [3,4, 5,01 16, 17] with which foF loop win
(val above) beforehand in a for loop.
e are three ways to define
Inthe above loop, range(3, 18) will first
work, You need not define loop variable
‘As mentioned, a range()) produces an integer number sequence, Th
range :
rolenents froa @ to stop-2, incrementing by 2
relenents froa start to stop-2, increnenting by 1
telenents from start to stop-1, incrementing by step
ise. The
range( stop)
range(start, stop)
range(start, stop, step)
wer part of the
1 The start value is always patt of the range. The stop value is new
step shows the ditfercnce belsseen two consecutive values in the range.
‘omitted, it is supposed to be 1.
© Ifstart values omitted, it supposed lo be 0. Ifthe step
Consider some examples of range( )as given below :
0,1,2,3,4,5,6
range(7)
= range(5, 12) 5,6, 7,8, 9,10, 11
range(S, 13, 2) 5,7,9.31
range(10, 4) no value
range(10, 4, -1) 10, 9, 8, 7,6,5
For example, the next program shows the cube of the numbers from 15 to 20:
1.5) Write a program to print cubes of numbers in the range 15 10 20,
for 4 Amrange(i5, 21):
print("Cube of nusber", 1
print(ist, 1°93)
wy
|) cube of nusber 15 is 3375
Cube of nusber 16 is 4096
Cube of number 17 is 4913
Cube of nunber 18 is 5832
Cube of number 19 is 6859
Cube of ausber 20 is 8000
F "
1.7 Write a program to print square root of every alternate number in the range 1 10 10.
for 4 inrange(1, 10, 2):
print ("square root of", i, "is", (1**0.5))www.worldvideweb.com
coopers 1 PITHON REVISION TOUR
1.11.2. The while Loop
A while loop is a conditional loop that will repeat the instructions within itself as long as a
conditional remains true (Boolean True or truth value true),
‘The general form of Python while loop is:
while :
‘loop-body
where the loop-body may contain a single statement or multiple statements or an
emply statement (i.e, pass statement). The loop iterates while the logical Expression evaluates to
true. When the expression becomes false, the program control passes to the line after the
loop-bouly.
P 1.8 wie 4 prograin that multiplies two integer numbers without using the * operator, using repeated
addition,
rope
com
1 = int (input("Enter First number
2 « Int Anput ("Enter second nusber :"))
product =8
count =n
while count >:
count = count - 1
product = product + a2
print ("The product of, ni, "and", n2, "is", product)
Enter first nunber
Enter second nunber : 5
The product of 4 and 5 is 20
In general, the while loop is used when it is not possible to know in advance how many
times the loop will be executed, but the termination condition is known. The while loop is
an entry-controlled loop as it has a control over entry in the loop in the form of test
condition.
1.12 JUMP STATEMENTS — break AND continue
Python offers two jump statements - break and continue —to be used within loops to jump out
of loop-iterations.
The breck Statement
A break statement terminates the very loop it lies within.
Execution resumes af the statement immediately following the
body of the terminated statement.COMPUTER SCIENCE WITH PYTHON =)
for evar> An csequence> :
The following figure
| Waite test condition +
The following code
fragment gives you an
(Fig. 1.6) explains the statement 2 statement 1 ‘
working of a break | Af + AF cconditiony :
statement. | eee Baik
| statenent 2 statement 2
statenent 3 A staterent 3 a
statenent 4 <5
example of a break statement 4 =a
statement: . - r oe
Figuee 1.6. The working of 2 break statement.
a=bec=O
for i fa range(1, 11) : ————-. range (1, 11) will generate a sequence
‘a= Ant (input ("Enter number 2 :*)) —«f memter from 1 10.
b= dnt (input ("Enter number
ifb
print ("Division by zeroerror! Aborting!")
break
else:
cxa/b
print ("quotient =", c)
print ("Programover !*)
The above code fragment intends to divide ten pairs of numbers by inputting twe numbers a
and bin each iteration. If the number b is zero, the loop is immediately terminated displaying
message ‘Division by zero error! Aborting! otherwise the numbers are repeatedly input and
their quotients are displayed.
The continue Statement
Unlike break statement, the continue statement forces the
~orati, . plies, y any code continue statement
next iteration of the loop to take place, skipping, any code in |Ke est of te lop sate
between. and causes the next iteration
The following figure (Fig. 1.7) explains the working of continue [the loop to take place
statement : .
hide etest-condlttem 1. atofthesttonnis 7 FOF ‘var> Am caequences + 3
statezent 2 fauhe Gere Uae statesent 2 j
| re shijgea und next
tendon tise armen: |
continue continue j
stateeent 2 statenent 2
statenent 3 stateent 3
statenent 4 sttenené
tn above loops, continue will cause skipping of statomnis 2
the Current lerabon and net eration wil start
Figure 1.7. The working of a continue statement.
eeGropter 1: PYTHON FEvision Tour,
1.13 MORE ON Loops
Thereare two more things you need to know abo
1.13.1 Loap else Stotement
Python loops have an oj
clause is as given belay
‘loops =the loyp ese clause and nested loops.
Plional else clause. Complete syntax of Python loops along with else
for cvarlable> in : while " statement | | ate 5 -*
J states | | sateen arent | see
(train) Mien) gy |e se
Dodyol- |= ~~ i the bop : |
teleop statesent statecent waa statenent | |
eto us ~ et
Samora, ap sateert >
cursido tink | statenert:
Suaments —_ _f sattert sy
cutside the loop) statenent
Figure 1.8 Contiol low in Python loops,
Consider following exarnple :
for a in range (1,4) =
ifaXBe-
break
print("Elenent is", end='*)
print(a)
fine inert Loop after printing a1 elenents of sequence")COMPUTER SCIENCE WITH PTHON — 3
The above will give the following output :
This line pried becase the eae
clase of pen for lp ecu ute
ies st the for lp we ensting. sory
Elesent is
Elesent is 3
Ending loop after printing all elesents of sequence.
If, in above code, you change the line
sfaXBa=0
with
ifax2as0:
Then the output will be :
Seen $$ —____ aie ta fir a= 2, he bet po xed rd oop
erminstal Horse just ove clement pot pried Ufor a 1).
As break terminated the lop the ese cliwe aloo did
The else clause works identically in while fot sie eg, he lig ah
loop, iz, executes if the test-condition goes
false and in case of break statement, the
loop-else clause is not executed.
1.13.2. Nested Loops
A loop may contain another loop in its body. This form of a loop is called nested loop. But in a
nested loop, the inner loop must terminate before the outer loop.
The following is an example of a nested loop :
for i inrange(1, 6) :
for j in range (1, i ye
print( end =
)
print()
In nested loops, a break statement will terminate the very loop it appears in. That is, if break
Stslement is inside the inner loop then only the inner loop will terminate
‘ and outer loop will
Continue. If however, the break statement is in outer loop, the
outer loop will terminate.
Col
cP NTROL FLOW STATEMENTS Progress In Python
This “Pril™ session is aimed at revising various concepts you leamt in Class XI.
Please check the practical component-book ~ Progress in Computer
Science with Python ond fill it there in PriP 1.3 under Chapter 1 alter
Practically doing i! on the computer.
pooibece,Qhoprer |: PYTMION REVISION TOUR
www.worldvideweb.com
Ler Us REVISE
a
*
+
+
+
eae
‘Stotements are the Instructions given to the computer tu perform ary kind of action.
Python statements can be on one of these types = empty stotement, single statement and compound statment,
A compound statement represents 0 group of statements executed us d unit
Every compound stviemert of Python has a header om an indented boxy below the header. Some examples of
compound stotements ore ; functions, i staterient, while statement etc.
Pytton provides one selection statement if m many forms — if-else and if-elifnetse,
The statements that allow a set of instructions to be performed repeatedly are iteration statements,
Python provides two looping constructs - for and while. The for laop Is a counting loop and while ts @ conditional
loop.
The while loop Isa crtry-currrolted loop as thas a comirot over entry tn ihe loop 11 the form of text condition,
Loops in Python can have else clause too. The else clause of a loop is executed! in the end a the Joop only when
loop tcrminaies normally.
The break statement con terminate a loop immediately end the control posses over to the statement following the
sfatement containing breok
In nested loops, o break statement terminates the very loop it appears tn.
The continue statement ubundons the current iteration of th’ oon by skipping over the rest of the staiements in the
Foop-boxty. Ie immediately transfers conirol to the beginning of the new iteration of the loop.
Solved Problems
a
What is the difference betieven a kevicwnd aint an identifier ?
Solution. Keyword is. special word that has special meaning and purpose. K
ywordsare reserved
and are a few. For example, if, oli, else ete. are keywords,
Lentifier is the user-defined ven toa part of a program vis, variable, object, function ete.
Mentifiers are not weserved. These are defined by the user bul they can have letters, digits and a
symbol underscore. They must begin with cither a letter ar underscore. For instance, chk, chess, Iria
ele. are identifiers in Python
What ave fiteruts in Python ? How many tapes of titerals are allenced int Python 2
Solution Literals mean constants fe, the data items that never change their value during a program
run, Python allows fire types of literals :
(String literals (ii) Numeric literats
(ii?) Boolean literals (i) Special Literal Nene
(#) Literal Collections like tuples, lists ete,
‘How many toays are there in Python to represent an integer literal ?
Solution. Python allows three types of integer literals =
(2) Decimal (base 10) integer literals
(b) Octal (base 8) integer literals
(©) Hexadecimal (base 16) integer literals6 The following cove is not
you pinpoint the problem
COMPUTER SCIENCE Wart Prion _ 9
le) Decimal Ineger Uterals An integer literal consoling of @ sequence of digits i taken tg 4,
decimal integer literal untess it begins with O (digit zero)
For instance, 12, 41, +97, ~17 are decimal integer literals.
fi ing with 0 (digit zero) is taken to be an oxta)
Literals. A sequence of digits starting 0) ta :
Inepa.he ieee decimal integer 8 will be written a5 OL0 as octal integer. @ =10,) and decimal
integer 12 will be wrilten as O14 as octal integer (129 = 144)
s preceded by Or oF OX is taken to be an
(©) Hexadecimal Integer Literals. A sequence of d
hexadecimal integer. ;
For mstance, decimal 12 will be written as. OXC as hexadecimal integer.
‘Thus number 12 will be written either as 12 (as decimal), O14 (as octal) and OXC (as hexadecimal,
A How many types of strings are supported in Python ?
Solution. Python allows two string types +
(Single tine Strings String;s that are terminated in single line
(i) Multtine Strings Strings storing multiple lines of text.
5. What is None literal in Python ?
Solution. Python has one special literal called None.
The None literal is used to indicate something that has not yet been created It is a legal empty
value in Python.
ing desired output, We want to input value as 20and obtain output as 40, Could
Murber = input( “Enter Number” )
Doublethetiurber » Number * 2
Print (DoubleThetiumber)
* Solution. The problem is that inpui( ) returns value as string, so the input value 20 is returned as
string ‘20' and not as integer 20. So the Output is 2020 in place of required output do.
Also Print is not legal statement of Python ; it should be Print
7. Why is following code giving errors ?
name = "Rehman*
print(*Greetangs 111")
Print("Hello", name)
Print ("How do you do 2")
Solution. The problem with above code is inconsistent indentation. In Python, we cannot indent a
Statement unless itis inside a suite and we eon indent only as much as required,
Thas, corrected code will be
name = "Rehman"
Print("Greetings 111+)
print (Hello", name)
Print (“How do you do ?") .
peesChopter 1: PYTHON FIMSION TOUR
&
10.
2
13.
“a
What are data types ? What are Python's buslt-in core dala types ?
Solution, The real life data is of many types. Sa to represent various types of real-life data,
programming languages provide ways are! facilities to handle these, which are known as data types.
Python's built-in core data types belong to:
© Numbers (integer, floating-puint, complex numbers, Booleans)
String List
© Tuple Dictionary
Which data types of Pythen handle Numbers ?
Solution Python provides following data {ype> of handle numbers (version 3.x)
(i) Plain integers (i) Long integers.
(i) Bootean (ix) Floating-point numbers
(©) Complex numbers
Why is Roslar considerad a subtype of integers ?
Solution. Boolean values True and False internally map to integers 1 and 0. That is, internally
True is considered equal ta 1 and False as equal to 0 (zero). When 1 and 0 are converted to
Boolean through bel) function, they return Truc and False, That is why Booleans are treated as
a sublype of integers.
What is the role uf comments anal mdentation in a
scram ?
Solution. Comments prc
terprel
format
ide explanatory notes to the readers of the program. Compiler or
ignores the comments but they are useful (or specifying additional descriptive
1 regarding, the code and logie of the program
Indentation makes the progtam more readable and presentable. Its main role is to highlight nesting,
of groups of control statements.
What is a statement ? W
is the significance of an emply statement 2
Solution. A statement 1s an instruction given to the computer to perform any hind of action.
An empty statement is usetul in situations where the code requires a statement but logic does not. To
fill these two requirements simultaneously, empty statement is used
Python offers pass statement as an empty statement,
Jf you are asked to tate! the Python lovps as determinable or non determinate, sehich label teould you give to
awhich loop? Justify your answer
Solution. The “for loop’ can be labelled as deter
ble Loup as number of its iterations can be
determined beforehar
Way the size of the sequence, it is aperating upon.
The ‘while loop’ can be labelled as nonedeterninable loop, as its number of iterations canno! be
determined beforehand. Its iterations depend upon the result of a test-condition, which cannot be
determined beforehand
There are tww types of else clauses in Python What are these two types of else elouses ?
Solution. The two types of Python else clauses are +
(2) else in an if statement (i) else in a loop statement
The else clause of an if statement is executed when the condition of the if statement results into false.
The else clause of a Inep is executed when the loop is terminating normally ie, when its
test-condition has gone filse for a while loop or when the for loop has executed for the last value
in sequence.1S. Write a program that asks the user
and sevmds tt contains,
Solution.
COMPUTER SCHICK WI Fry
a
inp mur of econ he express iN of ray ming
get the number of seconds froatheuser
numseconds « input ("Enter nunber of seconds")
nunseconds_int = int (nurseconds)
extract the number of minutes using integer division
nunminutes = nuaseconds_int//60
extract the number of seconds remaining since the last minute using the modulo
resainingseconds « nuaseconds_int X 60
print(‘ainute:
print (‘seconds
', numminutes)
rerainingseconds)
16 Write @ prygram that repeatedly asks from users some numtvrs until string ‘done’ is typed. The program —
should print the sum vf all numbers entered.
#tnknown Humber of Numbers to Sum
Solution.
total =o
5 = input (‘Enter a number or “gone
wiles l= "done :
rum = int(s)
total = total + nun
5 = input(Enter a number or “done™: *)
Print(‘The sum of entered numbers is’, total)
12. Write a program to print a square matical
Solution.
for row in
for col
a Se STG
2 4 6 8
306 9
4 8 2
5 Ww 15)
6 2 18 om
7 wo 2
6 6 a 2
ST SaeIB E736.
range(1, 10):
in range(1, 10
Prod = row * col
If prod «18:
Print(’', prod,’ *, end='')
else:
print()
print(prod, '', end='
1 table as shorn betoie +
5 6 7 “TaD
wo 2 MW wag
Boo oa
Mw RR %
HY 3 M45
%® RR a 54
S 2 49 me OG
4856 7
This adds a space if the nuther is single digit-
www,worldvideweb.com
Python .
Revision Tour-Il_ =
22 Suings in Python
23° Lists in Python
24 Tuples in Python
25. Dictionaries in Python
26 Sorung Techniques
sittin ‘ " ;
Qu
INTRODUCTION
The purpose of Revision Tour chapters is to brush up all the concepts you have leamt in class XI.
The previous chapter ~ Python Revision Tour | ~ covered basic concepts like : Python basics,
Data handling, and control flow statements. This chapter is going to help you recall and brush
up concepls like Strings, Lists, Tuples and Dictionaries.
22. STRINGS IN PYTHON
Strings in Python are stored as individual characters in contiguous locations, with two-way
index for each location. Consider following figure (Fig. 2.1).
[Fowmtinieiro> oy 2 9 4 5
rare|p [y|t [Hjoln
6-54
Figure 2.1 Suucture of a Fython String.
awe ialCOMED LANCE IH Pe,
From big, 24 you can infer that :
ettrings in Python are stored by storing, each character separately in
locations.
© The characters of the strings ate given two-way indices +
50,9, 2s oe thzeed in thee Joricard direction and
1, 2,3, ... site in the backward direction.
‘Thus, yon can acerss any character as ", line 1, in
nane[0) ="¢
TypeError: ‘str’ object does not support ites assignzent
2.2.2 Traversing o String
Traversing, refers to iterating through the elements of a string, one character at a time.
To traverse through a string, you can write a loop like :
code = "Powerful"
vend=* *)
‘The above code will print :
P~O~wW~e~r~feu~1~
2.2.3 String Operalors
In this section, you'll be learning to work with varior
strings in multiple ways. us operators that can be used to manipula!Choos 2 PYTHON HEMIHION TOUR.
aN
1. String Concetenation Operator +
The + operator creates a new string by Joining the two operand strings, eg,
“power” + "fue
will result into
‘powerful!
I
Cautions
The * operator has to have both operands of the same type cither of number types (for
addition) or of string types (Cor multiplication). t cannot work with ene operand as string and
one as a number,
2. String Replication Operator *
Touse a* operator with Strings, you need two types of operands —a string and a number, ie, as
number string of string * number, where string operand tells the string to be replicated and
umber operand te
Ils the number of times, tis to be repeated; Python will create a new string
thal is a number of repetitions ofthe string operand,
For example,
3° Hain
will retum
Yatnaniayt
Caution!
The * operator has to either have both o
tring type and one number type (for re
types.
perands of the number types (for multiplication) or one
plication). It cannot work with both operands of string
3. Membership Operators
There are fw membership operators for strings (in fact, forall sequence types) These are in and
not in.
in returns True if a character or a substring exists in the given string ; False otherwise
not in returns Tre ifa character or a substring doesnot exist in the given string; False otherwise
Both membership operators (\when used with strings), require that both operands used with
them are of string type, ie.,
in estring>
not in
Now, let's have a look at some examples :
>>>"a" in “heya”
True
>>> "Jap" in “heya”
False| a
>>>" Jap" An “Japan
False
>>> Sub “help”
False
>>> sub2 not In string
True
>>> string «*helping hand
>>> sub2 = HELP
>>> sub in string
True
>>> sub2 dn string
False
>>> sub not in string
False
4, Comparison Operators
Python's standard comparison operators ic, all relational operators (< <=,
COMPUTER SCIENCE WiTH Pron
2.25, Ie,
apply
{0 strings also. The comparisons using these operators are based on the ) #returns ASCII value of Passed character
‘The opposite of ord( ) function
the chr() takes the ASCII value
ASCH value.
‘The general syntax of ehr( ) function is :
chr(cints)
is chr), ic, while ordi
in integer form and r
Gives character conn,
# value given as integer
IC) returns the ASCII value of a character,
returns the character corresponding to that
"esponding to passed ASCII
|
|up FANON RWION TOU
Consider these examples :
>»> ord()
6s
>>> ord(ua')
6s
>>> chr(65)
| *
>>> chr(37)
‘a
2.2.4 String Slices
Ay
The term ‘string slice’ refers toa part of the string, where String Shce celers to part of
strings are sliced using a range of indices. That js, for asstring ‘ae. containing tone coo
say name, if we givenamel nim Jwherenand mareintegers RS haces from ne
suing,
and legal indices, Python will turn a slice of the string by
returning the characters falling between indices m and i :
starting at m,1¢ 1,042 ...till m= 1, :
Following figure (Fig, 2.2) shows some string slices using the
string :
helloString ="HelloWor}d” :
ellostedngl6:10) beddostednel6:]
owntes [Te] Tel [Mele] 4 ewes THe] 11 fe]
wes ]O 12:3 4 5 G67 8B 9 10) inser | 1
I T3456
q T
fin tas fiat
pellostring(3:-2)
ewmteen Trfe] | fel [wlele| fe ovate [He]! fe] lel tle
ides [0 1 2:3 4 5 6 7 B 9 10) ieee JO 129 5678 9 10
fint lost fit low
hellosteteg(:5]
Figure 22 String Slicing in Fython,
Interesting Inference
Using the same string slicing technique, you will find that
© for any index 1, s{:n] + s(n] will give you original string s-
This works even for n negative or out of bounds.
Consider the string namely word storing ‘amazing’.
999 word[3:], word [:3]
‘zing’ ‘ana’COMPUTER SCIENCE WITH PYTHON _
** ‘amazing’
po word[:-7)] + word{-73]
‘aeazing
€@ Index out of bounds causes error with strings but slicing 2 String outside the bounds dog
not cause error.
s="Hello* Witt cawe enor because 13 aad
print (ts) indes-out of bounds, for sing “Helio
But if you give
- Ore bit vous the bouts
Sm Wel” a honcho Heli i Sart Ys tad
print (s[4: 8]) iadeves are 0-4)
print (s[5 : 10))
hah as ae cute the bounds
the above will not give any error and print output as =
0 emp sng
i, letter 0 followed by empty string in next line.
2.2.5 String Functions
Python also offers many built-in functions and methods for string manipulation. The string
manipulation methods that are being discussed below can be applied to strings.as per following
syntax:
. ()
For instance, if you have a string namely str= “Rock the World” and you want to find its tength,
you will write the code somewhat like shown below =
>>> str = "Rock the World.”
>99 strsength( ) + th object
see the sng objec is at ond
15
‘method names length
>>> str2= "New World” ly
>> str2,length( )
9
‘you know that following websites and web applications have used Python
f extensively : Instagram, Dropbar, Google, Netflix, Spoti i
a, “i ‘oogle, Netflix, Spatify, Quora, Reddit, Facebook,Eo
Chopler 2.1 PYTHON REVISION TOUR
Tonle 24 Python's built-in string manipulation methods.
ateing.copitalize()
Retums a copy of the string with is first character capitalized.
Example
>o9" 4 love ay Indiv capitalize()
T love ny India
string. find (sub[,
start[, end]])
string.4salnua()
string.4salpha()
string.isdigit()
string.1sspace()
Returns the lowest index kn the string where the substring sub Is found within the
slice range of start and end. Returns «1 if sub is not found,
Example
>>> string = St goes as = ringa ringa roses’
>>> sub = ‘ring?
999 string. find(sub, 15, 22)
a
>>> string. find(sub, 15, 25)
9
Retums True if the characters in the string are alphanumeric (alphabets or
numbers) and there is at least one character, False otherwise.
Returns True if all characters in the string are alphabetic and there is at least one
character, False otherwise.
Retumms True if all the characters in the string are digits. There must be at least
one digit, otherwise it retums False.
Examples
>> stedng = "abea23"
22) string? « ‘held
>>> stedng3 = "12345"
>>> strings «* *
>>> string. tsalnum()
True
>>> string2. fsalnun()
True
>>> string3. 1salnun()
True
>>> strings. dsalnua()
False
99 steing.isalpha()
alse
>>> string2.4salpha()
True
>>> string3.1salpha()
False
>>> strings, tsalpha()
False
>>> string. Asdigit()
False
>> string2. Asdigit()
False
>>> string3.tsdigit()
False
>>> strings. isdigit()
True
Retums True if there are only whitespace characters in the string. There must be
at least one character. It retums False otherwise.
| Example
poo stedng =
pop string? =
>o> string. ésspace()
True
pop string2.tsspace()
False
# stores three spaces
# an enpty string.
| string. tslowee()
COMPUTER SCIENCE WITH Peto, re,
| Retums True if all cased characters in the string are lowercase. Th
least one cased character. It returns False otherwise.
Tests whether all ase characters in the string are uppercase and tequles thay
Mere MUM be gp
string.rstrip([chars})
If used without any argument, it removes the leading whitespaces.
One can use the optional chars argument to specify a set of characters tobe removed.
The chars argument is not a prefix; rather, all combinations of its values (all
possible substrings from the given string argument chars) ae stripped when they
Tead the string.
ing: tsuppee() | There be atleast one cased character: Retiree Teac oecat se otherwise
Examples
doo string » hello >>> string = “HELLOT
>>> string = "THERE >>> string? ="There*
D>» string3 = ‘Goldy >>> string) = "polay”
39> steding.Sslower() >>> string. 4supper()
True True
99> string2.dslower() boo string2.Asupper()
False False
>>> string3.dslower() boo string3.dsupper()
False False
o> strings. Ssupper()
True
>>> steingS.Asupper()
i False
string.lower() Retums a copy of the string converted to lowercase. Example
>> string. 1ower() string = "HELLO"
‘helio ee
string.upper() Retums a copy of the string converted to uppercase. Example
>>> string.upper() Esteing = “hellow
Mug 7 -
string-Astesp({chars}) | Returns a copy of the string with leading characters removed.
Relurns a copy of the string with trailing characters remo
If used without any argument, it removes the leading, whitespaces.
The chars argument is a string specifying the set of characters to be removed
‘The chars argument isnot a suffix rather, ll combinations ofits values are stripped
Examples
> string? = there ane er
“There sratched ier of thse fume
992 strdng2.Istrip( ‘The ) €——— removal from the left ef the ating
ine ‘The found. heace romana
>>> “sareganapadhanisa*.Istrip( "tears" )
“gemapadhanisa’
>>> strdng2.rstrip(‘care’)
™!
>>> “sareganapadhanisa".rstrip( "tears" )
‘saregenapadhant’Choper 2 1 PYTHON REVISION TOUR.
R
Program that reads « line and prints {ts staitsties lhe :
Number of uppercase letters :
Number of lotwercase letters:
Number of alphabets :
Nunter of digits:
Line = input( "Enter a Line :")
Jowercount = uppercount = @
digitcount = alphacount = 0
fora inline :
if a.dslower() :
lowercount += 1
elif a.isupper() :
uppercount += 1
elif a.isdigit() :
digitcount += 1
if a.dsalpha() :
alphacount +=1
print ("Nunber of uppercase letters :" , uppercount)
print ("Nunber of lowercase letters :", lowercount)
print (‘Wunber of alphabets :", alphacount)
print ("Nunber of digits :", digitcount)
Enter a line : Hello 123, z1ppy zippy zap
Number of uppercase letters : 7
| Number of lowercase letters : 11
| Number of alphabets : 18
;
Number of digits : 3
23° LISTS IN PYTHON
A list is a standard data type of Python that can store a sequence of values belonging to any
type. The Lists are depicted through square brackets, ¢.g,, following are some lists in Python :
oO #list with nomenber, empty List
(1,2, 3] #list of integers
(1, 2.5, 3.7, 9] #ist of numbers (integers and floating point)
Ca, "B,'e] # list of characters
(a, 1,'b, 3.5, 'zero’) # List of mixed value types
Cone’, ‘Two’, ‘Three’] # list of strings
eit ist is one of
Lists are mutable (i, modifiable) i¢., you can change elements of alist in, Pe iperdate types
the two mutable types of Python — Lists and Dictionaries are mutable types zall o
of Python are immutable.COMPUTER SCIENCE WITH PYTHON
2.3.1 Creoling Lisis
To create a list, put a number of expressions, separated by commas in square brackets, That,
to create a list you can write in the form given below :
leo
Le [value, «J
This construct is known as a list display construct.
Creating Empty List
‘The empty list is []. You can also create an empty list as :
Le list() art will generate an empty Mist and name that Listas,
Creating Lists from Existing Sequences
You can also use the built-in list type object to create lists from sequences as per the syntax
given below
Le Mst(esequence>)
where >> ML = List (hel lo’) tcreating st from string
= | pool
(he, 1
parte (Wye, ts ¥)
>o> 12 e Lst(t) creating 14st from tuple
>>> 12
(v,'e,'r,
y)
Creating List from Keyboard Input
You canuse this method of creating lists of single characters or single digits via keyboard input.
Consider the code below :
>>> 11 = List( input (‘Enter list elements:'))
Enter list elements: 234567
oo
(2,'%,4,'5,'6,7]
Notice, this way the datatype ofall characters entered is string even though we entered digits,
To enter a list of integers through keyboard, you can use the method given below.
Most commonly used method to input lists is evallinput( ))! as shown below :
st = eval (Input (“Enter List to be added :"))
print ("List you entered :*, list)
when you execute it, it will work somewhat like :
Enter list tobe added : (67, 78, 46, 23]
List you entered : [67, 78, 46, 23]
—
Bint
Flease nate, sometimes (notalways) eval() dors not work in Python shell. At that tine, youcan run itthrough ascript too.2.3.2 Lists vs. Strings ==
Lists and strings have lots In common yet key differences too. This section is going to
summarize the similarities and differences between lists and strings.
2.3.2A Similority between Lists and Strings
Lists are similar to strings in following ways :
© Length Function fen(L) returns the number of items (count) in the list L
© Indexing and Slicing
Ui) retums the item at index i (the first item has index 0), and
Uj] returns a new list, containing the objects between iand j.
© Membership operators
Both ‘in’ and ‘nat in’ operators work on Lists just like they work for other
sequences such as strings. (Operator in tells if an element is present in the
list oF not, and not in docs the opposite.)
© Concatenation and Rept
tion operators + and *
ie * operator adds one list to the end of another. The * operator repeats a
ist.
© Accessing Individual Elements
Like strings, the individual clements of a list are accessed through their
indexes.
Consider following examples :
>>> vowels « ['at, 'e’, "
>>> vowels[0]
y
>> vowels [4]
wu
>>> vowels[-1]
‘u
>>> vowels[-5]
‘a
V's")
2.3.2B Difference between Lists and Strings
The lists and strings are different from one another in following ways :
© Storage Lists are stored in memory exactly like strings, except that because some of
their objects are larger than others, they store a reference at each index
instead of single character as in strings.
© Mutability Strings are not mutable, while lists are. You cannot change individual
elements of a string in place, but Lists allow you to do so. That is,
following statement is fully valid for Lists (Ihough not for strings) :
L[1] = celenent>COMPUTER SCIENCE VOTH PYTHOR,
ed above and havea Took at following code
sider the same vowels iStCTE
For example, consi
a>>vowels[o] + +
>> vowels ch ef
pay e Te a Los arn
Aye Te rated = onan Ls ar
aoovowels[-4] wow
99> vowels
pase, tM
2.3.3 list Operotions
Im this section, we shall talk about most common list
operations, briefly.
(BA Traversing © List
Traversing a list means accessing and
ta traverse oF loop over the items in
for cites? An Istz = (6, 12, 20]
oo Isth + 1st2
1, 4, 9, 6, 12, 20)
The + operator when used swith lists requires that both the operands must be of list types.
2.3.3C Repeating or Replicating Lists
Like strings, you can use * ope i
strings. 9 erator to replicate a list s
he sre Jou tn se. ope plicate a list specified number of times, 84
poo 1st 3
11, 4,9,1,4,9,1, 4,9)
Like stri y is ‘it
strings, you can only use an integer with a * operator when trying to replicate a list.Craper 2 PITHON BELO TOU 8 a
2.3.30 Sheng the Lists
List shers, ike string shers are the sub part of a list extracted out. You can use indees of list
elements to create list slices as per following format :
seq* U[start:stop]
Consider the following example :
>>> Ist =[10, 12, 14, 28, 22, 24, 30, 32, 34]
Comey wrper Leet wey beet
>>> seqe Ist (3: -3] he wat ef te bat bat Pn
>93 509 peers remem for bat faang
fererge 3 emwards <0
[20, 22, 24)
>>> Ist #[10, 22, 24, 20, 22, 24, 38, 32, 34)
>> Est [3:39]
(20, 22, 24, 38, 32, 34)
>>> st [18:7] <= —_——
Ue, 12, 28, 20, 22, 24, 32]
Lists also support slice steps too, That is, if you want to extract. not consecutive but every other
element of the list thete is a way out - the slice stops. The slice steps are used as per following
format
seq L[ start: step:step]
mnsidet some examples to understand this.
poo dnt
(28, 32, 24, 28, 22, 24, 38, 32, 34) bactiale very Sal homens. (4,
ip T clemens om Kerewen Ook
roo Ust[@: 38:2) EO remabeog in shee
(38, 24, 22, 32, 38)
rend Be we les
(24, 24, 38) Hod climes i teteere
Using Slices for
You ¢
Following eva
Moddic
1 use shoes to overwrni
ne of more list elements with one or more other elements.
will make it clear to you
o> Le (Tone, “tao”, “THREC] aaa
vor tfe:2] = [@, 1
steel } ‘Uke strings, in Int sheet you can
rove (Dee start and stop beyord tents
[@, 1, Meee] of bet and won't roine
Incestrror, rather wil return
>>> Le[Tone", "two", “THREE™] the elements tating between
>>> tf@:2) #72" Reeceeee bowsddaries.
dook
["a", THREE)50 COMPUTER SCIENCE Witt, orton,
Pat
2.3.4. List Monipulation ,
You can perform various operations on lists ik
ippending, updating, deleting ete,
nding Elements to o List / :
“re You can also aud itemsto an existing sequence. The append() method adds single item oy
end of the list. It can be done as per following format :
L.append(iten)
Consider some examples :
29> Ist = [10, 12, 14]
>> IstL.append(16) |
>o> Asti The element cif ws arpurent to appeal) is
{29, 12,246) Asie the ead of esi nt
Updoting Elements to o List
To update or change an element of the list in place, you just have to assign new value to the
element's index in list as per syntax :
7
4 [index] = «new value>
Consider following example :
22> Ist = [19, 12, 14, 16] |
999 Ustd[2] = 24 Stzterent ating on element (al element =
hairy sider 2) tela,
doo Asta Display the ttt see the upstate Hi
Lae, 22, 24, 16) «.
Deleting Elements from a List
You can also remove items from lists. The del statement can be
used lo remove an individual
item, or to remove all items identified by a slice.
Its to be used as per syntax given below :
del List [ cindexs)
# to renove elenent at index
del List [ : estop> ]
# torenove elements in list slice
>>> del Ist(10:15) <—————__
Daler at elements between indezes 10 10.15 in tat
>>> Ist
framely bt Compare the result display bone
(1, 2, 3, 4,5, 6,7, 8, 9, 16, 17, 18, 19, 20)
If you use del only e.g, del Ist, it will delete
After this, no object by the name Ist would be existing,
You can also use pep() method to remove single element, nat list slices.
The popt ) method is covered in a later section, List Functions.
all the elements and the list object too,| 2: PYTHON REVISION TOUR
| 3.8 Making Tre Copy of a tis
Assignment with an assignment operator (=) on lists docs not make a copy. Instcad, assignment
} makes the two variables point fo the one list in memory (called shallow copy).
colors = ['red, ‘blue’, ‘green’] color ——e [ted [ee Taree] |
lwo
becolors ##Does not copy the list colon ——e [Fed | ‘bw | oreo
. Pp bao
So, if you make changes in one list, the other list will also report those changes because these
two listenames are labels referring to same list because '=" copied the reference not the actual
list.
To make b true copy of list colors ic, an toto —- | Rrot ere
independent list identical tolist colors you mls : 7
should create copy of list as follows : o—~ [Tet] tow | reer
Vv wo
belist(colors) «
Now colors and b are separate lists (deep copy)
2.3.6 List Functions
Python also offers many buill-in functions and methods for list manipulation, These can be
applied to list as per following syntax :
.)
~ Takes exactly one element and returns no value
For example, to add a nevw item “yellow” to a list containing colours, you may write:
‘red, ‘greert, ‘blue')
>>> colours .append('yellow)
See the trp ade teen ofthe it
>>> colours. —_—
[red ‘green’, ‘blue’, ‘yellow]
>>> colours =
The appeni( ) does not return the new list, just modifies the originalPo
. The extend method -
° “Tecate method isalso used foradding multiple clements (given in the form of alist) tg
‘The extend( ) function works as per following format :
| %
| i COMPUTER SCIENCE WATH Fray,
List .extend( )
= Takes exactly one clement (a ist type) and returns no ealue
Thats extend() takes alist as an argument and appends all of the element ofthe argument
to the list object on which extend( ) is applied. Consider the following example =
potte [a B,C]
moezeld,'e]
tent the E11 by bdo all
ta cemerit of t2
>>> th.extend(t2)
See the oe of a 1 re
— si te of at
(3, se 7G, 'e]
2»
02 on cha
tee Ge we ew
Difference between append ) and extend( ) methods
While append ) function adds one element to a list, extend{ ) can add multiple elements froma’
ist supplied to it as argument.
4, The insert method
“The insert( ) function inserts an item al a given position. It is used as per following syntax :
List.insert( , )
= Takes too arguments anu relurns no value
= The first argument is the index of the element before which the second argument.
- > tl.insert(2, ‘i') inset element ‘i’ at index 2.
2>>t1
[2
YY se cheent insert at index 2
5. The pop method
The pop() is used fo remove the item from the list. It is used as per following syntax :
Ust.pop()
‘# >> tl
(Epa u)
292 ele = £1.Pop(8) <——__ mon element at inde Oe. int
>>> elen element and stor i in elet
2B sy") ——— tafe semoring fat cement
>>> ele2=t1.pop()
por elee No inter aescified, it will remove
‘uv the bast element
Pg] *
The pop{ ) method raises an exception (runtime error) ifthe list is already empty.
6. The remove method
The Femovel ) method removes the first occurrence of given item from the list Itis used as per
following format :
List. remove ( )
~ Takes one essential argument and does not retum anything
The remove( ) will report an errorif thereis no such item in the liet. Consider some examples :
dsp)
>>> tle [ay 'e, "tp, 'q,
>>> UL. renove (‘a’)
doth
Le, tp, ‘a,
>>> tl renove(‘p')
>otL a Hint occurence of ‘pis temovea fo thelist
Ce, L'a, ad, pi)
7. The clear method
This method removes all the items from the list and the list becomes empty list after this
function. This function retums Nothing. It is used as per following format.
List.clear( )
For instance, if you have a list L1 as
>>> LL = (2,3, 4,5)
will remone all the tor 44.
>>> LA clear( ) ¢———— it mill remove all the ters from li 11
e——— Now the LI is en emp list
Unlike del statement, clear{ ) removes only the elements and not the list element.
After clear{ ), the list object still exists as an empty list.
Fint occurrence of a" is removed from the lit
ey. COMPUTER SCIENCE wing
8. The count method
This function retums the count of the item that you passed as argument. Ifthe given
tn the hist, it retums zero,
Itis used as per following format :
List.count(citem )
For instance. for alist L1 = [13, 18, 20, 10, 18, 23)
PRED a Faery ot nth Be
>>) L1.count (28)
8 No icon with value 26 onthe Lat, hence at rerumed O (cero)
9. The reverse method
The reersef ) reverses the items of the list. This is done “in place”, f.c., it does not create ane
list.
The syntax to use reverse method is:
List.reverse()
~ Tales no argument, retums no list; reverses the Uist ‘in place’ and does not return anything,
For example,
5 potlele, Ud, "a, a, '¢])
>>> the reverse()
aot The road lit
(e,'0, aq, '
10. The sort method
The sort( ) function sorts the items of the list, by default in increasing order. This is done
place’, does not ervate a new list.
Its used as per following syntax :
Ust.sert()
For example,
>ootle[le, 4,
>>> tl sort()
299 tL 4— Somes in defo ascending onder
Us, 'e, ‘a
‘a. '9)
Like reverse ) sort() also performs its function and d
loes not return anything.
To sort a list in decreasing order using sort( ),
You can write :
22> LASt.sort(reverse = True)iepee 2 + FINON REVSION TOUR 55
24° TUPLES IN PYTHON
no
The Tuples are depicted through parentheses é¢., round brackets, ¢g., following are some
tuples in Python :
oO * tuplewith nomenber, enpty tuple
m) tuple with one menber
(1,2,3) # tuple of integers
a2 " tuple of nunbers (integers and floating point)
ca, # tuple of characters
(31,0, 3.5, 20rd) tuple of mixed value types
(One', "Two', ‘Three'y # tuple of strings
| Tuples are immutable sequences ic, you cannot change clements of a tuple in place.
|
2.4.1 Creating Tuples 4
v To create 3 tuple, put a number of expressions, separated by commas in Parentheses. That is, to
create a tuple you can write in the form given below :
| THO
T= (value, ...)
This construct is known as a tuple display construct
Creating Empty Tuple
The empty tuple is (). You can also create an empty tuple as
T+ tuple()
Creating Single Element Tuple”
Making a tuple witha single clement is tricky because if you just givea single element in round
brackets, Python considers it a value only, ¢g.,
>>> t= (1)
pot
(1) 03 ret swine pws,
3 favee tae a pe an
To construct a tuple with one element just add a comma after the single element as shown
below :
To create w one-elrnent tuple, make
300 8g eo al coro atthe ed
soot
@) Now ¢ sores tuple, not ineger
))+—————
Creating Tuples from Existing Sequences
You can also use the built-in tuple type object (tuple() ) to create tuples from sequences as per
the syntax given below :
T= tuple() oo
Where can be any kind of sequence object including strings, lists and tuples,Consider following examples :
>>> t1 = tupleChello)
aooth
(ni, e190)
p>>Le [Wy "ey ‘este ¥)
>>> tz tuple(t)
pooez
o,
wv, t,y)
Crecting Tuple from Keyboord Input
You can use this method of creating tuples of single chara
input.
Consider the code below :
COMPUTER SCIENCE WITH Pron,
acreating tuple froaa string
a creating tuple froma list
ters or single digits via keyboard
t1 = tuple(input (‘Enter tuple elenents:"))
Enter tuple elenents : 234567
aot
(2, °3, 4,546, 7)
But most commonly used methed to input tuples is eval(input( )) as shown below =
tuple = eval (input ("Enter tuple to be added:"))
print("Tuple you entered :*, tuple)
when you execut
Enter tuple to be added: (2, 4, “
it will work somewhat like :
» N9KIL, “3, 41)
tuple youentered = (2, 4, "a", "hSki]") 13, 4])
2.4.2 Tuples vs. Lists
Tuples and hits are very
y similar yet different. This section is going to talk about the same.
2.4.2A Similority between Tuples and Lists
Tuples are similar to lists in following ways :
© Indexing and Slicing
© Length Function len(T) returns the number of items (count) in the tuple T.
TIi] returns the item at index i (the first item has index 0), and T[i:{] returns a new
tuple, containing the objects between i and j.
© Membership operators
Both ‘in’ and ‘not in’ operators work on Tuples also. That is, in tells if an element is
present in the tuple or not and nat in does the opposit
© Concatenation aid Replication operators + and *
The + operator adds one tuple to the end of another. The * operator repeats a tuple.hopter 2 PYTHON REVISION TOUR
7
@ Accessing Individual Eloments
The individual elements of a tuple are accessed
square brackets. Consider the following exampl
>>> vowels = ('a',‘e', ‘I', 'o!, ‘u)
>>> vowels [4]
w
>>> vowels[- 1)
u
through their indexes given in
2.4.28 Difference between Tuples ond Lists
Tuples are not mutable, while lists are.
You cannot change indiv
but lists
allow you to doso Thatis, following statement is fully v
If we have a list Land a tuple T, then
UL) = element
ual elements of a tuple in place,
‘lid for lists (BUT not for tuples).
tis valid
is VALID for Lists. BUT
TUL] = element 4s invalid
is INVALID for tuples as you cannot perform item-assignment in immutable types.
2.4.3 Tuple Operations
In this section, we shall talk about most common tuple operations, briefly.
2.4.38 Traversing o Tuple
Traversing a tuple means accessing and processing each element of it. The for loop makes it easy
to traverse or loop over th
for citen> in >otpli= (1, 3, 5)
>>> tpl2= (6, 7, 8)
doo tpl + tpl2
(2,3, 5, 6 7, 8)58 COMPUTER SCIRMCE WAT PYTHON _
ORTANT oo. cccceecteecseeeeee
Sometimes you need to concatenate a tuple (say 1p!) with another tuple containing only gait
clement. In that case, if you write statement like
4
>>> tpl + (3)
Python will return an error like :
Typefrror : can only concatenate tuple (not sgnt*) totuple 1
as single value not as tuple. That jy!
© The reason for above error isa single walue in () is treated we
| expressions @) and (a!) are integer and string respectively but (3,)and (/a', Jare single element!
i
tuples. Thus, following expression won't give any error:
>>> tele (3,)
2.4.3C Repeating or Replicating Tuples
Like strings and lists, you can use * operator toreplicate a tuple: specified number of times, e.g,
>>> tpl #3
(1,.3,5, 1,3, 5,4, 345)
ce an integer with a * operator when trying to replicate a
Like strings and lists, you can only
tuple.
2.4.3D Slicing the Tuples
extracted out. You ean use
Tuple slices, like listslices or string slices are the sub part of the tuple
indenes of tupl luple slices as per following format:
seq = T[start:stop)
ments to creal
Recall that index on last limit is not included in the tuple slice, Consider the follow ing example:
yoo tp = (10, 12, 14, 26, 22, 24, 30, 32, 34)
po» seqe tpl [3:-3]
>9> seq
(20, 22, 24)
you want to extract, not consecutive but every other element of the tuple, there isa way out -
the slice steps. The slice steps are used as per following format:
seq T[start:stop:step)
Consider some examples to understand this.
2>> tpl
(10, 12, 14, 20, 22, 24, 38, 32, 34)
Include every 2nd element, Le ahip W clemers in
>>» tpl[0: 10: 2) oe erwwen Che ering tuple sce
(20, 14, 22, 30, 34)
Inctide every Ind element. je,
>ootpl2 20: 3Je
enka sip 2 dement in between
poops 3] Nitta ands pine Oy epi given 093
That i, from the entire rape, pick every
Ge, 28, 39)
d Sed element for the tuple2: PYTHON REVISION TOUR 59
Ast Unpacking Tuples
Creating a tuple from a set of values is called packing and its reverse, ie, creating individual
values from a tuple’s elements is called unpacking,
Unpacking is done as per syntax :
evariablel>, , , _«t
where the number of variables in the left side of assignment must match the number of
elements in the tuple.
For example, if we have a tuple as:
te (12,8, 8)
The length of above tuple tis4 as there are four clementsinit, Now lounpack it, we can write:
WKY Tet
print(w,
The output will be :
1-2-A-B
24.4 Tuple Fun:
1, The len{ ) method
This method retums length of the tuple, é¢, the count of elements in the tuple.
Syntax: — len()
3 ond Methods
>22 employee = (‘John’, 10000, 24, ‘Sales')
>>> len(erployee)
8 treet returns the court of elements in the tape
2. The mox{ ) method
This method returns the element from the tuple having maximum value.
Syntax: rax()
doo tpl « (10, 12, 14, 20, 22, 24, 30, 32, 34)
>>>max(tpl)
ca
Maximram value from tuple tpl is returned
3. The min{ ) method
This method retums the clement from the tuple having minimum value,
ha
>o>tpl = (10, 12, 14, 20, 22, 24, 30, 32, 34) Meee
>>omin(tpl) the elements of tuple should be
20 =~ fasion vole for tpl tp reamed lanene,
Syntax: nin()60 COMPUTER SCIENCE WITH PYTHON ~ y
4.The index{ ) method
It retumss the index of an existing element of a tuple.
Syntax: . index (
- >>t1=[3, 4, 5, 6.0)
>>> tL. index(5)
2
But if the given item docs not exist in tuple, it raises ValueError exception.
5. The count } function
The count( ) method retums the count of a member element/object in a given sequenc
. (lis/tuple).
Syntax: — .count (