Textbook for Class XII
«Programming & Computational Thinking
«Computer Networks
+ Data Management (SQL, Django)
+Society,LawandEthics
~ SUMITA ARORA
" DHANPAT RAI & Co.COMPUTER SCIENCE
DHANPAT RAT & CO. (Pvt.) Ltc
EDUCATIONAL & TECHNICAL PUBLISHERGAGAN KAPUR
(P) Ltd., Delhi
J, Delhi-1 10006
Published by :
Dhanpat Rai & Co.
Soles Ofice : 1710, Nai Sora
Phone : 2325 0251 ,
Regd. Office : 4576/15, Agarwal Root
-1 10002
eryo Ganj, New Delhi-1 :
hae + 2324 7736, 37, 38, dhanpatrai@[Link]
© Sumita Arora
Si All Trademarks Acknowledged
0 Disclaimer
Every effort has been made to avoid errors or omissions in this publication.
In spite of this, some errors might have crept in. Any mistake, error or
discrepancy noted may be brought to our notice which shall be taken care
fin the next edition. It is notified that neither the publisher nor the author
or seller will be responsible for any damage or loss of action to any one, of
any kind, in any manner, therefrom.
rely
Le TeNefe) aNd
EDITIONS: 1997, 1998, 2002, 2004, 2007, 2009, 2010, 2011, 2012, 2017
REPRINT : 2002, 2003, 2004, 2005, 2006, 2009, 2013, 2015, 2016,
EDITION : 2014, 2019 (with Python)
THIRTEENTH EDITION : 2020 (with Python)
PRICE : &.595/- Combined Price (Textbook + Practical book)
Typesetting by : North Delhi Computer Convention, Delhi-1 10009,
[Link]@[Link]
Printed ot : Notraj Offset, DelhiPreface
Moder age technologies are so fast changing that we have to adapt to them in all spheres of life at the
same pace. Education (especially Computer Science subjects) is one such field where we see major
change in the syllabi every now and then.
The subject ‘Computer Science’ (code 083) saw a major curriculum changelin the recent past to
accommodate the changing needs as per the changing technologies. The book in your hands is an
updated and revised edition of the subject “Computer Science” (code 083) class 12pyhich now also
contains objective type questions added to each chapter along with many important minor updations in
the content of the book. - . a
Like earlier edition, this book adheres to the CBSE curriculum for ‘Computer Seience (083) for Class Xi.
Based on the syllabus, the book has been divided into four uri.
Unit 1: Programming and Computational Thinking (PCT=2)
Unit 1 has been divided into nine chapters (chapters 1-9). 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. 2 fs
Unit 2 : Computer Networks (CN)
‘his unit has been divided into two chapters (chapters 10-11). t covers computer networks’ basics such
2s types of networks, cloud technology, oT: wired and wireless networks, client, server networks,
network devices, modulation techniques, collision in wireless networks, IPv4, IPv6, TCP, other protocols
and network tools¢."<)
Unit 3 : Data Management (DM-2)
This unit hasbeen divided into four chapters (chapters 12-15). It covers SQL revision, more on SQL
commarids, developing a minimal web application using Ojango web framework, and Python database
conne ctivity with MySQL databases.
Unit 4 : Society, Law and Et (SLE-2)
This unit has been covered in one chapter (chapter 16). it covers many topics and issues related to
Society, law ang ethics, such as PR, plagiarism, digital rights and licencing, privacy laws and cyber crime,
IT 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
Foundation of programming and other concepts even stronger.
make theoe have shown screenshots of Python shell used ng.
hhapters of the book, we nS
IMPORTANT : In 3 atich _ In[ ] : prompt to take commands. But in text sex mn, We have Biven i
ee mn prompt, which is a standard way of telling that this command is given on Python
commands wi q
“shell prompt.
te a shells execute the code in the same way, though IPython shell is an enhanced shell, used in
All Python
i d other research works. [Link] free to uy
iversities and preferred in data sciences an ou are fr aaa
tho spehal of your choice, but we have installed Python using Anaconda distribution Which
ae maximum libraries along with Python. As Spyder IDE and IPython shell is available as part iy
aibcitie Python distribution and is very easy to use, we have given screenshots of. Spyder Ine and
IPython shell in this book at times.
‘The SiPO app for associated Digital Resources.
“We are launching digital resources along with this book for’
> Explanatory videos/animations/illustrationis
+ Selective Assignment solutions
© Other additional resources
{provide visual support for your learning. To [Link] view this content, you can use the SIPO’app,
downloadable currently from Play Storé (will soon be. available on App Store too),
‘Using the SIPO app, you can scan the QR codes given in the book to play/view the associated digital:
content. ae Ne “te
‘While writing the book, we have tried to Keep the explanation simple with lots of examples, illustrations
and 2\reader-friendly presentation. Like its predecessors, this book contains the summary of topics
Covered in the book:in'the form of ‘Let’Us Revise’ and keyterms compiled under ‘Glossary’. Also,
definitions and important ‘Points have been Presented separately through definition boxes and note
i RE Petes is always scope of improvement. Thus, it is a request to our esteemed
yee dPack, suggestions, opinions etc. for the improv
i thelr fe : : ement of the book. All your
+ fesponses afe whole-heartedly welcome. . :
folate *
: .
atuiary, 2020
5 SUMITA ARORA
Se E-Mail : [Link]@[Link]
follow me at : [Link]/SumitaAroraAcknowledgment
Acknowledgment is the most beautiful page in any project's final pages. More than 2
formality, this appears to me the best opportunity to express my gratitude.
-Mylist can never begin without you, dear GOD. Rather than saying ‘thank you" to you, you
know that I feel like saying ‘I love you’, to you, always. ss
Next on my thanks list are my friends, teachers, studerits, who really showered
constructive feedbacks and suggestions without which this book would ot have been in
present form. ~~ <<
‘Special thanks to my critics who help me bring out the best. ‘Thank You people very, rch jyour
honest opinions are most welcome. | really respect your ‘opinions? | mean it”:
Now it’s time to thank those people who have helped me in tt project. Kush, thank you
for your technical support. Meenu, thank you very much forthe efforts that you put in, in
the production of the book. | can never think of any project without you. God bless you.
Manoj and HariChand, Thank youvery,much for all that you have done.
Jagdish Ji and Gagan Ji, you people are real foundations of the projects done by me.
My projects would never [Link] possible without your faith in me. Thank you very
much. (
Finally, | must say thanks to my family, All know and I repeat it every time that my husband
Sandeep is the réason and real force behind my writing. Thank you Sandeep for yur faith
and above all your unending support in litle-little ways from kitchen to final oredr the
book ; you'have always been by my side to encourage me, support me. ‘Thank you very
much’éKushagra and Mythili, my sweethearts, | love you and thank you for your support.
We always tried not to disturb me whenever | am stuck in something. | feel proud at
inderstanding ways and maturity. God bless you. Love you.
SUMITA ARORA.
E-Mail : [Link]@[Link].
follow me at : [Link]/SumitaAroraUnit Name
ing and Computational Thinking-2
: ivan Sa NCE
5. Practicals A \o
sretal Qe or
Unit 1 : Programming and Computational Thinking (PCT-2) ( (80\Dheory + 70 Practical)
Revision of the basics of Python See o
4 Functions: scope, parameter passing, mutable/immatable properties of data objects, pass arrays to functions,
return values, functions using libraries : mathemat ical) and string functions.
4 File handling: open and close a file, read, writ8
streams, relative and absolute paths. 4 _
Using Python libraries: create and import Py! %
+ Recursion: simple algorithms with recursion: factorial, Fibonacci numbers; recursion on arrays: binary search.
} Idea of efficiency: performant :
q
fined aginversely proportional to the wall clock time, count the number of
operations a piece of code is performing, and measure the time taken by a program. Example: take two
different non same problem, and tinderstand how the efficient one takes less time.
8. >
ig Pyplot: line chart, pie chart, and bar chart.
tacks, queues.
ei horks'(CN) (30 Theory + 10 Practical)
network ®Types ofnetworks: local area and wide area (web and internet), new technologies
1d IoT, public vs private cloud, wired and wireless networks; concept of a client and server.
*eNetwork’deviees such as a NIC, switch, hub, router, and access point.
ork stack: amplitude’and frequency modulation, collision in wireless networks, error checking, and the
ACaddréss, main idea of routing, IP addresses: (v4 and v6), routing table, router, DNS, and web
co of retransmission, and rate modulation when there is congestion (analogy to a road
Pie G, 3G, 4G, Wi-Fi, What makes a protocol have a higher bandwidth ?
& Apple NRO taceroute, ping, contig, nslookup, whois, speedtest.
ayer: HTTP (basic idea), working of email, secure communication : encryption and certificates
(HTTPS), nets :
van aa ‘work applications: remote desktop, remote login, HTTP, FTP, SCP, SSH, POP/IMAP, SMTP,
Unit 2: Compiter
Unit 3: Da
+ shah Pinar (DM-2) (20 Theory + 20 Practical)
: jan a
file flatfile and CSV ene aplication that parses a GET and POST request, and writes the fields 04
* Interface Python with an SQL database.
* SQL commands: "
ands: aggregation functions — having, group by, order by.Unit 4: Society, Law and Ethics (SLE-2) (10 Theory)
~ Intellectual property rights, plagiarism, digital rights management, and licensing (Creative Commons, GPL
and Apache), open source, open data, privacy
+ Privacy laws, fraud: eyber-crime, phishing, illegal downloads, child pornography, seams; eyber forensics, IT
‘Act, 2000,
ind cultural changes induced by technology.
4 Technology and society: understanding of societal issues
4 Eswaste management : proper disposal of used electronic gadgets.
+ Identity theft, unique ids, and biometrics.
+ Gender and disability issues while teaching and using computers.
PRACTICAL
|_Unit No. Unit Name Marks.
1 Lab Test (10 marks)
| Python program (60% logic + 20% documentation + 20% code quality) 7
‘Small Python program that sends a SQL query to a database and 3
displays the result. A stub program can be provided.
2 Report File + Viva (9 marks) I~,
| Report 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 CSV file.
{ Viva voce : (based onithe report file) 2
3 Project + Viva (11 marks) |
| Project (that uses most of the concepts that have been learnt) 8 |
Project viva voce 3 |
Programming in Python
Recursively find the factorial of a natural number.
Read a file line by line and print it.
Remove all the lines that contain the character ‘a’ in a file and write it to another file
Write a Python function sin (x, 1) to calculate the value of sin (x) using its Taylor series expansion up to 1
terms, Compare the values of sin (x) for different values of n with the correct value.
Write a random number generator that generates random numbers between 1 and 6 (s
Write a'recursive code to find the sum of all elements of a list.
‘Write a recursive code to compute the n Fibonacci number.
Write a Python program to implement a stack and queue using, a list data-structure.
Write a recursive Python program to test if a string is a palindrome or not.
Write a Python program to plot the function y= x* using the pyplot or matplotlib libraries.
Create a graphical application that accepts user inputs, performs some operation on them, and then writes the
output on the screen. For example, write a small calculator. Use the tkinter library.
Open a webpage using the urlib library.
‘Compute EMis for a loan using the numpy or scipy libraries.
Take a sample of 10 phishing e-mails and find the most common words.
Data Management : SQL and Web-Server
~ Find the min, max, sum, and average of the marks in a student marks table.
+ Find the total number of customers from each country in the table (customer ID, customer name, country)
using group by.
yulates a dice).
HHP HHH SERS FH OSat ID, marks) table in descending order of the marks,
MySQL module.
+ equest (POST), and write it to a CSV file,
jor the (studer
importing the
to parse a user reque
query to ord
+ waite a SOX thon by
2 egate SOL with PN
2b Write a Django bases
x that is tangible and useful. This should be done in groups of
save tents at least 6 months before the submission deadline. The aim
at tae worthwhile to solve. Students are encouraged to visit local
inc that they are facing, For example, ifa busines is finding it hard
thon students can do a project that takes the raw data (list of
‘accounts for the GST tax ra and crates invoices in the
sivemely creative here. They can use a wide variety of Python libraries
pC stants can be rma ea ware fr the school, software for their disabled fellow
create se er teat Of couse to do some of this projects some additional learning is required;
Sea pao es 's should know how to teach themselves: i
Tae erie project for 6 months, atleast 500 lines of code is expected. The committee has also
STE POP ee il the degree of plagiarism in such projects. Teachers should take a very strict look at
Seen made aa ee int disiplinary action against students who are cheating on lab assignments, or
ena ot sain pirated software to do the same. Everything that is prop
josed can be achieved using
Sbsolutely free, and legitimate open source software.
Project
> Theaimof| the el
203 students 3
oct is to create something
dass proie
nd should be st
Ho find a real world problem
Mipesees a ask th tthe pro
sawnices for filing GST claims,
hei
businesses
The)[Link] for Digital Content
linked with this booR
“
Dear Students
f Get hold\of Linked Learning Resources (explanatory videos/
~illustrations/images/text solutions) for FREE, by scanning QR codes
(| given in the chapters using our integrated learning app
c@ “NX Sipo
Linked resources include :
= explanatory videos
© animations
® illustrations
@ images
™ ‘ext solutions of selective assignment questions.
50, what are you wailing for ? Download SIPO now1 © Python Revision Tour
-40 1.1 Introduction
1.2. Tokens in Python:
121 Keyuonds 2
1.2.2 Ientifirs (Names) 2
1.23 LiteralsValues 3
1.24 Operators 4
1.25 Punctuators 4
1.3. Barebones of a Python Program
14 Variables and Assignments
14.1 Dynamic Typing 6
14.2 Multiple Assignments 6
15. Simple Inputand Output
‘Output Through print ) Statement 8)
1.6. Data Types R
1.7 Mutable and Immutable Types
1.8 Expressions .
1.8.1 Evaluating Arithnnctic Operations: 14,
1.8.2 Evaluating Relational Exprésions 15
183° Evaluating Logical Expressions 16
418.4 Type Casting (Explicit Type Conversion) 16
1.85 Math Library Functions 17
9. Statement Flow Control
10. Th Conditionals,
1.10.1 Plain if Conditional Statement 20
Qa.102 Te ifelse Coitinal Statement 20
1103,-The if Contin Statenent 21
1.304 Nested if Statements 23
“1405 Storing Conditions 23
‘TAL Looping Statements
“Y1.11.4 The for Loop 24
1112 The while Lip 26
1.12. Jump Statements - breakand continue
The break Statement 26
The continue Statement 27
1.13. Moreon Loops
1.13.1 Loop else Statement 28
1132 Nested Loops 29
a2
Contents
10
12
14
19
20
24
26
28jon Tour-II
2 python Revi
21 Introduction ik
ane rings in Python
e a rtm Assignment ot Supported 2
522 Treersing# Sing 42
2.23 String Operators a
22a siring Slices 45
‘225 String Functions 46
23 Listsin Python
2.341 Creating Lists 51
232 Lists ws Strings 52
233. List Operations 53
2.34 List Manipulation 55
235 Making True Copy of a List 56
236. List Functions 56
24 Tuplesin Python
241 Creating Tuples 60
242 Tuples vs. Lists 61
243 Tuple Operations 62
244 Tuple Functions and Met
25. Dictionariesin Python 5%
2541 Crenting Dictionary 650
252 Accessing Elements ofa Dictionary 66)»
253 Cha adi &
ics of ®bictionary 67>,
62
254 Dictio yoru i
2.5.5¢Dictionary cons and Ranges
26 Sorting Techniques
16.1 Bubble Sort 75
6.2 a 76
Ning/Invoking/Using a Function 95
Python Function Types 96
Defining Functions in Python
ie 33.1 Structure of a Python Program 99
Flow of Execution in a Function Call
a
51
60
66
a
75
93 -
93
94
97
3.41 Arguments and Parameters 104 1
35. Passing Parameters
351 PositionaRequired Arguments. 106 i
352 Default Arguments 107
353
poe Kezeer Named) Arguments 108
Multiple Argument Types Together 109
| |3.6.1 Returning Multiple Values. 113
3.7. Composition
38. Scope of Variables
3.8.1 Name Resolution (Resolving Scope of a Namie) 120
3.9 Mutable/Immutable Properties of Passed Data Objects
4.9.1 Mutability/inmutability of Arguments/Parameters and Function Calls 125
| 3.6 Returning Values From Functions
,
4 | Using Python Libraries
153-186 4.1 Introduction
4.2. Whatisa Library?
4.2.1 What isa Module ?- 154
4.3. Importing Modules in a Python Program
43.1 Importing Entire Module 158
4.3.2 Importing Select Objects from a Module 159
43.3. Python's Processing of import
Command 159
4.4. Using Python Standard Library's Functions and Modules
44.1 Using Python’ Built-in Functions 162
444.2 Working with Some Standard Library Modulus 168
4.5. Creatinga Python Library
45.1 Structure of a Package 172
45.2 Procedure for Creating Packages 172
45.3 Usi
Importing Python Libraries. 17
Useful Additional Information (UAD,
Object Oriented Programming Concepts (UAI-1)
5 File Handling
195-228 5.1 Introduction
52 DataFiles
“0. 5.3) Openingand Closing Files
153.1 Opening Files 196
5.3.2) Closing Files 199
5.4) Reading and Writing Files
54.1 Reading from Files. 199
54.2 Writing onto Files 205
5.4.3. The lush( ) Function 209
5.44 Removing Whitespaces after Reaing from File 209
54.5 Significance of File Pointer in File Handling 201
55. Standard Input, Output and Error Streams
6 {Recursion
229-264 6.1. Introduction
62. Recursive Function
110
15
us
123
153
154
157
162
171
187-194
195,
196
196
199
212
229
230463, How Recursion Works
64. Recursion In Python
‘4.1 Some Recursive Codes 243
64.2 Binary Search 246
64.3 Recursie Binary Search
65. Recursion Vs Iteration
250
7 Idea of Algorithmic Efficiency
7.1 Introduction
72. Whatis Computational Complexity ?
"73. Estimating Complexity of Algorithms
73.1 Big-O Notation 266
7.3.2 Guidelines for Computing Complexity 268
7.4. Best, Average and Worst Case Complexity
265 - 284
§
f
8 _ Data Visualization using Pyplot
285-332. ‘8:1. Whatis Data Visualization?
8.2 Using Pyplot of Matplotlib 1
8.21 Installing and Importing maipltib “
8.2.2. Working with PyPIof Methods 2
: ates m
83. Creating Charts with matplotlib Library's pyplot Interface
83.1 Line Cha
83.2 Bar CI
Iseful Additional Information (UAT)
List Comprehension And Nested Lists (UAI-2)
9 Dat@Structures : Stacks and Queues using Lists
341-384) 9.1 Introduction
9.2. Elementary Data Representation
~— 93. Different Data Structures
93.1 Linear Lists Arrays 343
93.2 Stacks 343
933 Queues 343
9.3.4 Linked
93.5 Trees 344
233
240
251
265
266
266
am
285
286
293
314
322
333-340
341
342
342
siege9.4. Operations on Data Structures
9.5 Stacks
9.5.1 Implementing Stack in Python 347
9.5.2 Stack Applications 350
9.6 Queues
9.6.1 Implementing Queues in Python 360
9.62 Variations in Queues 363
9.6.3 Queue Applications 364
10
385 — 408
- Computer Networks — I
d
10.1 Introduction
10.2. Computer Networks ~ An Introduction
10.2.1 Components of a Computer Network 387
10.3. Types of Networks
10.3.1 Types of Networks based on nrign Spread 3
10.3.2 Types of Networks by Component wis 390
10.3.3 Type of Networks based on Communication Channel
fs
104.3 Hub 397
1044
1045
104.6
104.7
10.4.8 Access Pe
105 The Cloud
405. 51 Types of Clouis 400),
10.671 internet of Things (or)
é: Jimologies for IoT 401
11.2.1 Major Types of Modulation 410
©) 113 Collision in Wireless Networks
i
113.1 How CSMAICA Works 413,
m4 (Error Detection)
11.5. Main Idea of Routing
11.6 TCP/IP
11.6.1 Network Congestion and Retransmission in TCP 424
1L7 Addresses on a Network
117.1 The Domain Name and DNS 428
10.4 Network Devices/Hardware
10.4.1 NIC (Network Interface Cir 8
104.2 WiFi Card 396
=
co,
344
345
358
385
386
388
396
399
400
409
410
412
415
420
423
425118. Collular/Wireless Connectivity Protocols
11.9 Basic Network Tools
0
a Pacers (for Linux) or TRACERT (for Windows) 431
1193 NSLOOKUP 431
1194 IPCONFIG Command 432
119.5 WHOIS Command 433
119.6 Speed Test 433
11.10 Various Protocols Used on Networks
© 11.1 How HTTP Works - A Basic Idea
11.12, Working of Email Cis
11.13 Secure Communication
11.131 HTTPS 439 »
11.13.2 Secure Sockets Layer (SSL) 439 » .
11.14 Network Applications : :
MySQL SQL Revision Tour
12.1 Introduction
122 Relational Data Model
Referentil Integrity 456
12.3. MySQL-A Popular Relational DataBase Management System
12.3.1 MySQL and SQL 457
123.2 Common MySQL Data Types 458
124 Accessing Database in MySQL
12.5 Creating Tables in MySQL
12.6 Inserting Data Into Table
| nserting NULL values 460
Inserting Dates 460
@ Simple Queries Through Select Command
127.1 Selecting’All Data 460
127.2 Selecting Particular Rows 460
912.73 Selecting Particular Columns 461
127.4. Bliminating Redundant Data (with Keyword DISTINCT) 461
12.7.5" Selecting From All the Rows ~ ALL Keyword 461
“127.6 Viewing Structure of a Table 461
“Qy 12.7.7, Performing Simple Calculations 462
12.7.8 Using Column Aliases 462
12.7.9 Condition Based on a Range 462
127.10 Condition Based on a List 462
127.11 Condition Based on Pattern Matches 462
127.12 Searching for NULL. 463
128 Creating Tables with SQL Constraints
128.1 SQL Constraints 464
1282 Applying Table Constraints 468
434
436
437
438,
441
455
456
457
458
459
459
460
464Viewinga Table Structure
Inserting Data Into Another Table
Modifying Data in Tables
Deleting Data from Tables
12.13 Altering Tables
12.14 Dropping Tables
12.15. SQLjoins
12.16 Indexes in Database
13. | More on SQL
13.1 Introduction
13.2. Ordering Records in Result - Order by Clause
483 - 505 |
14 Creating a Django based Basic Web Application
507 - 546
13.2.1. Recalling SQL SELECT ORDER BY Clause 483.
X
13.2.2 Ordering Data on Multiple Columns 485
1323. Orrin Dla onthe aso Expres
13.24 Specifying Custom Sort Order 486 |
13.3. Aggregate Functions
13.4. Types of SQL Functions
13.5 Grouping Result - GROUP BY «
1351 Nested Groups ~ Grouping MultipeColamns 482
1352 Placing Contin on Grows HAVING Clause 493
13.5.3 Now-Group Expressions with GROUP BY 495)
14.1 Introduction x
14.2. What isWeb Framework?
Web Frametork 2s. Library SOS +
143 HowWeb, Websites and Web-applications Work?
144 Introducing Django
Why Django ? 510 ~
"44,5" Installing Django
“Whats virtualeny and Why to use it ? 510
14:7, Django Basics and Project Structure
% 1471
What are “Project” and “App’ in Djan
14.7.2 Understanding Django Project Architecture 520
14.8 Steps to Createa Basic Django Web Application
14.9 Creating Models, Views and Templates
491
1492
1493
194
Creating Models 522
Creating Templates: 523
Creating Views 524
Creating URL Confs 525
468
469
469
469
470
4am.
471
472
483
483
488
491
491
507
507
508
510
510
si4
515
s2u
522528
ry Data to CSV and Text Files
iting Dictiona
amin: to a CSV File 528
530
1 Writing i!
14.10. i a
10.2. Writing into a Text File
oa GET and POST Request
14.11. Practically Processing G
15 | Interface python with MySQL sé
15.1 Introduction 547
mre 452. Connecting to [Link] Python 5s 3
15.21 Steps for Creating Database Connectivity Applications Ps,
15.3. Parameterised Queries 557
154. Performing insert and update Queries
16 |" Society, Law and Ethics
563-~592| 161 Introduction : ‘ 563
| 16.2. Bthical Issues an see
j 16.2.1. Intellectual Property Rights 564)
j 16.22 Plagiarism 564 Y
j 16.23 Digital Property Rights 565%
16.3 Open Source Philosophy and Software Licences 566
163.1 Terminology 566, :
1632 Phitephy of Ope\Source 567
1633 Deniions 568, ~
1634) Licenses and Wri of Opent Source Technology 570
16.4 Pr
165. Onl = Fraud ~ le
aud & 572
tybercrime »
».7 Computer Fi ic a
ter Foreisies
Cyber La andi Ir Ace o76)
‘echnology and Society me
2.1 Economic Benefits 578 ne
a
‘Management
110.1 E-Waste Disposal Process 578 oe
16.10.2 Benefits of e-Waste Recycling 579
Identity Theft
16.12. Gender Issues while Teaching/Using Computers aide
16.12.1 Gender Issues 581 581
16.13 Disability Issues while Teaching and using Computers si
a= B‘Appendices
A1-A26 © Appendix A: Utility of Module’s_name_
Appendix B: Working with A Useful Python Library - tkinter
Jango Installation on Ubuntu Linux
reating (data) Models for Django apps
Appendix E: Installing MySQl. Python C
roject Creation and Distribution
Appendix G: Additional Problems on Networking
Appendix C:
Appendix D
Appendix F:
Answers to Objective Type Questions (OTQs)
@-
Additional Resource 1
Additional Resource 2
Additional Resource 3
Al
A2
AS
AG
AAO
Adal
algsTS_OF
QR CODES
Lists oF QR COPES
Bubble Sort in action 75
Insertion Sort in action 76
Function Anatomy in action 95
Part of a Function in action 95
Working of a Function in action 107
Flow of Execution in action 703
Function Parameters in action 106
Variable Scope in action 178
Name Resolution in action 120
For Selective Assignment Solutions
Two Ways of Import in action 167
For Selective Assignment Solutions 182
147
Reading from File in action 201
working of File Pointer in action 217
For Selective Assignment Solutions 226
Recursion in action 233
Recursion in action 238
For Selective Assignment Solutions 267
Loops Complexity 268
Consecutive Statements Complexity 269
Nested Loops Complexity 269
Itelse Complexity 270
Logarithmic Complexity 270
For Selective Assignment Solutions 282
These Graphs in action 301
This Graph in action 308
These Graphs in action 313
‘ For Selective Assignment Solutions 330
lacks in action 345
Queues in action 359
Circular Queues in action 363
For Selective Assi
lgnment Soluti
Development of Django mee
Web Application 530
zZtwtwTo
Kushagra and Mythili,
With Love11
Python
Revision Tour
at a\ Charl’
1.1 Introduction 1.8. Expressions
1.2. Tokens in Python 1.9. Statement Flow Control
1.3. Barebones of a Python Program 1.10. The if Conditionals
1.4 Variables and Assignments 1.11 Looping Statements
1.5. Simple Input and Output 1.12 Jump Statements — break and continue
1.6 Data Types 1.13 More on Loops
17. Mutable and Immutable Types
INTRODUCTION
You must have enjoyed learning Python in class XI. Python programming language, developed
by Gutido Van Rossum in early 1990s, has become a very popular programming language
among beginners as well as developers. The journey of Python that you started in class XI will
continue ir, class XIl as well. In class XII, you shall learn more about Python and some advanced
concepts, Before we start with newer topics and concepts in Python, let us revise all that you
have leant in class XI. And this chapter will be doing just the same, ic, take you to the revision
tour of Python that you learnt in your previous class.2
Ea
1.2 TOKENS IN PYTHON
The smallest individual unit ina p'
ora lexical unit.
sthon has following tokens + ae
pps (i) Identifiers (Names) (HH) Literals
rogram is known asa Toker
punctuators
(i Keywords
(iv) Operators (7) Punctuators
4A sample Python program
for a1_in range(1,<1@) 5
if a%2 == @
keywords go iterals
5 operators
identifiers:
Figure 1.1 Some tokens in a Python program.
Let us revise our understanding of tokens
1.2.1 Keywords
Keywords are predefined words with special meaning to the
language compiler or interpreter. These are reserved for
special purpose and must not be used as normal identifier
names.
Python programming language contains the following keywords :
False assert del for in or
None break elif from is pass
True class else. global lambda raise
and continue except if nonlocal return
as def finally import not try
1.2.2 Identifiers (Names)
Identifiers are the names given to diffe:
functions, lists, dictionaries and so forth,
The naming rules for Python identifiers can be
© Variable names must only be
NO spaces in between,
© Variable names must be mi
numbers, and underscore (_).
® Variable names ca:
they can contain
a non-keyword word with
ade up of only letters,
innot begin with a ni
manor umber, although
COMPUTER SCIENCE WITH Prrycyll
rent parts of the program viz. variables, objects, ¢
summarized as follows :
eran
The smallest individual yu
rogram is known as a qt a}
a lexical unit. 7
Sacre
A keyword is a word
special meaning reserved by
programming language.
while
with
yieldChapter 1: PYTHON REVISION TOUR
The following are some ‘The following are some invalid identifiers :
valid identifiers:
DATA-REC contains special character - (hyphen)
Myfile = DATE9_7_77 (other than AZ, a-z and _ (underscore) )
BYE 29cicT Starting with a digit
ca ee break reserved keyword
gate. ee [Link] contains special character dot (.)
1.2.3. Literals/Values
Literals are data items that have a fixed/constant value.
Python allows several kinds of literals, which are being given below.
(i) String Literals
‘Astring literal isa 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 line strings must terminate in one line ie., the closing quotes should be on the
same line as that of the opening quotes. (See below)
© Multiline 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 needed at the end of intermediate lines. (see below) :
>>> Text1= "Hello World" «—___
Single line string
“Helly go
Multi-line string
Instrings, you can include non-graphic characters through escape sequences. Escape sequences
are given in following table :
"Escape | What it does Escape What it does
sequence | [Non-graphic character] sequence __[Non-graphic character]
\ | Backslash (\) \r Carriage Return (CR)
\ | Single quote (’) \t Horizontal Tab (TAB)
¥ Double quote (”) \ woo. Character with 16-bit hex value
xxx (Unicode only)
\a ASCII Bell (BEL) \Uxxxxxxxx | Character with 32-bit hex value
2x0xXX (Unicode only)
\b ASCII Backspace (BS) \v ASCII Vertical Tab (VT)
\f ASCII Formfeed (FF) \o00 Character with octal value 000
\n New line character \xhh Character with hex value hh
\N{name} Character named name in the
Unicode database (Unicode only)COMPUTER SCIENCE WITH PYTHON q
(i) Numeric Literals
Numeric literals are numeric values and these can be one of th
e following types :
‘ust integers or ints, are positive or negative whole
(a) int (signed integers) often called just integ
numbers with no decimal point.
. ite in:
The integer literals can be written i aL ie
Doe + an integer beginning with digits 1-9. eg» 1
oie i i followed by letter 0) ¢.g., 0035, 0077 ete,
© Octal form : an integer beginning nt (eer ie on
], 8 and 9 are i .
Here do remember that for Octal, ity een ee
i : an integer beginning with 0x (zero follow 1 0X73,
© Hexadecia orm er that vad digitsetters for hexadecimal numbers are 0-9 and
AF.
(&) Floating Point Literals, Floating point literals or real literals floats represent real anes
and are written with a decimal point dividing the integer and fractional Lined a numbers
having fractional parts. These can be written in fractional form e.g., ~13.0, .75, 7. ete. or in
Exponent form e.g,, 0.17E5, 3.E2, .6E4 etc.
(.Complex number literals are of the form a + bJ, where a and b are floats and J (or j) represents
=I, which is an imaginary number). a 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.e., True (Boolean
true) 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 literal is used to indicate absence of
value
Python can also store literal collections, in the form of tuples and lists ete.
1.2.4 Operators
Operators are tokens that tri
igger some computati i . ;
oljecisin an expression 'putation / action when applied to variables and other
The operators can be arithmetic o
t Perators (+, ~,*, /, %, **, /), bitwi . ift
operators (<<, >>), identity operators (is, is not), relational te = - i si
operators (and, ox), assignment operator (c cpeuealan e
arithmetic-assignment operators (/=, +=, —, ", emer operators (in, not in), and
1.2.5. Punctuators
ymbols that are used in
structures, and indi Shas or a lane ;
one insisate the thythm and emphasis of expressiee ogee eee SemteN
7 Pressions, statements, and progral
Most common punctuators of PythonChopter 1 : PYTHON REVISION TOUR
1.3. BAREBONES OF A PYTHON PROGRAM
A Python program may contain various elements such as comments, statements, expressions etc.
Let us talk about the basic structure of a Python program.
# This program shows a program’ s components
4 Definition of function SeeYou() follows
Comments er SeevOUC) + Fanetion
(begin with #) print ("Time to say Good Bye ! 1")
# Main program-code follows now
a= 15
anne "ee
binant? Expressions
print (a+ ae ie
if bos? # colon means it’s a block
.» print ("Value of 'a' was more than 15 initially.") Inline comments
Indentation (comment beginning
(se indented aces in the middle of a line)
‘& print ("Value of 'a'was 15 or less initially.")
Function call
“4 —— seevou() # calling 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 or multiple # style comments.
© Functions, which are named code-sections and can be reused by specifying their names
(function calls).
© Block(s) or suite(s), which is a group of statements which are part of another statement or
a function. All statements inside a block or suite are indented at the same level.
1.4 VARIABLES AND ASSIGNMENTS
Variables represent labelled storage locations, whose values can be manipulated during
program run.
In Python, to create a variable, 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 need to write somewhat similar to what is shown below :
Student
Age = 16
jacob!COMPUTER SCIENCE WITH PYTHON
i as shown below.
Python will internally create labels referring to these values
student | =}——|
=
age [ f
ela
1.4.1. Dynamic Typing .
have learnt, a varial
cya asinine string etc.). For instance,
X=10
We can say that variable x is referring to a value of integer type. ; me
Later in your program, if you reassign a value of some other type to variable x, Python will nol
complain (no error will be raised), e.g.,
1c is defined by assigning to it some value (of a part
after the statement :
PRA nnes
eee A variable pointing to a value of|
print (x) a certain type, can be made to
X= "Hello World" point to a value/object of|
) print(X) different type. This is called
Dynamic Typing.
Above code will yield the output as :
10
Hello World
So, you can think of Python variables as labels associated with objects (literal values in our case
here) ; with dynamic typing, Python makes a label refer to new value with new assignment
(Fig. 1.2). Following figure illustrates it.
x= 10 *| =| int:10
‘Bo int:10
————__
String:Hello World
Figure 1.2 Dynamic typing in Python variables,
Dynamic Typing vs. Static Typing
ariables in a single stateme - You can assign same value to multipl
tement, e.g,
a=b=c=10
It will assign value 10 to all three variables a, b, ¢.Chapter 1: PYTHON REVISION TOUR We
2. Assigning multiple values to multiple variables. You can even assign multiple values to
multiple variables in single statement, ¢
X,Y) Z= 10, 20, 30
Tt will assign the values or 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
y and 30 to =.
If you want to swap values of x and y, you just need to write as follows :
x VEY) X
In Python, assigning a value to a variable means, variable’s label is referring to that value.
val =3
val -6
[for statement
val = 3]
P3000
6 | [for statement
( val = 6]
[i |vat
val
Memory address (3000) Memory address [3048] storing
Variable val stores values at same location storing value 3is assigned a value 6 is assigned a label as
(memory-address) and changes values label as val {for statement val = 6).
stored in it. val {for statement val = 3] Now val no longer is referencing
to memory location 3000.
Literal values are having a fixed location and variable
names reference them as labels.
(@) In traditional programming languages:
like C/C++ etc.
(0) In Python programming language
Figure 1.3. How variables are stored in traditional programming languages and in Python.
1.5 SIMPLE INPUT AND OUTPUT
In Python 3.x, to get input from user interactively, you can use built-in function input( ). The
function input) is used in the following manner =
variabLe_to_hold_the_value = input ()
For example,
name = input (‘What is your name ?')
Jay the prompt as :COMPUTER SCIENCE WITH PYTHON ~
String type. Python offers two functions int(
e of . eros
‘The input() function always returns a vali Site ce received through input() into int ang
and float() to be used with input() to convert th
float types. You can : sane
i ing input( ) function.
© Read in the value using input
© And then use int() or float( ) function with the read value to cl
to int or float respectively.
hange the type of input value
You can also combine these two steps in a single step too, i.e., as +
= int( input( ) )
Or
= float( input( ) )
" ms oes
Float ( input("Enter warks : ") )
vIn [19]: mark:
Enter marks : 73.5
Function int( ) around input( )
converts the read value into int type
and function float( ) around input( )
In [28]: age = int( input(
What is your age ? 16
function converts the read value into
float type.
In [22]: type(marks)
Out[23]: float
In [22]: type(age)
coutlaad nets
While inputting integer values using int() with input(), make sure that the value being entered
must be int type compatible. Similarly, while inputting floating point values using float() with
input(), make sure that the value being entered must be float type compatible (e.g., ‘abc’ cannot
be converted to int or float, hence it is not compatible).
Output Through print( ) Statement
The print( ) function of Python 3.x is a way
to send output to standard output device, which is
normally a monitor.
The simplified syntax to use print( ) function is as follows :
Print (*objects, [ sep =‘? or end = “\n’ or ])9
“objects means it can be one or multiple comma separated objects to be printed,
Let us consider some simple examples first :
print ("hello")
print (17.5)
print (3.14159*(r*p))
#astring
# a number
# the result of a calculation, which will
# be performed by Python and then printed
# out (assuming that some number has been
# assigned to the variable r)
# multiple comma separated expressions
Print ("I\'m", 12+5,"years old, )ee a
The print statement has a number of features :
© it auto-converts the items to strings i.c., if you are printing a numeric value, it
automatically convert it into equivalent string and print it ; for numeric expressions, it
first evaluates them and then converts the result to string, before printing.
© itinserts spaces between items automatically because the default value of sep argument
(separator character) is space(’ ),
Consider this code :
For ier sting object with no
print ("My", "name", "As", "Amit ."y 4 sce in then are being printed.
will print
is amit, <———— nt the output line has automatically spaces inserted it
My name is Amit. ‘between them Because default sep character isa space,
‘You can change the value of separator character with sep argument of print() as per this :
The code :
print ("My", “name”, "is", “Amit.", sep="...")
will print
: This time the print) separated the tems
My. .omame. 4s. .amit, sith vor sep characters hich
© it appends a newline character at the end of the line unless you give your own end
argument. Consider the code given below :
print ("My name is Amit.")
print("I am 16 years old")
It will produce output a:
My name is amit.
I am 16 years old
If you explicitly give an end argument with a print() function then the print( ) will print the line
and end it with the string specified with the end argument, and not the newline character, ¢.g.,
the code
print("My name is Amit.
print("I am 16 years old. ")
will print output as :
otis eprint) oad he ti ih geen
a,
character, which is'$" here. iad because it was not
My name is Amit. $I am16 years old. — newline, nest line wus prints from here itself
1.1 Write a program to input a number and print its cube,
‘num = float (input( ‘Enter a number: *))
‘fnum_cube = num * num * num
print( ‘The cube of", num, ‘is’, num_cube)COMPUTER SCIENCE WITH PYTHON,
int it re root.
Write a program to input a number and print its squar
num = float(input( ‘Enter a number: '))
num_sqrt = num ** 0.5 au
print(‘The square root of", num, ‘is’, num_sqrt)
PYTHON : BASIC INPUT/OUTPUT
Progress In Python 1.
iP
is ‘PriP” session is aimed at revising various concepts you learnt in Class XI.
Science with Python and fill it there in PriP 1.1 under Chapter 1 after
practically doing it on the computer.
¢ Please check the practical component-book — Progress in Computer »)
pooticc<
1.6 DATA TYPES
Data types are means to identify type of data and set of valid operations for it. Python offer
following built-in core data types : (i) Numbers (ii) String (iii) List (fe) Tuple (v) Dictionary.
(i) Data types for Numbers
Python offers following data types to store and process different types of numeric data :
(a) Integers
© Integers (signed)
© Booleans
(b) Floating-Point Numbers
(©) Complex Numbers
(a) Integers. There are two types of integers in Python :
(@ Integers (signed). It is the normal integer representation of whole numbers. Python 3.
Provides single data type (int) to store any integer, whether big or small. i
It is signed representation, ie, the integers can be positive
(i) Booleans, These represent the
subtype of plain integers, and B
and 1, respectively,
as well as negative.
truth values False and True. The Boolean type is 3
‘oolean values False and True behave like the values
(0) Floating Point Numbers, In Python, floating point number
Precision floating point numbers (15 digit precision), The ra
underlying machine architecture Subject to available (virtua
(© Complex Numbers. Python re
numbers are a composite quantity
Which are represented internally
tS represent machine-level doubl
inge of these numbers is limited
1) memory. 4
Presents complex numbers in the form A+ Bj, Com
made of two parts : the real
Part and the imaginary part, both
8s float values (floating p:
oint numbers).Chapter 1: PYTHON REVISION TOUR
You can retrieve the two components using attribute
references. For a complex number z :
© zareal gives the real part.
© zimag gives the imaginary part as a float, not as a
complex value.
Table 1.1 The Range of Python Numbers
Data type Range
Integers an unlimited range, subject to available (virtual) memory only
Booleans 200 values True (1), False (0)
Floating point | an unlimited range, subject to available (virtual) memory on
numbers underlying machine architecture.
Complex Same as floating point numbers because the real and
numbers imaginary parts are represented as floats.
(i) Dato Type for Strings
Allstrings in Python 3.x are sequences of pure Unicode characters. Unicode is a system designed to
tepresent every character from every language. A string can hold any type of known characters
ice, letters, numbers, and special characters, of any known scripted language.
Following are all legal strings in Python :
“abcd” , “1234”, ‘$%&’, 2727", “SEA” , “apy”, ‘ee,
ad, “opsias!
A Python string is a sequence of characters and each character
can be individually accessed using its index.
(ii) Lists,
A List in Python represents a group of comma-separated values of any datatype between
square brackets e.g., following are some lists :
[1, 2, 3,4, 5]
[ate iy’, u']
['Neha’, 102, 79.5]
In list too, the values internally are numbered from 0 (zero) onwards i.., first item of the list is
internally numbered as 0, second item of the list as 1, 3rd item as 2 and so on.
(v) Tuples
Tuples are represented as group of comma-separated values of
any date type within parentheses, ¢.g,, following are some tuples :
p= (1, 2, 3, 4,5)
a= (2, 4, 6, 8) ; iat
r=(a'e," ablea
a
4
ss COMPUTER SCIENCE WITH PYTHON — yy
2.
23 42
(v) Dictionaries /
icti¢ is d set of
The dictionary is an unordere: he
requirement that within a dictionary, no two keys can a re at :
within a dictionary). For instance, following are some dicti
: i ithin { }, with the
separated key : value pairs, witl , the
Se ae i .e., there are unique keys
23,104, Us 5}
far1,
>>> vowels = {'a': 1, 'e: 2, i: 3,'0 4, ‘u's 5}
>>> vowels['a'] NN ere 0, 6,0" and are the keys ofdctionary vowels:
1 1.2.3, 4,3 ar values for these keys respectively: |
hi ;
Following figure summarizes the core data types of Python.
Core Data Types
Numbers None Sequences Mappings 4
1 ——
—-— rN
Integer Floating Complex sting Tuple List Dictionary
1 point
Boolean
1.7 MUTABLE AND IMMUTABLE TYPES
The Python data objects can be broadly categorized into to ~ 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 Python, the following
types are immutable: integers floating point numbers, Bolenns, strings, tuples, 7
In immutable types, the variable names are stor
you change the value, the variable’s referenc
explanation for sample code given below :
ed as references to a value-object, Each time
€ memory address changes. See following
© Initially these three statements are executed :
Pes
9=P ¢—— All variabies having same val
3 i ‘ame value reference and the s
nie value object i.e., Pod will all 4 moder
reference same integerChopter 1: PYTHON REVISION TOUR
=) sfatz tats
a
qr
Figure 1.4
When the next set of statements execute, i.c.,
p=10
then these variable names are made to point to different integer objects.
Figure 1.5
Mutable Types fee a
Python frontloads some commonly
Mutability means that in the same memory address, new wed values in’ memory. Each
value can be stored as and when you want. The types that do
not support this property are immutable types.
address of the value. Multiple
variables/identifiers can refer to a
r be changed in
The mutable types are those whose values can 8 on ae
place. Only three types are mutable in Python.
These are :
ists, dictionaries and sets.
To change a member of a list, you may write =
Chk = [2, 4, 6]
chk[2] = 40
It will make the list namely Chk as [2, 40, 6].COMPUTER SCIENCE WITH PYTHON _y
14
1.8 EXPRESSIONS
jon in Python is any valid combination of operators, literals and variables,
‘An expressio s
nithmetic expressions, string expressions, relation
expressions in Python ean be of any type : a7
tapmescions, logical expressions, compound expressions ete. —
Adi ; ions i ers (intege ating:
“Arithmetic expressions involve numbers (integers, a % ae ornate
point numbers, complex numbers) and arithmetic operators, epee
eto ee ane ard atoms. An expresso
als and/or variables of any valid composed of one or more
‘An expression having liter. " 7
a relational expression. For ‘operations.
type and relational operators is a n
example, these are valid relational expressions :
zesq, xZ, Xazyl=z j
‘An expression having literals and/or variables of any valid type and logical operators isa
Togical expression. For example, these are valid logical expressions :
aorb, bandc, aandnotb, not cor not b
x>y, yeez, ZIEX,
Python also provides two string operators + and *, when combined with string operands and
integers, form string expressions.
Following are some legal string expressions :
“and” + "then" #would result into 'andthen' - concatenation
"and" *2 # would result into ‘andand' - replication
1.8.1 Evaluating Arithmetic Operations
Toevaluate an arithmetic expression (with operator and operands), Python follows these rules :
© Determines the order of evaluation in an expression considering the operator precedence.
© As per the evaluation order, for each of the sub-expression (generally in the form of
¢.g., 13 % 3)
= Evaluate each of its operands or arguments.
= Performs any implicit conversions (e.g., promoting int to float or bool to int for
arithmetic on mixed types). For implicit conversion rules of Python, read the text
given after the rules.
© Compute its result based on the operator.
= Replace the subexpression with the computed result and carry on the expression
evaluation.
® Repeat till the final result is obtained.
In a mixed arithmetic expression, Python converts all oj f
e , verts all operands up to the type of the largest
operand (type promotion). In the simplest form, an expression istike 7
xly or p**
applied :
e, if op! operator op2 (eS
4). Here, if both arguments are standard numeric types, the following coercions are
© If either argument is a complex number, the other is
converted to complex ;
© Otherwise, if either argument is a floating point
number, the other is converted to floating point ; compiler without F
© No conversion if both operands are integers. intepventionsChopter 1: PYTHON REVISION TOUR
Table operator precedence
Operator | | Description |
i) Parentheses (grouping) | Highest
” Exponentiation |
Bitwise nor
Positive, negative (unary +, -)
| Multiplication, division, floor division, remainder
| Addition, subtraction
\ Bitwise OR |
& | Bitwise AND |
| * Bitwise XOR
|
Recuaoe a! Comparisons (Relational operators), identity operators
| is, is not |
| not x Boolean NOT
| and Boolean AND
| or Boolean OR Lowest
Example 1.1 Consider below given expressions what. What will be the final result and final data type ?
(a, b=3,6 (©) a,b=3,6 (a, b=3,6.0
c=b/a cab//a c=b%a
Ans. (a) In expression
c=6/3 bisa
c=2.8 | |
int int ,
7 Hs te prt ih aos
floating pt
(®) In expression (0) Inexpression
c=6//3 b // a ¢=6.0%3 b % a
c=2 1 | c=0.0 | 1
int int float int
at a)
int float
1.8.2 Evaluating Relational Expressions
All comparison operations in Python have the same priority, which is lower than that of any
arithmetic operations. All relational expressions (compa id Boolean values only ie.,
True or False.
Further, chained expressions like a<4) and (7<¥)
(ii) (@<=N) and (N<=b)
1.8.3 Evaluating Logical Expressions :
While evaluating logical expressions, Python follows these rules :
(The precedence of logical operators is lower than the arithmetic operators, so constituen
arithmetic sub-expression (if any) is evaluated first and then logical operators are’
applied, e.¢.,
25/S or 2.0 + 20/10 will be first evaluated as : Sor 4.0
So, the overall result will be 5.
(i) The precedence of logical operators among themselves is not, and, or. So, the expression
@ or b and not c will be evaluated as :
(a.0r (band (not c) )) Similarly, following expression
((p and q) or (not r))
pand q or not r will be evaluated as :
(ii) Important. While evaluating, Python minimizes internal work by following these rules :
(@) In or evaluation, Python only evaluates the second argument if the first one is false val
( Inand evaluation, Python only evaluates the second argument if the first one is true ot
Example 1.3 What will be the output of following expression 2
(518) and (10 < 5) or (3 < 18) and not 8< 18
Solution. False
1.8.4 Type Casting (Explicit Type Conversion)
An explicit type conversion is user-
type. The explicit type com
(expression)
where is th
le data type to whi
PPecast your expression, = “® Which you want to j
aoe Operand to a specific type is}
if we have (@=3andb= 5.0), then called type casting.
int(b)
will cast the data-type of the expression as int.CChopter 1 : PYTHON REVISION TOUR
1.8.5 Math Library Functions
Python’s standard library provides a module namely math for math related functions that work
with all number types except for complex numbers.
In order to work with functions of math module, you need to first import it to your program by
giving statement as follows as the top Tine of your Python script:
import math
Then you can use math library’s functions as math. -
Table 1.2 Some Mathematical Functions in math Module
Prototype
(General Form)
Description
Example
[Link](num)
The ceil() function returns the
smallest integer not less than num.
[Link] (1.03) gives 2.0
[Link](—103) gives -10.
[Link] (num)
The sqrt( ) function returns the
square root of mun. If num <0,
domain error occurs.
[Link](81.0) gives 9.0.
exp | [Link](arg)
The exp( ) function returns the
natural logarithm e raised to the
arg power.
[Link] (2.0) gives the value
of e.
math fabs (num)
fabs
floor _ | [Link] (num)
‘The fabs( ) function returns the
absolute value of num.
‘The floor{ ) function returns the
largest integer not greater than
num.
math. fabs(1.0) gives 1.0
_math fabs(~L0) gives 1.0.
[Link](1.03) gives 1.0
math,floor(-103) gives -20.
log —_| [Link] (num, [base]
)
The log( ) function returns the
natural logarithm for num. A
domain error occurs if num is
negative and a range error occurs
if the argument num is zero.
[Link](1.0) gives the natural
logarithm for 1.0.
[Link] (1024, 2) will give
logarithm of 1024 to the base 2.
Jogi0__| math.Jogi0 (num)
[Link] (base, exp)
pow
[Link](arg)
[Link](arg)
The logi0( ) function returns
the base 10 logarithm for num.
A domain error occurs if num is
negative and a range error
occurs if the argument is zero.
The pow) function returns base
raised to exp power ie,. base exp.
A domain error occurs if base =O
and exp <=0 ; also if base <0 and
teger.
The sin( ) function returns the
sine of arg. The value of arg
must be in radians,
The cos( ) funct
cosine of arg. The value of arg
must be in radians.
math.logl0(1.0) gives base 10
logarithm for 1.0.
math pow (3.0, 0) gives value of
3.
[Link] (40, 2.0) gives value
of F
[Link](val)
(val is a number).
[Link] (val)
(val is a number).COMPUTER SCIENCE WITH PYTHON _¥
Example
S. tic Prototype ) Description xample
Function: rm)
No. (congrats : the | [Link](val)
htan(arg) The tan( ) function returns the | marhiont TT
nl jee tangent of arg. The value of arg
must be in radians.
aaa le x
a es(3) The degrees( ) converts ang]
12, | degrees | mathuteprees() from radians to degrees.
ene aaa E i le x
ans | [Link](x) ‘The radians( ) converts ang}
ee |e from degrees to radians,
[Link](x, y) This function returns the
oe le modulus resulting from the | as eee te a
livisic of ith y. [Link](7.4, gives value |
pada gee «gy | 28 1-4000000000000004 |
It is little different from x % y ‘i |
; [Link](-7.4, 3) gives value
in the sense that it offers more | oni
precision, and returns the ase ual
result with the sign of x (unlike | math. es eo ieee value
x % y, which returns with sign | #8 ~2.30
of y).
fmod is preferred for floats,
because of higher precision
while x % y is preferred for
integers.
15. | factorial | [Link](arg) _| This function returns factorial | [Link](4) gives value
of arg as an integer. as 24
It will raise ValueError if arg is | [Link](6) gives value
not integral or is negative. as 720 j
16. | gcd | math. ged(x, y) This function setums the [Link](8, 6) gives value as 2
greatest common divisor of the | [Link](28, 20) gi
integers x and y. If either x or y Bed(28, 20) gives value as 4
is nonzero, then
the value of ged(x, y) is the
largest positive integer that
divides both x and y.
gcd(0, 0) returns 0.
DATA HANDLING
>o>epcceCChopter 1: PYTHON REVISION TOUR ‘5
Let Us REVISE
_ —
‘A Python program can contain various components like expressions, statements, comments, functions, blocks and
indentation.
4 Blocks are represented through indentation.
Python supports dynamic yping i.e, a variable can hold values of different types at different times.
‘The input( ) is used to obtain input from user ; it always returns a string type of value.
‘Output is generated through print( ) (by calling print function) statement.
Operators are the symbols (or keywords sometimes) that represent specific operations.
‘Anexpression is composed of one or more operations. Itis a valid combination of operators, literals and variables.
‘Types of operators used in an expression determine its type. For instance, use of arithmetic operators makes it
arithmetic expression.
4 Expressions can be arithmetic, relational or logical, compound etc.
+ In implicit conversion, all operands are converted up to the type of the largest operand, which is called ype
promotion or coercion.
4 The explicit conversion of an operand to a specific type is called type casting and it is done using type conversion
functions that is used as ( )
1.9 STATEMENT FLOW CONTROL
In a program, statements may be executed sequentially, selectively or iteratively. Every
programming language provides constructs to support sequence, selection or iteration.
A conditional isa statement set which is executed, on the basis of result of a condition. A loop is
a statement set which is executed repeatedly, until the end condition is satisfied.
1. Compound Statement
A compound statement represents a group of statements executed as a unit. The compound
statements of Python are written in a specific pattern as shown below :
:
The conditionals and the loops are compound statements, i.e., 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 ate called a block.
© The first line of compound statement, i.e., its header contains a colon (:) at the end of it.
For example :
humt = int (input ("Enter number1"))
num2 = int(input("Enter number1") )
Af nun2 < numa : «<——————. Th colon pans Lend of hacer live
t= num2 * num2
t=t+10 + Tie contained statements within i
indented to the right
print(num2, num, t)2. Simple Statement
Compound statements are mat
jement in Python.
de of simple statements. Any single executable statement is,
simple stat
3. Emply Statement
The simplest statement is the
an empty statement is the pass statement.
It takes the following form :
pass
Wherever Python encounters a pass statement,
statement in the flow of control.
empty statement ie., a statement which does nothing. In Pyth,
’
Python does nothing and moves to next
:
\
1.10 THE IF CONDITIONALS
“The if conditionals of Python come in multiple forms : plain if conditional, i
and if-elif conditionals.
if-else conditional
a ae ;
1.10.1 Plain if Conditional Statement
An if statement tests a particular condition; if the condition evaluates to true, a course-of-actior
is followed i.c., a statement or set-of-statements is executed. If the condition is false, it doe
nothing : |
The syntax (general form) of the if statement is as } |
shown below : |
; Test
if : Caen prise
statement |
[statements] { a
For example, consider the following code fragments eet cls
using if conditionals : .
if grade =='a' :
Print(*Congratulations! You did well")
ifa>b:
print("Ahas more than 8 has")
Print ("Their difference is", (a-b))
1.10. i i :
0. = The if-else Conditional Statement Test fra
is form of if state: Soo
ees ts aa ——— > Body of else
eal ae feds a condition and if the x8 :
7 fe, i
indented below if so : carries out statements | tueChapter 1: PYTHON REVISION TOUR
21
The syntax (general form) of the if-else statement is as shown below :
if :
statement
[statements]
elif :
statement
[statements]
and
if :
statement
[statements]
elif :
statement
[statements]
else :
statement
[statements]
you want to check a condition when control reaches else, i
Be colon) is in Both: the ip
header as well as else line
‘The statements in if-block and else are
indented
, condition test in
Python provides if-elif and if-elif-elseCOMPUTER SCIENCE WITH PYTHON — yj
22
Consider following two example code fragments :
if runs >= 100 : :
print("Batsman scored a century")
elif runs >= 50: .
print ("Batsman scored a fifty")
else: et
print(*Batsman has neither scored a century nor Fifty")
ifnum<@: :
print (num, "is a negative number.")
elif num==0:
print (num, “is equal to zero.
else:
print (num, “is a positive nunber.")
1.3. Write a program that inputs an integer in range 0 - 999 and then prints if the integer entered is a 1/
digit number.
num = int(input(“Enter a number (@..999) : “))
if num<@:
print ("Single digit number is entered")
elif num < 100:
print (“Two digit number is entered")
elif num <= 999:
print("Three digit number is entered")
else:
print(“Invalid entry. Valid range is @ to 999. ")
Sample runs of this program are given below :
Enter a number (0..999) : -3
Invalid entry. valid range is 0 to 999.
eee ae
Enter a number (0..999) ; 4
Single digit number is entered
ee
Enter a number (0..999) : 100
Three digit number is entered
Enter a number (0..999) : 19 ~
‘wo digit number is entered
Enter a number (0,.999) ;
Invalid entry. valid Fange is 0 to 999Chopter I: PYTHON REVISION TOUR 23
1.10.4 Nested if Statements
Sometimes you may need to test additional conditions. For such situations, Python also
supports nested-if form of if. A nested if is an if that has another if in its if’s body or in elif's
body or in its else’s body.
Consider the following example code using nested-if statements :
x= int(input (“Enter first number
y= int(input("Enter second nunber
z= int(input("Enter third number
min = mid = max = None
fx 999: :
print("Znvalid entry. Valid range is @ to. 999.")
else:
if num < 10: :
print("Single digit number is 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 two kinds of loops : for loop and while loop to represent counting loop an
conditional loop respectively. 1
1.11.1 The for Loop
The for loop of Python is designed to process the items of any sequence, such asa list or a stri
one by one.
The General Form of for loop
The general form of for loop is as given below :
for in :
statements_to_repeat
For example, consider the following loop :
for element in [10, 15, 20, 25] :
print(element +2, end =
The above loop would
give output as
WoW 22 27 in
‘© The above-given for loop executes a 5 of statements for each of the el
; ‘equence of statements for e f the elemer
> Te i
‘o keep the count, it uses a control variable (¢/
value an each a ttuses lement in above case) i if
lastly 25,0 NO" Firstly value 10, the mar nth kes 2
n the next value of sequence, 15, then 20E
Chapter 1: PYTHON REVISION TOUR pee
The range( ) based for loop
For number based lists, you can specify range( ) function to represent a list as in :
for val in range(3, 18) :
print(val)
Inthe above loop, range(3, 18) will first generate alist 3, 4, 5,..., 16,17] with which for loop will
work. You need not define loop variable (val above) beforehand in a for loop.
As mentioned, a range() produces an integer number sequence. There are three ways to define a
range :
range(stop) #elements from @ — to stop-1, incrementing by 1
range(start, stop) #elements from start to stop-1, incrementing by 1
range(start, stop, step) #elements from start to stop-1, incrementing by step
© The start value is always part of the range. The stop value is never part of the range. The
step shows the difference between two consecutive values in the range.
© If start value is omitted, it supposed to be 0. If the step is omitted, itis supposed to be 1.
Consider some examples of range( ) as given below :
range(7) @,1, 2,3,4,5,6
range(5, 12) 5, 6,7, 8,9, 10, 11
range(5, 13, 2) 5, 7,9, 11
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 :
Write a program to print cubes of numbers in the range 15 to 20.
for i in range(15, 21):
print("Cube of number", i, end=' ')
print("is", i +3)
Cube of number 15 is 3375
Cube of number 16 is 4096
Cube of number 17 is 4913
Cube of number 18 is 5832
Cube of number 19 is 6859
Cube of number 20 is 8000
) 1.7 Write a program to print square root of every alternate number in the range 1 to 10.
rogrr
m for iin range(1, 10, 2) :
nrint("eauane nant of". i. "is". (i **0.5))COMPUTER SCIENCE WITH PYTHON — yy 7
26
A while a will repeat the instructions within itself as long a,
p is a conditional loop that ill repes a6
i is
ditional remains true (Boolean True or truth value ruc) a
conditiona ains
‘The general form of Python while loop is ¢
while :
Joop-body
where the loop-body may contain
empty statement (ie., pass statement). Thi
true. When the expression becomes false, the
loop-body.
a single statement or multiple statements or an
loop iterates while the logical Expression evaluates to
program control passes to the line after the
P 1,8 — Write a program that multiplies two integer numbers without using the * operator, using repeated)
addition.
nl = int(input(“Enter first number :"))
n2 = int (input (“Enter second number :"))
product=0 =
count =n1 Ww
while count >@:
count = count - 1
product = product +n2
print (“The product of", ni, "and", n2, "is", product)
Enter first number : 4
Enter second number : 5
The product of 4 and 5 is 20
In general, the while loop is used when it i:
times the loop will be executed, but the te
an entry-controlled loop as it has a con
condition.
1.12 Jump STATEMENTS — break AND continue
Python offers two jump statements —
ction break and continue ~ to be
The break Statement
A break statement te
Execution resu:
body of the te
inates the very loop it lies within,
mes at the statement immedi:
; \ediat i
na a ete itely following thePYTHON REVISION TOUR
CChopler 1:
the following figure | MH ctest-contttton + for evar Ay cdequentay 1 |
(Fig. 1.6) explains the statement 1 statenent 1 |
working of a break Af ceondition> : AF : |
statement. break — ae
The following code statement 2 statement 2
fragment gives you an statement 3 a statenent 3 “A
example of a break statement 4 a5 statenent 4 «a
statement = . }
debscee, Figure 1.6 The working of a break statement.
for iin range(1, 11) : *——___ ange (1, 11) will generate a sequence
inter number 1:")) of numbers from 1.10.
inter number 2 :"))
print ("Division by zero error! Aborting!")
break
else:
cea/b
print("Quotient =", c)
print("Program over !")
The above code fragment intends to divide ten pairs of numbers by inputting two numbers a
and b in each iteration. If the number b is zero, the loop is immediately terminated displaying
ion by zero error! Aborting!’ otherwise the numbers are repeatedly input and
message ‘Dit
their quotients are displayed
The continue Statement posted
i ‘inue tement forces the f ie ae |
Unlike break statement, the continue 7 ; ae The continue statement skips
next iteration of the loop to take place, skipping any code in th rest ofthe loop statements.
between. and causes the next iteration of
The following figure (Fig. 1.7) explains the working of continue jthelloop to take, place... “ll
statement :
while : for in :
rest of the statements
in the current iteration statement x
‘ave skipped anu next
iteration begin
statement 1
Af + Af :
continue
|
|
|
statement 2
statement 3 }
statement 4 1
statement 3
statement 4
‘ontinue will cause skipping of statements 2 & 3 |
ave Tops,
1G ie ‘iteration and next iteration will start
inthe current
Eimua 17 The workina of a continue statement.COMPUTER SCIENCE WITH PYTHON -
1.13 MORE ON LOOPS
There are two more things you need to know about loops - the loop else clause and nested loo,
1.13.1. Loop else Statement
Python loops have an optional else
clause is as given below :
clause. Complete syntax of Python loops along with ¢|
for evariables in : while :
statement) statement1
statement2 statement2
else: else:
statement(s) statement(s)
‘The else clause of a Python loop executes when the loop terminates normally, i-e., wl
test-condition results into false for a while loop or for loop has executed for the last value in
sequence; not when the break statement terminates the loop.
Following figure (1.8) shows you control flow in Python loops.
for @:
#Read the next price
if max_price > @:
else :
2. Predict the outputs of the following programs :
(2) count =@
while count < 10:
print (‘Hello’)
count += 2
(© keepgoing = True
x= 100
while keepgoing:
print (x)
X=x-16
if x < 50:
Keepgoing = False
@ x25
while x < 59;
print(x)
© for x in [1,2,3,4 5}:
Print (x) :
O is entered the pro}
()
(i)
@
a
()
a limit amount and a lig
for p in range(1,10):
print(p)
for z in range(-500, 500,100):
print(z)
x=10
yes
for i in range(x - y * 2):
print "se", i)
c=0
for x in range(1@):
for y in range(s):
Ct=1
print(c)
x= [1,2,3]
counter = @
while counter < len(x):
Print (x[counter] *%)
for y inx:
Print(y **% +
counter 451
for x in ‘Lamp:
Print ([Link](x))
ai i alpYTHON REVISION TOUR
Chopter ?
) xetone (1) x="apple, pear, peach, grapefruit’
. y='two! y=[Link](, ')
counter = @ for ziny:
while counter < Len(x)? if z<'ntt
print(x[counter], y[counter]) print([Link](z))
counter += 1 else:
print([Link](z))
(m)x="apple, pears peach"
y=[Link](", ")
forziny:
print(z)
4. Find and write the output of the following python code : [CBSE D 2015]
for Name in ["Jayes', ‘Ramya’, ‘Taruna’, "Suraj’] :
print (Name)
if Name[@]
break
else:
print (‘Finished!")
print (‘Got it!')
4. How many times will the following for loop execute and what's the output 2
() for i inrange(-1,7, -2): (i) for i in range(1,3,1):
for j in range (3): for j in range(i+t):
print(1, j) print(*)
Is the loop in the code below infinite ? How do you know (for sure) before you run it 2
5
while n< 10:
m=n-1
n=2*n-m
print(n, m)
Type C : Programming Practice/Knowledge based Questions
1. Write a program to print one of the words negative, zero, or positive, according to whether variable x is
less than zero, zero, or greater than zero, respectively.
Write a program that returns True if the input number is an even number, False otherwise.
Write a Python program that calculates and prints the number of seconds in a year.
Write a Python program that accepts two integers from the user and prints a message saying if first
number is divisible by second number or if it is not.
Write a program that asks the user the day number in a year in the range 2 to 365 and asks the first day
of the year - Sunday or Monday or Tuesday etc. Then the program should display the day on the
day-number that has been input.10.
i.
COMPUTER SCIENCE WITH PYTHON _
itten in feet as an argumer
inction that accepts a length writ net
rare this length written in inches, Write a second function that asks the user fora sepber of feet
eum this valve, Write a thitd fanction that accepts a number of inches Eon tsps th 0 the %
Use these three functions to write a program that asks the user for a num! 8 them
corresponding number of inches.
Write a program that reads an integer N from thi i
umbers from N to (2"* N) if N is nonnegative. If N is a negative number,
numbers from (2 * N) to N. The starting and ending points are included in the sum. ’
Write a program that reads a date as an integer in the format MMDDYYYY. The program will ca)
function that prints print out the date in the format , .
Sample run :
‘One foot equals 12 inches. Write a fu
1 keyboard computes and displays the sum of
then it’s the sum of q.
Enter date : 12252019
December 25, 2619
Write a program that prints a table on two columns ~ table that helps converting miles into kilometres. |
Write another program printing a table with two columns that helps convert pounds in kilograms,
Write a program that reads two times in military format (0900, 1730) and prints the number of hou
and minutes between the two times.
A sample run is being given below :
Please enter the first time : 0900
Please enter the second time : 1730
8 hours 30 minutes2
2.1 Introduction
2.2 Strings in Python
2.3. Lists in Python
2.4 Tuples in Python
2.5. Dictionaries in Python
2.6 Sorting Techniques
INTRODUCTION
The purpose of Revision Tour chapters is to brush up all the concepts you have learnt in class XI.
The previous chapter — Python Revision Tour I ~ covered basic concepts like : Python basics,
Data handling, and control flow statements. This chapter is going to help you recall and brush
up concepts like Strings, Lists, Tuples and Dictionaries.
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).
[] e.g., to access the first character g
‘the index of first character is 0,
ame is storing “PYTHON”,
(), i.¢., to dete
ras ", line 1, in
name[0] ='p!
TypeError: ‘str’ object does not support item assignment
2.2.2 Traversing a String
Traversing refers to iterati
a ig refers to iterating through the elements of a string, one chai ‘
averse through a string, you can write a loop lik ed
e:
code = “Powerful”
for ch in code :
print (ch, ~, end=* *)
The above code will print :
PrO~Wmen rage
2.2.3. String Operators
In this section,
this section, you'll be learnit
strings in multiple ways, 'ng t© work with various operators th
‘Ors that can be used to maniChopter 2 : PYTHON REVISION TOURUI
1, Sting Concatenation Operator +
‘The + operator creates a new string by joining the two operand strings, eg,
"power" + “Ful”
will result into
‘powerful
Caution |
The + operator has to have both operands of the same type either of number types (for
addition) or of string types (for multiplication). It cannot work with one 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, i.,, as
number * string or string * number, where string operand tells the string to be replicated and
number operand tells the number of times, it is to be repeated; Python will create a new string
that is a number of repetitions of the string operand.
For example,
Slee
will return
alata!’
Caution |
The * operator has to either have both operands of the number types (for multiplication) or ont
string type and one number type (for replication). It cannot work with both operands of strin;
types.
3. Membership Operators
There are two membership operators for strings (in fact, for all 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. retums True if a character or a substring does not 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, i.e.,
in
not in
Now, let's have a look at some examples :
>>> "a! in “heya”
True
>>> "Jap" in "heya"
False>>> "Jap" in "Japan"
False
>>> sub = "help"
False
>>> sub2 not in string
True
>>> string = "helping hand
>>> sub2 ="HELP*
>>> sub in string
True
>>> sub2 in string
False
>>> sub not in string
False
4. Comparison Operators
Python's standard comparison operators i, all relational operators (<, <=, >, >=, =, !=, ) appl
to strings also. The comparisons using these operators are based on the stand
character-by-character comparison rules for ASCII or Unicode (i.e., dictionary order). Thus,
can make out that :
will give True
will give True
will give True
will give True
will give False (letters? case is different)
will give True (letters? case is different)
String comparison principles are :
© Upper-case letters are considered smaller than the lower-case letters,
Determining ASCII/Unicode Value of a Single Character
Python offers a built-in function ord( ) that takes a
single charact id returns
corresponding ASCII value or Unicode value : : cute
ord() #returns ASCII value of passed character
BL opposite of ora ) function is chr(), i, while ord() returns the ASCII value of a characte!
le te d init it a
aoe 'e ASCII value in integer form and returns the character corresponding to
The general syntax of chr( ) function is :
chr() # Gives character corresponding to Passed ASCII
# value given as integerChopler 2 : PYTHON REVISION TOUR. 45
Consider these examples :
>>> ord(‘A’)
65
>>> ord(ua)
65
>>> chr(65)
w
>>> chr(97)
o
2.2.4 String Slices
The term ‘string slice’ refers to a part of the string, where String Slice refers to part of a
strings are sliced using a range of indices. That is, for a string string containing some conti-
eae : guous characters from the
say name, ifwe give namel n:m]wheren and mare integers Us
and legal indices, Python will return a slice of the string by
returning the characters falling between indices » and m :
starting at 1, 1+ 1, +2 ...till m — 1.
Following figure (Fig. 2.2) shows some string slices using the
string :
helloString ="Hello World” :
helLestringt 6:30] helosteingt6:]
eencers [Te [i [o] [lel ]é ounces [HTe[ i] To] [wlelr[i]@
nex [0 123 45 6 7 8 9 10) index [0 123 45 67 8 9 10
ey Pee) edhe eer th
first lost first lest
heldosering[3:-2]
ounces [HTeT Te] [w]e] +] t]4 craracrers [He] iT io] [wle]-] ila)
ier [0 1 2345 67 8 9 10] index [0 123 5 67 8 9 10
first last first lest
hellostring{ :5]
Figure 2.2 String Slicing in Python.
Interesting Inference
Using the same string slicing technique, you will find that
© for any index n, s[:n] + s{n:] will give you original string s.
This works even for 1 negative or out of bounds.
Consider the string namely word storing ‘amazing’.
>>> word[3:], word [:3]
“zing ‘ama‘COMPUTER SCIENCE WITH PYTHON
>>> word[ :3] +word[3:]
‘amazing!
>>» word[:~7], word [-7:]
“ ‘amazing"
>>> word[:~7] + word[-7:]
‘amazing’
ici in side the be Fe
© Index out of bounds causes error with strings but slicing a string outside the bounds d
not cause error.
"Hello" Wit eas err becuse 5 sina
int jn index-out of bounds, for string "Hello"
?
But if you give
" One limit is outside the bounds
are (length of Hello is 5 and thus valid
print (s[4: 8]) indexes are 0-4)
print (s[5 : 10])
A __. Bath limits are outside the bounds
the above will not give any error and print output as :
© ompry string
ie, 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 st
manipulation methods that are being discussed below can be applied to strings as per follo
syntax :
. ()
For instance, if you have a string namely str= “Rock the World”
and you want to find its lengtl
you will write the code somewhat like shown below :
>>> str = "Rock the World."
>>> str. length( )
15 eee
>>> str2 = "New World”
>>> [Link]( )
9
see the string object is ste and
‘method name is Length( ),
Do you know that followin
extensively : Instagram,
and many others ?
iB websites and web app
lications have used P
Dropbox, Google, Netflix, i
Spotify, Quora, Reddit, Facebook,HON REVISION TOUR+I 47.
Chapter 2 : PYT
Table 2.1 Pythons built-in n string manipulation methods
pe ee
[gers capitalize() lized.
|
Returns a copy of the string with its first character capi
Example
>>>" d love my India’.capitalize()
1 love my India
Jestr> find 5 (subl, ‘Retums the lowest index in the vtring where the substring sub is found
start[, end]]) within the slice range of start and end. Returns -1 if sub is not found.
Example
"it goes as - ringa ringa roses’
>>> sub = 'ringa’
|
a
|
|
| >>> string:
| >>> [Link](sub, 15, 22)
|
|
a
>>> [Link](sub, 15, 25)
19
| .isalnum() Returns True if the characters in the string are alphanumeric (alphabets or
numbers) and there is at least one character, False otherwise.
.isalpha() Returns True if all characters in the string are alphabetic and there is at least
‘one character, False otherwise.
| [Link]() Returns True if all the characters in the string are digits. There must be at
least one digit, otherwise it returns False.
| Examples |
; >>> string: “abc123" |
| >>> string2 = ‘hello’ |
>>> string3 = "12345" |
>>> string4 =
| >>> [Link]() { >>> [Link]() } >>> [Link]()
|
| |
| | True False False |
| | >>> string2-dsalnum() >>» [Link]() } >>» [Link]() |
| | True True False ]
| | >>> [Link]() >>> [Link]() : >>> [Link]()
| | True False True
[p> [Link]() } >>> [Link]() : >>> [Link]()
(False False False
isspace() Returns True if there are only whitespace characters in the string . There
must be at least one character. It returns False otherwise.
Example
# stores three spaces
# an empty string
>>> string. isspace()
True
>>> string2. isspace()
False= 48 a
oe rl i re lowercase. There must
ae = an the string a1
True if all cased characters in a
ing are uppercase and requires
| Tests whether all ase characters in the sring are MPP Ao ee
[festr>-tsupper() that there be at Teast one cased character. a
. inti s. Title case is any text with most of the
Ret if the string is in title case. . string is
[ernie me Tne Ee Pala |
| | title case,
| Examples :
| >>> stringl 'HELLO”
| | 599 string] = ‘hello’ >>> string2 ="There’
| — eo ea a a ae
| ean es peter >>> stringl-isupper()
| Devel True
i 339 string? 4slower() >>> [Link]()
| False False
| >»> [Link]() >>> [Link]()
| False Gre ;
| >>> To Be Or Not To Be” istitle()
| True
| >>> “To Be or Not to Be”. istitle()
| False :
| a
| .lower() Returns a copy of the string converted to lowercase.
| Example
| >>> [Link]() #stringl = "HELLO" [
| ‘hello
.upper() Returns a copy of the string converted to uppercase.
| Example
>>> string] upper() string! = "hello"
"HELLO
.title() Returns a titlecased version of the str
COMPUTER SCIENCE WITH PYTHON ~ yy,
‘tro, startasith(prefix[,
start[, end]])
.endswith(suf-
fix[, start[, end}])
ing where words start with an
Uppercase character and the remaining characters are lowereee |
Example
>>> “My name is serious" title()
‘My Name Is Serious’
Returns True if string starts with
False. the argument prefix, otherwise returns
Returns True if the stri i ‘1
False, © string ends with the specified suffix, otherwise returnsChop
lr 2 : PYTHON REVISION TOUR! ‘ a5
For both startswith( ) and endswith( ), the start and end are optional arguments
that specify the string positions to be compared. If given, only the string between
the start to end indexes is compared.
Example
>>> nm= "My name is seriously funny"
>>> nm startswith ("My") >>> nm endswith("funny")
True True
>>> [Link]("funny", 5, 11)
False
>>> [Link]("funny", 5)
True
>>> nm,startswith("My", 5)
False
>>> nm, startswith("ser", 10)
False
>>> nm, startswith("ser", 11)
True
-.swapcase()
Returns a copy of the string with uppercase characters converted to
lowercase and vice versa.
Example
>>> “Hello World". swapcase()
“HELLO wORLD"
>>> "Hello World". swapcase().swapcase()!
"Hello World"
| .partition(sep)
Splits the string at the first occurrence of argument sep, and returns a
3-tuple containing the part before the separator, the separator itself, and the part
after the separator.
If the separator is not found, it returns a 3-tuple containing the string itself,
followed by two empty strings.
Example
>>> nm = “My name is seriously funny"
>>> [Link](*is*) — <——— Ven hen separators found
(*My name ', ‘is’, ‘seriously funny’)
When given separator is not
>>> [Link](‘ok") — found inthe sting
(My name is seriously funny’, '', '')
|. count (subl,
Sturt, en} :
Returns the number of non-overlapping occurrences of substring sub in the range
[start, end] of the given string . The start and end are optional arguments and
if not given, the whole string is considered for finding and counting the given
substring sub.
>>> nm. = “To Be or Not to Be”
>>> nm. count ("Be")
2 Mle string is searched for
>>> nm, count ("Be", 7)
Do The string with 7H index omvards is searched for
>>> [Link]("Be", 7, 11)
e
+ ares,
The string between the range of indexes 7 to 11 is searched for
Some cases, it is not necessarily true that [Link]().swapcase() —= s.COMPUTER SCIENCE WITH PYTHON,
> with leading characters removed.
it removes the leading whitespaces.
to specify a set of characters to be
Returns a copy of the string specil
The chars argument is a string -Istrip({chars])
> with trailing characters removed.
wes the leading whitespaces.
fying the set of characters to be remoy,
ions of its values are stri
‘stro .rstrip([ehars))
Example ; ‘The’, ‘Th’, ‘he’, ‘Te’ , A
>>> string2 = ‘There’ and their reversed strings are
"There! matched, if any of these found, i
ee smroved front the left of the string
Ghee the!) 4 removed from ig
peered eee “The’ found , hence removed
‘ret
>>> "saregamapadhanisa".1strip( "tears" )
‘gamapadhanisa’
>>> [Link](‘care’)
tr
>>> "saregamapadhanisa".rstrip( "tears" )
‘saregamapadhani!
Program that reads a line and prints its statistics like :
| Number of uppercase letters
Number of lowercase letters:
Number of alphabets :
Number of digits:
Line = input( “Enter a line
Jowercount = uppercount = @
digitcount = alphacount = @
for a in line :
if [Link]() :
lowercount += 1
elif [Link]() ;
uppercount += 1
elif [Link]() :
digitcount +1
[Link]() ;
alphacount += 1
print "Nunber of uppercase letters
print (“Number of low
. ercase 1
Print("Nunber of alphabets :-tten®
Print “Number of digit.
Enter a line : Hello 123, zIpPY zippy
Number of uppercase letters : 7
Number of lowercase letters : 11
Number of alphabets : 1g
Number of digits : 3
» Uppercount)
» lowercount)
» alphacount)
» digitcount)a
A
eek
|
|
|
3s PYTHON REVISION TOUR.
al 51
UsTS IN PYTHON
is a standard data type of Python that can store a sequence of values belonging to any
Alist
type. The Lists are depicted through square brackets, ¢.¢., following are some lists in Python :
0 Hist with nomender, empty list :
[23] HList of integers
1, 2.55 3-79) #List of nunbers (integers and floating point)
tart, 'e) # List of characters
[a 1,0, 3.5, zero] # List of mixed value types
Tone’, Two’, ‘Three'] # List of strings
Lists are mutable (i.c., modifiable) ie., you can change elements of a list in place. List is one of
the two mutable types of Python ~ Lists and Dictionaries are mutable types ; all other data types
‘of Python are immutable. 9
23.1 Creating Lists
To create a list, put a number of expressions, separated by commas in square brackets. That is,
to create a list you can write in the form given below :
t=O
L=[value, ...]
This construct is known as a list display construct.
Creating Empty List
The empty list is [ ]. You can also create an empty list as =
L=list() #It will generate an expty list and name that list as L-
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 :
L= List()
where can be any kind of sequence object including strin
Consider following examples :
, tuples, and lists.
>>> 11 = list(hello') #ereating list from string
>it
(hr, 'e, ‘o]
note (W,'é,'r,'t, ¥)
>>> 12= list(t) fcreating list from tuple
>> 12
[We "r,t 'y]
Creating List from Keyboord Input
You can use this method of creating lists of single characters or single digits via keyboa
Consider the code below :
>>> 11 = List( input(‘Enter List elements:
Enter list elements: 234567
oi
[2,34
rd input.
)
3,"P52
string even though we entered digit,
‘¢ the method given below.
t())2 as shown below :
Notice, this way the data type of all characters entered it
To enter a list of integers through keyboard, you ©
thod to input lists is eval(inpu'
st to be added :"))
list)
when you execute it, it will work somewhat like =
enter list to be added : (67, 78, 46, 23]
List you entered : [67, 78, 46, 23]
Most commonly used me
List = eval (input ("Enter 1i
print("List you entered :"
2.3.2 Lists vs. Strings
Lists and strings have lots
summarize the similarities an
in common yet key differences too. This section is going tg
d differences between lists and strings.
2.3.2A Similarity between Lists and Strings
Lists are similar to strings in following ways :
© Length Function len(L) returns the number of items (count) in the list L.
© Indexing and Slicing
L[i] returns the item at index i (the first item has index 0), and
L[é] returns a new list, containing the objects between i and j.
© Membership operators
Both ‘in’ and ‘not 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
or not, and not in does the opposite.)
© Concatenation and Replication operators + and *
The + operator adds one list to the end of another. The * operator repeats a list
© Accessing Individual Elements >>> vowels = ['a', 'e’, ‘i’, ‘0, 'U]
ie strings, the individual elements of a >>> vowels [0]
list are accessed through their indexes. ‘a
Consider adjacent examples : >>> vowels[4]
2.3.28 Difference between Lists and Strings :
The lists and strings are different from one another in . asi
following ways :
© Storage Lists are stored in memory exactly like stri
their objects are larger than others, io
instead of single charact i
except that because some
they store a refe inde*
ter as in strings. ference at each
Strings are not
mutable, while li
elements of a string in bu
following statement is full
Li] = >> vowels[@] =")
>>> vowels Notice, it changed the element
[aye "t,o, in lace: changed oA"
and ‘e" changed to 'E') no new P NOTE al
>>> vowels[-4] = list created ~ because Lists are
MUTABLE. lists are similar to strings in
many ways like indexing, slicing
and accessing individual
elements but they are different
>>> vowels
[A,'E, i,’ U)
2.3.3 list Operations
: in the sense that Lists are
In this section, we shall talk about most common list mutable while strings are not.
operations, briefly. ceecenaas
2.3.3A Traversing a List
Traversing a list means accessing and processing each element of it. The for loop makes it easy
to traverse or loop over the items in a list, as per following syntax :
for - in
:
process each itemhere
For example, following loop shows each item of a list L in separate lines :
LLP, 'y, ‘ty Hy 0")
forainL:
print(a)
The above loop will produce result as :
P
posa<
2.3.3B Joining Lists
The concatenation operator +, when used with two lists, joins two lists and returns the
concatenated list. Consider the example given below :
>>> Ist1=[1, 4, 9]
>>> Ist2 = [6, 12, 20]
>>> Ist + 1st2
[1, 4, 9, 6, 12, 20]
The + operator when used with lists requires that both the operands must be of list types.
23.3C Repeating or Replicating Lists
Like strings, you can use * operator to replicate a list specified number of times, eg.,
(considering the same list Ist1 = [1, 3, 5] )
>>> 1sti*3
0,4, 9,1, 4,9,1, 4,9]
Like strings, you can only use an integer with a * operator when trying to replicate a list.COMPUTER SCIENCE WITH PYTHON - yg
é
2.3.30 Slicing the Liss tracted out. You can use indexes of j
List slices, like string slices are the sub part of a list ex!
elements to create list slices a5 pet following format :
seq=L{start:stop]
Consider the following example :
>>> Ist =[10, 12, 14, 20, 22, 24, 30, 32, 34] oo Lint Bond
es fhe lng
eles in range 3 onwards <30
[20, 22, 24]
>>> Ist =[10, 12, 14, 20, 22, 24, 30, 32, 34]
>>> Ist [3:30]
[20, 22, 24, 30, 32, 34] Giving lower limit much lower, but
>>> Ist [-15 :7] Python returns elements from list
[10, 12, 14, 28, 22, 24, 30] falling in range -15 onwards <7
Lists also support slice steps too. That is, if you want to extract, not consecutive but every ol
element of the list, there is a way out - the slice steps. The slice steps are used as per following
format :
seq = L[start:stop: step]
Consider some examples to understand this.
>>> Ist
[1e, 12, 14, 20, 22, 24, 30, 32, 34] Include every 2nd element, i.e,
>>> Ist[@ : 10 : 2] skip 1 element in between. Check
[10, 14, 22, 30, 34] resulting list slice
>>> Ist[2 : 10 : 3] «_
[14, 24, 34] Include every 3rd element, i.e.,
skip 2 elements in between
Using Slices for List Modification
>>> L= ["one", "two", "THREE"]
>>> L[@:2] =[0,1]
>>>
(2, 1, "THREE"] _Uke strings, in list slices, you
“Bive start and stop beyond Il!
>>>L=["one", "two", - (of list and it won't :
>>> Ufa] owes 2 “THREE"] “Indexérror, rather it will retul
ae the elements falling bet
> Pecified boundaries.
["a", "THREE"] =Cchopler 2 : PYTHON REVISION TOUR«t 55 &
2.3.4 List Manipulation
‘You can perform various operations on lists like : appending, updating, deleting etc.
‘Appending Elements to a List
‘You can also add items to an existing sequence. The append() method adds a single item to the
end of the list. It can be done as per following format :
[Link]( item)
Consider some examples :
>>> Asti = [10, 12, 14]
>>> [Link](16)
>>> Ast, The element specified as argument to append( ) is
[20, 12, 14, 16] aad the end of existing lst
Updating Elements to a 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 :
L [index] =
Consider following example :
>>> Ist1 = [1@, 12, 14, 16]
>> eaf2] «26 rora aeet=
>>> Ist. Display the list to see the updated list.
[10, 12, 24, 16] <.
Deleting Elements from a List
You can also remove items from lists. The del statement can be used to remove an individual
item, or to remove all items identified by a slice.
Itis to be used as per syntax given below :
del List [ ] # to remove element at index
del List [ : ] _ # to remove elements in list slice
eg,
>>> del Lst[10:15] <——————___etete all elements between indeses 10 to 15 in list
>>> Ist namely Ist. Compare the result displayed below
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 17, 18, 19, 20]
Ifyou use del only e.g., del Ist, it will delete all the elements and the list object too.
After this, no object by the name Ist would be existing.
You can also use pop( ) method to remove single element, not list slices.
The pop( ) method is covered in a later section, List Functions.2.3.5 Making True Copy of @ List does not make a copy. Instead, assigy
=) on lists )
; ignment operator (=) 0 led shallow copy)-
Sa ries patil to the one list in memory (cal
makes the two varial
“rad! | ‘blue’ _| “reer
: colors ae — sual
colors = [’red, ‘blue’ ‘greer"] list 0
TEEN:
colors ——> ‘blue’ | ‘ar al}
list
becolors — ##Does not copy the , :
So, if you make changes in one list the other list wi report those changes because
i I also report those chi
, o
two listsnames are labels referring to same list because ’~ copied the reference not the
ni a
list.
To make b true copy of list colors ie, an
colors———» [__‘red’_| ‘blue’ | ‘green’
list 0 1 2
independent list identical to list colors you a
should create copy of list as follows : oS [ of i or 7
list
belist(colors) ss+esrere®
Now colors and b are separate lists (deep copy).
2.3.6 List Functions
Python also offers many built-in functions and methods for list manipulation. These can be
applied to list as per following syntax :
.()
1. The index method
This function returns the index of first matched item from the list.
List index (- )
For example, for a list L1 = [13, 18, 11, 16, 18, 14],
29> [Link] (18) +—_retums the index of fist value 18, even if
1
there is another value 18 at index 4,
However, if the given item is not in the list, it raises exception value Error
2. The append method
The append( ) method adds an item to the end of the li
A ist. It works as per followi tax:
List. append(
- ) oe
~ Takes exactly one element and returns no value
For example, to add a new item “ ce i
, yellow” to a list containin, colou ite :
>> colours = [ ‘red’, ‘green’, ‘blue'] a ees
>>? colours. append('yellow’)
>>> colours
See the item got added At the end of the list
Cred, ‘greent, ‘blue’, ‘yellow
The append( ) does not return the new ist, just modifies the original,Chopter 2 : PYTHON REVISION TOUR«I a
3, The extend method
Theextend() method is also used for adding multiple elements (given in the form of a list) to a list
The extend( ) function works as per following format :
[Link](
)
= Takes exactly one element (a list type) and returns no value
That is extend ) takes a list as an argument and appends all of the elements of the argument list
to the list object on which extend ) is applied. Consider the following example :
>>> ti=['a, by 'c]
poot2=[d,'e] Extend the list 1, by adding all
elements of «2
>>> [Link](t2)
pot ‘See the elements of list (2 are
A added atthe end of ist 11
[a B, "ey", 'e]
pote
ra, 'e] Ae But list 2 remains unchanged.
Difference between append( ) and extend{ ) methods
While append( ) function adds one element to a list, extend( ) can add multiple elements from a
list supplied to it as argument.
4. The insert method
The insert( ) function inserts an item at a given position. It is used as per following syntax :
[Link]( , - )
= Takes two arguments and returns no value.
The first argument is the index of the element before which the second argument
- is to be added. Consider the following example:
>>d>t1=['a,'e, 'U]
>>> tleinsert(2, ‘i')
>>>t1
Cat, 'e', 'L,'U'] ~~ ee element ‘inserted at index 2
5. The pop method
The pop( ) is used to remove the item from the list. It is used as per following syntax :
# )
~ Takes one optional argument and returns a value — the item being deletedCOMPUTER SCIENCE WITH PYTHON
‘on in the list, and return it. If no ing
ment from the given positit rt Conalder some examples
Thus, pop() removes an eT omg the last item in tf
specified, pop( ) removes a
>>> tl a
(ik, ‘ay 'e, "Ey Pas oe
Remove element at index se
ee oe ome clement and store it in elet
ae ae The removed element
poo tr
te ¥,3.'¢,0) List after removing first element
‘aye’, “P,P ds
>>> ele2 = [Link]()
>>relez <——— Qo index specified, it will remove
w the last element
port
Casey
Pd]
The pop( ) method raises an exception (runtime error) if the list is already empty.
6. The remove method
The remove( ) method removes the first occurrence of given item from the list. It is used as
following format :
[Link] ( )
~ Takes one essential argument and does not return anything
The remove( will report an error if there isno such item in the list. Consider some examples:
>>otis[a,'e,
>>> tl remove('a')
>>> t1 4 First occurrence of ‘a’ is removed ‘from the list
[ep a,
>> [Link](‘p')
>>>t1 4 First occurrence of ‘pis removed from the list
Cet, ‘a, 'a,'q,'p]
2G, ‘a, 'q, ‘P']
»'B']
7. The clear method
[Link]( ;
For instance, if you have a list L1 as
>>> L1= (2, 3, 4,5]
>>> [Link]( )
>>>L1
[] << ow the 11 is an empy tis
Unlike del sta
After clear( ), the list obj
+ till remove all the items from lst U1
tement, clear( ) removes only
: the '
ject still exists as an empty isn ements and not the list elementChopter 2 : PYTHON REVISION TOUR-I ey
8. The count method
This function returns the count of the item that you passed as argument. If the given item is not
jin the list, it returns zero.
It is used as per following format :
List. count (
- )
For instance, for a list L1 = [13, 18, 20, 10, 18, 23]
>>> [Link] (18)
p< Pais 2 a there are to items with value 18 inthe list,
>>> LA. count (28)
9
- >> [Link]()
>>>tl +<—_—— The reversed list
(P,'d,'a', ‘dH, 'e']
10. The sort method
The sort( ) function sorts the items of the list, by default in increasing order. This is done “in
place”, i.e, it does not create a new list.
It is used as per following syntax :
[Link]()
For example,
pooti=[e,','d,'a, dy 'P')
>>> [Link]()
>>> tl <—@—OOS™ Sorted list in default as
‘ds 'd)
wscening order
fa,'e,
Like reverse( ), sort( ) also performs its function and does not return anything.
To sort a list in decreasing order using sort( ), you can write :
>>> [Link] (reverse = True)COMPUTER SCIENCE WITH PYTHcy
2.4 TUPLES IN PYTHON
The Tuples are depicted through pare
tuples in Python :
ntheses ie, round brackets, €g., following are «°
4 tuple with no member, empty tuple
4 ) # tuple with one member
; le of integers
oe qc of numbers (integers and floating point)
# tuple of characters
(a, 1,°0, 3.5, "zero’) _-# tuple of mixed value types
Cone’, "Two, “Three’) # tuple of strings
Tuples are immutable sequences i.e, you cannot change elements of a tuple in place.
2.4.1 Creating Tuples :
To create a tuple, put a number of expressions, separated by commas in parentheses. Thats
create a tuple you can write in the form given below :
T=Q
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 with a single element is tricky because if
you just give a single element in round!
brackets, Python considers it a value only, e.g, :
>oot= (1)
root
1 <1) 0s treated as an integer expression,
‘ence t stores an integer 1, not a tuple
To construct a tuple with one ele; jt
mer 1
Toca nt just add a comma after the single element as shov
>o>te3, «To create a oneclement ple, make
Bee ‘Sure to add comma at the end
(3,) )
where >> t1 = tuple(‘hello') ficreating tuple froma string
poota
(tt, es Ty "To
p> be fW, e's "ts YD
>>> t2= tuple(L) # creating tuple froma list
>>> t2
(ws "ey Pst '¥)
Creating Tuple from Keyboard Input
You can use this method of creating tuples of single characters or single digits via keyboard
input. :
Consider the code below :
t1 = tuple(input(‘enter tuple elements:'))
Enter tuple elements : 234567
>>> tl
(2,35
"6, '7)
But most commonly used method to input tuples is eval(input( )) as shown below :
tuple = eval (input ("Enter tuple to be added:"))
print (“Tuple you entered :", tuple)
when you execute it, it will work somewhat like :
Enter tuple to be added: (2, 4, "a", "AIkIL, "[3, 4])
Tuple you entered : (2, 4, "a", "hjkjl", (3, 4])
2.4.2 Tuples vs. Lists
Tuples and lists are very similar yet different. This section is going to talk about the same.
2.4.24 Similarity between Tuples and Lists
Tuples are similar to lists in following ways :
© Length Function len(T) returns the number of items (count) in the tuple T.
© Indexing and Slicing
T[i] 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 not in does the opposite.
© Concatenation and Replication operators + and *
The + operator adds one tuple to the end of another. The * operator repeats a tuple.COMPUTER SCIENCE WITH PYTHON _
© Accessing Individual Elements
The individu
square brackets. Consider th
>>> vowels = ("
>>> vonels[4]
v
>>> vowels[- 1]
‘u
id thi
nts of a tuple are accessed thy
oS cae he following examples :
o', 'U)
rough their indexes given
i between Tuples and Lists d
Aon eee a lists are. You cannot change individual elements of a tuple in plagg
Share tatementis fully valid for lists (BUT not for tupleg}
but lists allow you to do so. Thats, following s
If we have a list L and a tuple T, then
L[i] = element tis valid
is VALID for Lists. BUT
T[i] = element #is 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.3A Traversing a Tuple
Traversing a tuple means accessing and processing each element of it. The for loop makes ites
to traverse or loop over the items in a tuple, as per following syntax :
for
- in :
process each item here
For example, following loop shows each item of a tu
T=(P,'U, ‘ry 'e)
for aint:
print(T[a])
ple T in separate lines :
The above loop will produce result as :
P
u
:
e
2.4.3B Joining Tuples
The + operator, the con,
Consider the example gi
(1, 3, 5)
(6, 7, 8)
>>> tpl + tpl2 4
(1, 3,5, 6, 7, 8)
catenation oj
erator,
ven below : when used with two tuples,chapter 2: PYTHON REVISION TOUReI 63
PORTANT,
sometimes you need to concatenate a tuple (say ipl) with another tuple containing only one
clement. In that case, if you write statement like :
>>> tpl + (3)
Python will return an error like :
Typetrror : can only concatenate tuple (not “int") to tuple
‘The reason for above error is: a single valu in () is treated as single value not as tuple. That is,
expressions (3) and (a’) are integer and string respectively but (3,) and (‘a’,) are single element :
tuples. Thus, following expression won't give any error :
>>> tpl + (3, )
2.4.3C Repeating or Replicating Tuples
Like strings and lists, you can use” operator to replicate a tuple specified number of times, e.g.
>>> tpl *3
(1,3, 5, 25 3) 5) 4 3, 5)
Like strings and lists, you can only use an integer with a * operator when trying to replicate a
tuple.
2.4.3D Slicing the Tuples
Tuple slices, like list-slices or string slices are the sub part of the tuple extracted out. You can use
indexes of tuple elements to create tuple slices as per following format :
seq=T[start:stop]
Recall that index on last limit is not included in the tuple slice. Consider the following example :
soo tpl = (10, 12, 14, 20, 22, 24, 38, 32, 34)
>>> seq= tpl [ 3:-3]
>>> seq
(20, 22, 24)
If you want to extract, not consecutive but every other element of the tuple, there is a 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.
>>> tpl
(10, 12, 14, 20, 22, 24, 30, 32, 34)
clude every 2ul element, skip Cement in
yoo tpl{@ 10:2] erwwen. Check esting tuple slice
(10, 14, 22, 30, 34)
Inctule every Sd element, be
goo tpl[2 $283] ee 2 eat In beter
(14, 24, 34)
[No start and stop given. Only step is given as 5
poo tpl [2 3] ra is, fro tei le, pl ery
(10, 28, 3@) Srd element for the tupleCOMPUTER SCIENCE WIIH PYTHONS
2.4.3E Unpacking Tuples
Creating a tuple from a set of
values from a tuple’s elements is cal
Unpacking is done as per syntax :
values is called packing and its reverse, ic, creating indivigy,
led unpacking.
, , , 4
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 :
t= (1, 2,'8, 8)
The length of above tuple is 4as there are four elements in it. Now to unpack it, we can write;
WX, y, Zab
prints "=") X) "5 Yo "os 2)
The output will be :
1-2-A-B
2.4.4 Tuple Functions and Methods
1. The len( ) method
This method returns length of the tuple, i., the count of elements in the tuple.
Syntax: — len()
>>> employee = (‘John’, 1000, 24, ‘Sales')
>>> len(employee)
—_—
4 The len( ) returns the count of elements in the tuple
2. The max( ) method
This method returns the element from the tuple having maximum value.
Syntax: — max()
>>> tpl = (1@, 12, 14, 20, 22, 24, 30, 32, 34)
>>> max(tp1)
——__ ,,.
34 Maximum value from tuple tpl is returned
3. The min( ) method
This method returns the ele
ment from the tuple having minimu:
Syntax: — min() pice
>>> tpl = (10, 12, 14, 20, 22,
>>> min(tp1)
10 <———__
24, 30, 32, 34)
‘Maximum value from tuple tpt is returnedChopler 2 : PYTHON REVISION TOUR.
{The index( ) method
Tt returns the index of an existing element of a tuple,
Syntax: © . index (
- )
poo th = [3, 4 5, 6.0]
>>> th. index(5)
2
But if the given item does not exist in tuple, it raises ValueError exception.
5, The count{ ) function
The count( ) method returns the count of a member element/object in a given sequence
(ist/tuple).
Syntax: .count (