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

120c1a Python Notes

Uploaded by

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

120c1a Python Notes

Uploaded by

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

UNIVERSITY OF MADRAS

BACHELOR OF COMPUTER APPLICATIONS (BCA)


DEGREE PROGRAMME
SYLLABUS WITH EFFECT FROM 2023-2024

Year: I Semester: I
Core-I: Python Programming
120C1A
(Common to B.Sc.-CS, CS with AI, CS with DS, Software Appl.)
Credits 5 Lecture Hours:4 per week
Learning Objectives: (for teachers: what they have to do in the class/lab/field)
 Describe the core syntax and semantics of Python programming language.
 Discover the need for working with the strings and functions.
 Illustrate the process of structuring the data using lists, dictionaries, tuples and sets.
 Understand the usage of packages and Dictionaries
Course Outcomes: (for students: To know what they are going to learn)
CO1: Develop and execute simple Python programs
CO2: Write simple Python programs using conditionals and looping for solving problems
CO3: Decompose a Python program into functions
CO4: Represent compound data using Python lists, tuples, dictionaries etc.
CO5: Read and write data from/to files in Python programs

UNITS CONTENTS

I Introduction: The essence of computational problem solving – Limits of


computational problem solving-Computer algorithms-Computer Hardware-
Computer Software-The process of computational problem solving-Python
programming language - Literals - Variables and Identifiers - Operators -
Expressions and Data types, Input / output.
II Control Structures: Boolean Expressions - Selection Control - If Statement-
Indentation in Python- Multi-Way Selection -- Iterative Control- While
Statement- Infinite loops- Definite vs. Indefinite Loops- Boolean Flag. String,
List and Dictionary, Manipulations Building blocks of python
programs,Understanding and using ranges.
III Functions: Program Routines- Defining Functions- More on Functions: Calling
Value-Returning Functions- Calling Non-Value-Returning Functions- Parameter
Passing - Keyword Arguments in Python - Default Arguments in Python-Variable
Scope. Recursion: Recursive Functions.
IV Objects and their use: Software Objects - Turtle Graphics – Turtle attributes-
Modular Design: Modules - Top-Down Design - Python Modules - Text Files:
Opening, reading and writing text files – Exception Handling.
V Dictionaries and Sets: Dictionary type in Python - Set Data type. Object Oriented
Programming using Python: Encapsulation - Inheritance – Polymorphism. Python
packages: Simple programs using the built-in functions of packages matplotlib,
NumPy, pandas etc.
UNIVERSITY OF MADRAS
BACHELOR OF COMPUTER APPLICATIONS (BCA)
DEGREE PROGRAMME
SYLLABUS WITH EFFECT FROM 2023-2024

Learning Resources:

Recommended Texts

1. Charles Dierbach, “Introduction to Computer Science using Python - A


computational Problem-solving Focus”, Wiley India Edition, 2015.

2. Wesley J. Chun, “Core Python Applications Programming”, 3rd Edition , Pearson


Education, 2016

Reference Books

1. Mark Lutz, “Learning Python Powerful Object Oriented Programming”, O’reilly


Media 2018, 5th Edition.

2. Timothy A. Budd, “Exploring Python”, Tata MCGraw Hill Education Private


Limited 2011, 1 st Edition.

3. John Zelle, “Python Programming: An Introduction to Computer Science”, Second


edition, Course Technology Cengage Learning Publications, 2013, ISBN 978-
1590282410

4. Michel Dawson, “Python Programming for Absolute Beginers” , Third Edition,


Course Technology Cengage Learning Publications, 2013, ISBN 978-143545500

Web resources

1. https://onlinecourses.swayam2.ac.in/cec22_cs20/preview
CONTENTS

UNIT- I
Chapter 1 Introduction 8
1. 1 Fundamentals of Computers 8
1.1.1 The Essence of Computational Problem Solving 14
1.1.2 Limits of Computational Problem Solving 14
1. 2 Computer Algorithms 15
1.2.1 What is an Algorithm? 15
1.2.2 Algorithms and Computers 17
1. 3 Computer Hardware 17
1.3.1 Digital Computing 17
1.3.2 The Binary Number System 18
1.3.3 Fundamental Hardware Components 19
1.3.4 Operating Systems 20
20
1.3.5 Limits of Integrated Circuits Technology: Moore’s Law

1. 4 Computer Software 20
1.4.1 What is Computer Software? 21
1.4.2 Syntax, Semantics, and Program Translation 21
1.4.3 Procedural vs. Object-Oriented Programming 23
1. 5 The Process of Computational Problem Solving 23
1.5.1 Problem Analysis 24
1.5.2 Program Design 24
1.5.3 Program Implementation 25
1.5.4 Program Testing 25
1. 6 The Python Programming Language 26
1.6.1 Introduction to Python 26
1.6.2 Features of Python 26
1.6.3 The IDLE Python Development Environment 27
1.6.4 The Python Standard Library 28
1.6.5 Input and Output Functions 28
1.6.6 How to use Python IDLE? 30
Chapter 2 Data and Expressions 32
2. 1 Literals 32
2.1.1 What is a Literal? 32
2.1.2 Numeric Literals 32
2.1.3 String Literals 33
2.1.4 Control Characters 34
2.1.5 String Formatting 35
2.1.6 Implicit and Explicit Line Joining 35

3
2. 2 Variables and Identifiers 36
2.2.1 What is a Variable? 36
2.2.2 Variable Assignment and Keyboard Input 38
2.2.3 What is an Identifier? 38
2.2.4 Keywords and Other Predefined Identifiers in Python 38
2. 3 Operators 39
2.3.1 What is an Operator? 39
2.3.2 Arithmetic Operators 39
2. 4 Expressions and Data Types 40
2.4.1 What is an Expression? 40
2.4.2 Operator Precedence 40
2.4.3 Operator Associativity 41
2.4.4 What is a Data Type? 41
2.4.5 Mixed-Type Expressions 43
UNIT-II
Chapter 3 Control Structures 45
3. 1 What is a Control Structure? 45
3. 2 Boolean Expressions (Conditionals) 45
3.2.1 Relational Operators 45
3.2.2 Membership Operators 46
3.2.3 Boolean Operators 46
3.2.4 Operator Precedence and Boolean Expressions 48
3.2.5 Short-Circuit Evaluation 48
3.2.6 Logically Equivalent Boolean Expressions 48
3. 3 Selection Control 49
3.3.1 If Statement 49
3.3.2 Indentation in Python 51
3.3.3 Multi-Way Selection 51
3. 4 Iterative Control 55
3.4.1 While Statement 55
3.4.2 Input Error Checking 57
3.4.3 Infinite loops 58
3.4.4 Definite vs. Indefinite Loops 58
3.4.5 Boolean Flags and Indefinite Loops 58
Chapter 4 Lists 60
4. 1 List Structures 60
4.1.1 What is a List? 60
4.1.2 Common List Operations 60
4.1.3 Python List Methods 61

4
4.1.4 List Traversal 61
4. 2 Lists (Sequences) in Python 62
4.2.1 Python List Type 62
4.2.2 Tuples 62
4.2.3 Sequences 63
4.2.4 Nested Lists 63
4. 3 Iterating Over Lists (Sequences) in Python 66
4.3.1 For Loops 66
4.3.2 The Built-in range Function 67
4.3.3 Iterating Over List Elements vs. List Index Values 71
4.3.4 While Loops and Lists (Sequences) 72
UNIT-III
Chapter 5 Functions 74
5. 1 Program Routines 74
5.1.1 What is a Function Routine? 74
5.1.2 Defining Functions 74
5.1.3 Temperature Conversion Program 76
5. 2 More on Functions 77
5.2.1 Calling Value-Returning Functions 77
5.2.2 Calling Non-Value-Returning Functions 78
5.2.3 Parameter Passing 78
5.2.4 Keyword Arguments in Python 80
5.2.5 Default Arguments in Python 81
5.2.6 Variable Scope 82
UNIT-IV
Chapter 6 Objects and Their Use 84
6. 1 Software Objects 84
6.1.1 What is an Object? 84
6.1.2 Object References 84
6. 2 Turtle Graphics 87
6.2.1 Creating a Turtle Graphics Window 87
6.2.2 The “Default” Turtle 88
6.2.3 Fundamental Turtle Attributes and Behavior 89
6.2.4 Additional Turtle Attributes 93
6.2.5 Creating Multiple Turtles 95
Chapter 7 Modular Design 97
7. 1 Modules 97
7.1.1 What is a Module? 97
7.1.2 Module Specification 97
7. 2 Top-Down Design 98
7. 7.2.1 Developing a Modular Design of the Calendar Year Program 99
5
7. 7.2.2 Specification of the Calendar Year Program Modules 99
7. 3 Python Modules 101
7.3.1 What is a Python Module? 101
7.3.2 Modules and Namespaces 102
7.3.3 Importing Modules 103
7.3.4 Module Loading and Execution 105
7.3.5 Local, Global, and Built-in Namespaces in Python 106
7.3.6 A Programmer-Defined Stack Module 106
7.3.7 A Palindrome Checker Program 108
Chapter 8 Text Files 110
8. 1 What is a Text File? 110
8. 2 Using Text Files 110
8.2.1 Opening Text Files 110
8.2.2 Closing Text Files 111
8.2.3 Reading Text Files 111
8.2.4 Writing Text Files 112
8. 3 String Processing 114
8.3.1 String Traversal 114
8.3.2 String-Applicable Sequence Operations 114
8.3.3 String Methods 115
8.3.4 String Operators 116
8. 4 Exception Handling 116
8.4.1 What is an Exception? 117
8.4.2 The Propagation of Raised Exceptions 117
8.4.3 Catching and Handling Exceptions 118
8.4.4 Exception Handling and User Input 124
8.4.5 Exception Handling and File Processing 125
8.4.6 Python Built-in Exceptions 125
8.4.7 Python User-Defined Exceptions
126
UNIT – V
Chapter 9 Dictionaries and Sets 128
9. 1 Dictionary Type in Python 128
9.1.1 What is a Dictionary? 128
9.1.2 Creating a Dictionary 128
9.1.3 Accessing Values in the Dictionary 129
9.1.4 Updating a Dictionary 130
9.1.5 Deleting Elements from a Dictionary 130
9.1.6 View Keys and Values 131
9.1.7 Dictionary Methods 132
9.1.8 Dictionary Built-in Functions 132
9. 2 Set Data Type 132

6
9.2.1 The Set Data Type in Python 133
9.2.2 Set Operations 136
9.2.3 Set Methods 138
139
9.2.4 Built-in Functions with Set
139
9.2.5 Frozenset

Chapter 10 Object-Oriented Programming 142


10. 1 What is Object-Oriented Programming? 142
10.1.1 What is a Class? 142
10.1.2 Three Fundamental Features of Object-Oriented Programming 143
10. 2 Encapsulation 143
10.2.1 What is Encapsulation? 143
10.2.2 Defining Classes in Python 143
10.2.3 Creating an Object in Python 144
10.2.4 Special Methods in Python 145
10.2.5 Python Constructors 146
10.2.6 Built-in Class Functions 147
10.2.7 Built-in Class Attributes 148
10.2.8 Abstraction 149
10. 3 Inheritance 150
10.3.1 What is Inheritance? 150
10.3.2 Subtypes 156
10.3.3 Defining Subclasses in Python 156
10. 4 Polymorphism 157
10.4.1 What is Polymorphism? 157
10.4.2 The Use of Polymorphism 157
10.4.3 Method Overriding 159
Chapter 11 Recursion 161
11. 1 Recursive Functions 161
11.1.1 What is a Recursive Function? 161
11.1.2 Advantages and Disadvantages of Recursion 161
11.1.3 The Factorial Function 162
11. 2 Recursive Problem Solving 163
11.2.1 Thinking Recursively 163
11.2.2 MergeSort Recursive Algorithm 163
11. 3 Iteration vs. Recursion 165
11. 4 Towers of Hanoi 166

CORE II: PRACTICAL – I PROBLEM SOLVING USING PYTHON LAB 169

7
Problem Solving Using Python

UNIT – I

Chapter 1

************************************************************************
Introduction
************************************************************************
In this Chapter, the Fundamentals of Computers, Essence of Computational Problem Solving via
some examples, Computer Algorithms, Computer Hardware and Computer Software are
discussed. At the end of this chapter, the Process of Computational Problem Solving, with an
introduction to the Python programming language are presented.

1.1 Fundamentals of Computers

What is Computer?

 A Computer is an Electronic Data Processing machine which accepts the data, stores them,
process them and produce the results automatically.
 The word COMPUTER stands for Commonly Operated Machine Particularly Used
for Trade, Education and Research.

Characteristics of a Computer

 Speed

A Computer can work very fast. It can perform Millions of Instructions Per Second
(MIPS). The speed of a Computer is determined in terms of Microsecond or Nanosecond.

 Accuracy
Computers perform calculations with 100% accuracy. Errors may occur due to data
inconsistency or inaccuracy.
 Diligence
The ability of a Computer to perform tasks without getting tired is known as
Diligence. Computers are highly reliable, they do not get tired or lack concentration. They
can work for hours and hours and can give accurate or error-free results.
 Versatility

Versatility refers to the capability of a Computer to perform different kinds of works with
same accuracy and efficiency. It means that the computer is capable of working in different
areas.

 Reliability
A Computer is reliable as it gives consistent result for similar set of data i.e., if we give same
set of input any number of times, we will get the same result.
 Automation
Automation means working automatically. A Computer can work on its own without the
intervention of the person using it.

8
 Memory

The Computer has an in-built memory where it can store a large amount of data.
Secondary Storage devices like HDDs, CDs, DVDs, Pen Drives, etc. are used for storing the
data permanently.

Applications of Computer

 Computers play a major role in every field of life. They are used in Homes, Business,
Educational Institutions, Research Organizations, Medical Field, Government Offices,
Entertainment, etc.
 Home
Computers are used at homes for several purposes like Online Bill Payment, Watching Movies
or Shows at Home, Home Tutoring, Social Media Access, Playing Games, Internet Access, etc.
 Business

Computers are used in business organizations for: Payroll Calculations, Managing Employees
Database, Maintenance of Stocks etc.

 Education
Computers are used in Educational Sectors through Online Classes, Online Examinations,
referring E-Books, Online Tutoring, etc. They help in increased use of Audio-Visual aids in the
Education field.
 Medical Field
Computers are used in Hospitals to maintain a database of patients’ history, diagnosis, X-
rays, live monitoring of patients, etc.
 Government
Computers play an important role in Government. Some major fields in this category are:
Budgets, Income Tax Department, Computerization of Voters Lists, Computerization of
Driving Licensing System, Computerization of PAN Card, Weather Forecasting etc.
 Entertainment
Computers help to Watch Movies Online, Play Games Online, Listening to Music, etc. Videos
can be fed from Computers to full screen televisions. Photo editors are available with
amazing features.
 Banking
Banks are the major users of Computers. In the Banking Sector, Computers are used to store
the details of Customers and conduct Transactions, such as Deposit and Withdrawal of
money through ATMs.

 Military

Computers are used extensively by the Military. Some Military areas where a Computer has
been used are: Missile Control, Military Communication, Military Operation and Planning,
Smart Weapons etc.

 Communication

Computers have made real-time communication over the Internet easy. Some main areas in
this category are: E-Mail, Chatting, FTP, Video-Conferencing etc.
 Science and Engineering

9
Computers are widely used in the field of Science and Engineering. Robotics is an expanding
area of technology which combines Computers with Science and Engineering to produce
machines that can either replace humans, or do specific jobs that humans are unable to do.

Generations of Computer

First Generation (1946 to 1959)

 The First Generation Computers were developed by using Vacuum Tubes.


 Batch Processing Operating System was used in this generation.
 Punched Cards, Paper Tape, and Magnetic Tape were used as input and output devices.
 They understood only Machine Language to perform operations.
 They were very expensive and only large organizations were able to afford it.
 Some examples of this generation were ENIAC, EDVAC and UNIVAC.

Second Generation (1959 – 1965)

 The Second Generation Computers were developed by using Transistors.


 Batch Processing and Multiprogramming Operating Systems were used in this generation..
 In this generation Assembly Languages was used.
 High-Level programming languages were also being developed at this time, such as early
versions of COBOL and FORTRAN.
 They were Faster than First Generation Computers.
 The Second Generation Computer uses Punched Cards for input and Printouts for output

Third Generation (1965 – 1971)

 The Third Generation Computers were developed by using Integrated Circuits (IC).
 In this generation, Remote Processing, Time Sharing, Multiprogramming Operating Systems
were used.
 The Third Generation Computer consumed less power and also generated less heat.
 The users interacted with Third Generation Computers through Keyboards, Monitors
and an Operating System.
 High-Level Languages (FORTRAN-II TO IV, COBOL, PASCAL PL/1, BASIC, ALGOL-68 etc.)
were used during this generation.

Fourth Generation (1971 – Present)

 The Fourth Generation Computers were developed by using Microprocessors.


 They are very smaller in size and are portable.
 They generates very less amount of heat.
 In this generation, Time Sharing, Real Time, Distributed Operating Systems were used.
 All the High-Level Languages like C, C++ etc., are used in this generation.

Fifth Generation (Present and Beyond)

 This generation is based on Artificial Intelligence.


 AI is an emerging branch in Computer Science, which interprets the means and method of
making Computers think like human beings.
 These include applications such as Voice Recognition and Parallel Processing.
 This generation is based on ULSI (Ultra Large Scale Integration) technology resulting in the
production of microprocessor chips having ten million electronic component.
 All the High-Level Languages like C and C++, Java, .Net etc., are used in this generation.

Types of Computer

10
Computers can be classified into three types on the basis of data handling capabilities:

 Analog Computer
 Digital Computer
 Hybrid Computer

1) Analog Computer

 An Analog Computer is a Computer which is used to process Analog data.


 Analog data is continuous data that changes continuously. Examples of such data are:
Voltage, Current, Temperature, Pressure, Speed and Weight.
 Analog Computer is a Computer that operates with numbers represented by directly
measurable quantities.
 The Analog Computer has no memory and is slower than the Digital Computer.
 Speedometer and Mercury Thermometer are examples for Analog Computers.

2) Digital Computer

 Digital Computers are designed to process discrete data.


 A Digital Computer is a digital system that performs various computational tasks.
 The Digital Computers use the Binary Number System, which has two digits: 0 and 1. A
binary digit is called a bit.
 It accepts the raw data (binary numbers 0 and 1) as input and processes it with programs
stored in its memory to produce the output.
 All Modern Computers like Laptops and Desktops are examples for Digital Computers.

3) Hybrid Computer

 The Hybrid Computer combines the features of Digital and Analog Computers.
 It is fast like an Analog Computer and has memory and accuracy like Digital Computers.
 It can process both continuous and discrete data.
 It accepts analog signals and converts them into digital form before processing.
 They are used in Airplanes, Hospitals, and Scientific applications.

Classification of Computers

 Digital Computers are broadly classified into four categories based on their Size, Memory
Capacity and Processing Speed.

1) Microcomputer
2) Minicomputer
3) Mainframe Computer
4) Supercomputer

1) Microcomputer

 Microcomputer is also known as a Personal Computer.


 It is a General-Purpose Computer that is designed for individual use.
 It is a Single-User System.
 It has a Microprocessor as a Central Processing Unit, Memory, Storage Area, Input Unit
and Output Unit.
 Laptops and Desktop Computers are examples of Microcomputers.
 It is less expensive and easy to use.

11
2) Minicomputer

 A Minicomputer is a medium sized Computer that is larger than a Microcomputer.


 It consists of two or more Processors and can support up to 250 users simultaneously.
 It is a Multi-User System.
 Minicomputers are used in institutes and departments for tasks such as Billing, Accounting
and Inventory Management.
 It is very fast compared to its size.

3) Mainframe Computer

 Mainframe Computers are designed to support hundreds or thousands of users


simultaneously.
 They can support multiple programs at the same time.
 It means they can execute different processes simultaneously.
 These features of mainframe computers make them ideal for big organizations like
Banking and Telecom Sectors, which need to manage and process a high volume of data

4) Supercomputer

 Supercomputers are one of the fastest computers currently available.


 They are designed to process huge amount of data.
 It has thousands of interconnected processors.
 They are very expensive.
 Supercomputers are particularly used in Scientific and Engineering Applications such
as Weather Forecasting, Research Laboratories, Graphic Animation, Nuclear Research,
etc.
 The first Supercomputer was developed by Roger Cray in 1976.

Block Diagram of a Computer

A Computer is divided into three basic units namely:

1. Input Unit
2. Central Processing Unit
3. Output Unit

These units are defined as follows (Figure 1-1):


12
1) Input Unit

 The Input Unit is used to give information to the Computer.


 The Input Unit transmits the data to the Main Memory of the Computer.
 Some of the most commonly used input devices are Keyboard, Mouse, Scanner, Joystick,
Camera, Microphone etc.
2) Central Processing Unit (CPU)

 The Central Processing Unit (CPU) is known as the Brain of the Computer.
 The Central processing unit (CPU) again consists of 3 parts:

 Arithmetic Logic Unit (ALU)


 Memory Unit
 Control Unit

Arithmetic Logic Unit (ALU)

 The ALU performs Arithmetic Operations and Logical Operations.


 The ALU receives the data from the Memory Unit while processing the data.
 After the calculations are over, the result is sent from ALU to the Main Memory.

Control Unit (CU)

 The Control Unit of a CPU controls all the activities and operations of the Computer.
 It is also responsible for controlling input/output, memory and other devices connected to
the Computer.
 The Control Unit determines the sequence of operations to execute the given instructions.

Memory Unit

 The Memory Unit is the storage section of the Computer. Random Access Memory (RAM)
is the Main Memory of the Computer.
 The Memory Unit transmits the information to the other units of the Computer System
when required.
 It preserves the intermediate and final results before these are sent to the Output
devices.

3) Output Unit

 The Output Unit consists of devices that are used to display the results.
 The Output data is first stored in the Memory and then displayed in human-readable form.
 Some of the most widely used Output devices are Monitor, Printer and Projector.

Figure 1-1 Block Diagram of Computer

13
1.1.1 The Essence of Computational Problem Solving

 Solving problems by the use of Computation is known as Computational Problem


Solving.
 In order to solve a problem computationally, two things are needed:
 A representation that captures all the relevant aspects of the problem, and
 An algorithm that solves the problem by use of the representation.
 Trying all possible solutions to a given problem is referred to as a Brute Force Approach.
 A representation that leaves out details of what is being represented is a form of abstraction.
The use of abstraction is common in Computer Science.
 The Python programming language provides an easy means of representing sequences of
values.
 As an example Computational Problem, suppose that we needed to write a program that
displays the Month Calendar for any given month and year, as shown in Figure 1-2.

May 2020

Sun Mon Tues Wed Thurs Fri Sat


1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31

Figure 1-2 Month Calendar

 The representation of this problem is straightforward.


 Only a few values need to be maintained—the month and year, the number of days in each
month, the names of the days of the week, and the day of the week that the first day of the
month falls on.
 Most of these values are either provided by the user (such as the month and year) or easily
determined (such as the number of days in a given month).

1.1.2 Limits of Computational Problem Solving

 An algorithm that correctly solves a given problem must solve the problem in a reasonable
amount of time. Otherwise it is of limited practical use.
 The Traveling Salesman Problem (Figure 1-3) is a classic computational problem in
Computer Science. The problem is to find the shortest route of travel for a salesman needing
to visit a given set of cities.

Figure 1-3 Traveling Salesman Problem

 In a Brute Force approach, the lengths of all possible routes would be calculated and
compared to find the shortest one.
 For ten cities, the number of possible routes is 10! or over three and a half million
(3,628,800). For twenty cities, the number of possible routes is 20! or over two and a half
quintillion (2,432,902,008,176,640,000).

14
 A similar problem exists for the game of Chess (Figure 1-4). A Brute Force Approach for a
Chess-Playing program would be to “look ahead” to all the eventual outcomes of every move
that can be made in deciding each next move.
 There are approximately 10120 possible chess games that can be played. This is related to the
average number of look-ahead steps needed for deciding each move.

Figure 1-4 Game of Chess

1.2 Computer Algorithms

1.2.1 What is an Algorithm?

 An Algorithm is a step by step procedure for solving any problem.


 Algorithms solve general problems (determining whether the given number is a prime
number), and not specific ones (determining whether 12345 is a prime number).
 Algorithms, therefore, are general computational methods used for solving particular problem
instances.
 The word “Algorithm” is derived from the ninth-century Arab Mathematician, Al-Khwarizmi.
 The computation that a given computer performs is only as good as the underlying algorithm
used.

Properties of Algorithms

All algorithms must satisfy the following criteria:

1) Input: An algorithm has zero or more inputs.


2) Output: An algorithm has one or more outputs.
3) Definiteness: The steps in the algorithm must be clearly defined and detailed.
4) Finiteness: The algorithm must terminate after a finite number of steps.
5) Effectiveness: An algorithm is also generally expected to be effective. Effectiveness is
precisely measured after translating the algorithm into a Computer program.

Flowchart

 A Flowchart is a graphical representation of an algorithm.

Flowchart Symbols

Some of the common symbols used for drawing Flowchart are as follows:

Terminal
An oval represents the start and end of a flowchart.

Input / Output
A parallelogram represents input / output.
15
Process
A rectangle represents a process.

Decision
A diamond represents a decision.

Flow Lines
The Flow Lines represent the direction of flow in a flowchart.

Connectors
A connector symbol, which is a small circle with a letter or number inside allows us to connect to a flowchart on
a different page.

Function / Subroutine
A program module is represented in a flowchart by a rectangle with some lines to distinguish it from process
symbol.

Examples::

1) Draw a Flowchart to find the sum of two numbers.

16
2) Draw a Flowchart to find the biggest among two numbers.

1.2.2 Algorithms and Computers

 An Algorithm is defined as a step-by-step procedure for solving a problem.


 In the 1930s–1940s the study of algorithms does not depend on the existence of Computers.
The algorithm for performing long division is such an example.
 Most algorithms are not as simple or practical to apply manually.
 Most require the use of Computers either because they would require too much time for a
person to apply, or involve so much detail as to make human error likely.
 Because Computers can execute instructions very quickly and reliably without error,
Algorithms and Computers are a perfect match.

1.3 Computer Hardware

 Computer Hardware is the collection of physical parts of a Computer System.


 It includes all the important components of the Central Processing Unit (CPU) and Main
Memory.
 It also includes Peripheral Components such as a Keyboard, Monitor, Mouse, and Printer.

1.3.1 Digital Computing

 In Digital Computing, all information is represented as a series of digits.


 To represent numbers using base 10, the digits 0–9 are used.
 Consider the information represented within a Computer System, as shown in Figure 1-5.

Figure 1-5 Decimal Digitalization

 In current electronic computing, each digit is represented by a different voltage level.


 All information within a Computer System is represented using only two digits, 0
and 1, called binary representation (Figure 1-6).

17
Figure 1-6 Binary Digitalization

 In this representation, each digit can be one of only two possible values, similar to a light
switch that can be either on or off.
 Computer Hardware, therefore, is based on the use of simple electronic “on/off” switches
called Transistors that switch at very high speed.
 Integrated Circuits (“chips”) are the building blocks of Computer Hardware. They
comprised of millions or even billions of transistors.

1.3.2 The Binary Number System

 The Binary Number System is a Number System that uses only two digits 0 and 1.
 This Number System is also called the base-2 Number System.
 Computers use the Binary Number System to manipulate and store all of their data including
Numbers, Words, Videos, Graphics, and Music.
 For representing numbers, any base (radix) can be used.
 For example, in base 10, there are ten possible digits (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) in which
each column value is a power of ten, as shown in Figure 1-7.

Figure 1-7 Base 10 Representation

 Other radix systems work in a similar manner. Base 2 has digits 0 and 1, with place values
that are powers of two, as shown in Figure 1-8.

Figure 1-8 Base 2 Representation

 Converting from base 2 to base 10 is simply a matter of adding up the column values that
have a 1.
 The term bit stands for "binary digit." A byte is a group of eight bits. A Kilobyte is
1,024 bytes.
 Binary representation is used in Digital Computing because of the resulting simplicity of
hardware design.
 The algorithm for the conversion from base 10 to base 2 is to successively divide a number
by two until the remainder becomes 0. The remainder of each division provides the next
higher-order (binary) digit, as shown in Figure 1-9.

18
Figure 1-9 Converting from Base 10 to Base 2

 Thus, we get the binary representation of 99 to be 1100011.

Example:

 Convert the Binary (101111)2 into its Decimal equivalent.

Thus, (101111)2 = (47)10

 Convert the Decimal (47)10 into its Binary equivalent

 Read upwards the sequence of remainders and this will give the Binary equivalent of the
Decimal number.

Thus, (47)10 = (101111)2

1.3.3 Fundamental Hardware Components

 The Central Processing Unit (CPU) is the “Brain” of a Computer System, containing digital
logic circuitry able to interpret and execute instructions.
 Memory Unit is an essential component of a Digital Computer. All the data and instructions
are stored here before and after processing.
 The data read from an Input Unit are transferred to the Computer’s Memory.
 There are two types of Memory Units: Primary Memory and Secondary Memory.

 The Primary Memory is used to store the data temporarily.


 The Primary Memory is also known as the Main Memory (Random Access Memory) of
the Computer.
 The Main Memory is Volatile; that is, the contents are lost when the power is turned off.
 The Secondary Memory is used to store the data permanently.
 The Secondary Memory is Nonvolatile; that is, the contents are not lost when the power
is turned off.
 Hard Disk is usually considered as the Secondary Memory. CDs, DVDs, Pen Drives etc. are
also used for storing the data permanently.

19
 Input / Output devices include anything that allows for input (such as the Mouse and
Keyboard) or output (such as a Monitor or Printer).
 Buses transfer data between components within a computer system, such as between the
CPU and main memory. The relationship of these devices is explained in Figure 1-10 below.

Figure 1-10 Fundamental Hardware Components

1.3.4 Operating Systems

 An Operating System (OS) is a program that acts as an interface between the User
and the Computer Hardware.
 It is a System Software that controls the overall operation of the Computer.
 Every Computer must have at least one OS to run other programs.

Figure 1-11 Operating System

 The Operating System acts as the “middle man” between the Hardware and executing
Application Programs (Figure 1-11).
 It controls the allocation of memory for the various programs that may be executing on a
Computer.
 Some popular Operating Systems include: Microsoft Windows, UNIX, LINUX, Mac OS and
Android.

1.3.5 Limits of Integrated Circuits Technology: Moore’s Law

 Moore's Law states that the number of transistors that can be placed on a single
silicon chip doubles every two years.
 Gordson E. More, one of the pioneers of integrated circuits and co-founder of Intel
Corporation predicted this law in 1965.
 While this doubling of performance cannot go on indefinitely, it has not yet reached its limit.

1.4 Computer Software

20
 The first Computer programs ever written were for a mechanical computer designed by
Charles Babbage in the mid-1800s (Babbage’s Analytical Engine).
 Charles Babbage is the Father of Computer.
 The person who wrote these programs was a woman, Ada Lovelace, who was a talented
Mathematician.
 Ada Lovelace has been called the world's first Computer Programmer.

1.4.1 What is Computer Software?

 Computer Software or simply Software is a set of programs, which is designed to


perform a well-defined function.
 A Program is a sequence of instructions written to solve a particular problem.
 The two major types of Computer Software are:

 Application Software
 System Software
 Application Software is a program or group of programs designed for end users.
The different types of Application Software include the following: Word Processing
Software, Spreadsheet Software, Presentation Software, Database Software, Multimedia
Software etc. and so on.
 System Software is a set of programs that control and manage the operations of
Computer Hardware. Operating Systems are an example of System Software. The
System Software is essential in managing the whole Computer System.

1.4.2 Syntax, Semantics, and Program Translation

What are Syntax and Semantics?

 Syntax and Semantics are the important concepts that can be applied to all languages.
 The Syntax of a language is a set of characters and the acceptable arrangements (sequences)
of those characters.
 The Semantics of a language is the meaning associated with each syntactically correct
sequence of characters.
 Every language has its own Syntax and Semantics.

Program Translation

 The Central Processing Unit (CPU) is designed to interpret and execute a specific set of
instructions represented in binary form (i.e., 0s and 1s) called machine code.
 Only programs in machine code can be executed by a CPU, as shown in Figure 1-12.

Figure 1-12 Execution of Machine Code

 Most Programs are written in a “high-level” programming language such as Python.


 In order to convert the high level language program to machine code, a translator program
must be used.
 A translator is a programming language processor that converts a Computer Program from
one language to another. It takes a program written in source code and converts it into
machine code.
 There are three different types of translators as follows:
i) Compiler
21
ii) Interpreter
iii) Assembler

Compiler

 A Compiler is a Translator used to convert the programs written in High-Level


Language to Low-Level Language. It converts the whole program in one session
and reports the errors detected after conversion.
 It takes more time to execute.
 The Compiler translates programs directly into machine code to be executed by the CPU, as
shown in Figure 1-13.

Figure 1-13 Program Execution by using a Compiler

Interpreter

 An Interpreter is a Translator used to convert the programs written in High-Level


Language to Low-Level language. It converts the program one line at a time and
reports the errors detected while doing the conversion (Figure 1-14).
 An interpreter can immediately execute instructions as they are entered. This is referred to
as interactive mode. This feature is very useful for program development.
 An Interpreter is faster than a Compiler as it immediately executes the code upon reading
the code. It is often used as a Debugging Tool for Software Development as it can execute a
single line of code at a time.
 A Python program is executed by an Interpreter.

Figure 1-14 Program Execution by using an Interpreter

Assembler

 An Assembler is a Translator used to translate the programs written in Assembly


Language to Machine Language.
 Assembly Language is difficult to understand as it is a Low-Level programming language.
 An Assembler translates a Low-Level language, an Assembly Language to an even Lower-
Level language, which is the Machine Code. The Machine Code can be directly understood by
the CPU.

Program Debugging: Syntax Errors vs. Semantic Errors

 Program Debugging is the process of finding and correcting errors (“bugs”) in a computer
program.
 Syntax Errors are caused by invalid syntax (for example, entering prnt instead of print).

22
 Semantic Errors (generally called logic errors) are errors in program logic. Such errors
cannot be automatically detected, since translators cannot understand the intent of a given
computation.
 For example, if a program computed the average of three numbers as follows,

(num1 + num2 + num3) / 2.0

a translator would have no means of determining that the divisor should be 3 and not 2.
 Computers do not understand what a program is meant to do. They only follow the
instructions given. It is up to the programmer to detect such errors.
 Program Debugging is not a trivial task, and constitutes much of the time of program
development.

1.4.3 Procedural vs. Object-Oriented Programming

 Procedural Programming and Object-Oriented Programming are the two major


programming paradigms in use today.
 Procedural Programming is a programming model, derived from Structured Programming,
based on the concept of calling Procedure. Procedures, also known as Routines, Subroutines
or Functions, simply contain a series of computational steps to be carried out.
 Object-Oriented Programming is a programming model based on the concept of Objects.
Objects contain data in the form of attributes and code in the form of Methods.
 Most programming languages support only one paradigm. Python supports both Procedural
and Object-Oriented Programming.

Difference between Procedural Programming and Object-Oriented Programming

Sl. No. Procedural Programming Object-Oriented Programming


In Procedural Programming, program In Object-Oriented Programming,
1 is divided into small parts program is divided into small parts
called Functions. called Objects.
Procedural Programming follows Top Object-Oriented Programming
2
Down approach. follows Bottom Up approach.
There is no access specifier in Object-Oriented Programming have
3 Procedural Programming. access specifiers like private, public,
protected etc.
Adding new Data and Function is not Adding new Data and Function is easy.
4
easy.
Procedural Programming does not Object-Oriented Programming provides
5 have any proper way for hiding data Data Hiding so it is More Secure.
so it is Less Secure.
In Procedural Programming, Overloading is possible in Object-Oriented
6
Overloading is not possible. Programming.
In Procedural Programming, Function In Object-Oriented Programming, Data is
7
is more important than Data. more important than Function.
Procedural Programming is based Object-Oriented Programming is based
8
on unreal world. on real world.
Examples: C, FORTRAN, Pascal, Examples: C++, Java, Python, C# etc.
9
BASIC etc.

COMPUTATIONAL PROBLEM SOLVING

1.5 The Process of Computational Problem Solving

 Computational Problem Solving does not simply mean the act of Computer Programming.
 It is a process, with programming being only one of the steps.
23
 Before a program is written, a design for the program must be developed. And before a
design can be developed, the problem to be solved must be well understood.
 Once written, the program must be thoroughly tested. These steps are outlined in Figure 1-
15.

Figure 1-15 Process of Computational Problem Solving

1.5.1 Problem Analysis

 Problem Analysis involves identifying the problem and establishing the causes and effects
related to that problem.

Understanding the Problem

 Understanding the problem is the first step of any Problem Solving.


 Once a problem is clearly understood, the fundamental computational issues for solving it
can be determined.
 For each of the problems, the representation is straightforward.
 For the Month Calendar problem, there are two algorithmic tasks— determining the first day
of a given month, and displaying the month calendar in the proper format. The first day of
the month can be obtained by direct calculation using the algorithm provided.
 For both the Traveling Salesman Problem and the Game of Chess, the brute-force approach
is infeasible.
 Thus, the computational issue for these problems is to find other, more efficient algorithmic
approaches for their solution.

Knowing What Constitutes a Solution

 Besides clearly understanding a computational problem, one must know what constitutes a
solution. For some problems, there is only one solution. For others, there may be a number
(or infinite number) of solutions. Thus, a program may be stated as finding,
 A solution
 An approximate solution
 A best solution
 All solutions

 There may be more than one “best” solution for any given problem. In the Traveling
Salesman problem there is only one solution (unless there exists more than one shortest
route). For the game of chess, the solution is to win the game. Thus, since the number of
chess games that can be played is on the order of 10120, there are a comparable number of
possible solutions to this problem.
24
1.5.2 Program Design

 Program Design is the process that an organization uses to develop a Program.

Describing the Data Needed

 For the Month Calendar problem, the data include the month and year (entered by the user),
the number of days in each month, and the names of the days of the week. A useful
structuring of the data is given below,

[month, year]
[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
[‘Sunday’, ‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday’, ‘Saturday’]

 The month and year are grouped in a single list since they are naturally associated. Similarly,
the names of the days of the week and the number of days in each month are grouped.
Finally, the first day of the month, as determined by the algorithm in Figure 1-8, can be
represented by a single integer,

0 – Sunday, 1 – Monday,…, 6 – Saturday

 For the Traveling Salesman problem, the distance between each pair of cities must be
represented.
 For example, the distance from Atlanta to Los Angeles is 2175 miles. There is duplication of
information in this representation, however. For each distance from x to y, the distance from
y to x is also represented.

 Finally, for a chess-playing program, the location and identification of each chess piece needs
to be represented. Various ways of representing chess boards have been developed, each
with certain advantages and disadvantages. The appropriate representation of data is a
fundamental aspect of Computer Science.

Describing the Needed Algorithms

 When solving a Computational Problem, either suitable existing algorithms may be found or
new algorithms must be developed.
 For the Month Calendar problem, a day of the week algorithm already exists.
 For the Traveling Salesman problem, there are various algorithms that can be utilized, for
solving problems with tens of thousands of cities.
 Finally, for the Game of Chess, since it is infeasible to look ahead at the final outcomes of
every possible move, there are algorithms that make a best guess at which moves to make.
 Algorithms that work well in general but are not guaranteed to give the correct result for
each specific problem are called heuristic algorithms.

1.5.3 Program Implementation

 Program Implementation is about making a program work.


 Design decisions provide general details of the data representation and the algorithmic
approaches for solving a problem.
 The details, however, do not specify which programming language to use, or how to
implement the program. That is a decision for the implementation phase.
 In Python Programming, the implementation needs to be expressed in a syntactically correct
and appropriate way, using the instructions and features available in Python.

1.5.4 Program Testing


25
 Program Testing is the process of executing a program with the intent of finding
errors.
 Testing is done incrementally as a program is being developed, when the program is
complete, and when the program needs to be updated.
 The general Truisms of Software Development are as follows:

1. Programming errors or pervasive, persistent, and inevitable.


2. Software Testing is an essential part of Software Development.
3. Any changes made in correcting a programming error should be fully understood as to
why the changes correct the detected error.

1.6 The Python Programming Language

1.6.1 Introduction to Python

 Python is a General-Purpose High Level programming language.


 Guido Van Rossum is the creator of the Python programming language, first released in the
early 1990s.
 Python is named after the comedy television show Monty Python's Flying Circus.
 Python has a simple syntax.
 Python is an interpreted programming language.
 Python provides powerful programming features, and is widely used.
 Companies and organizations that use Python include YouTube, Google, Yahoo, and NASA.

1.6.2 Features of Python

 There are many features in Python. Some of the essential features of Python are listed below.

1. Easy to Learn and Use


 Python is easy to learn as compared to other programming languages. Python code looks
like simple English words. There is no use of semicolons or brackets, and the indentations
define the code block.

2. Interpreted Language
 Python is an interpreted language because Python code is executed line by line at a time.
This makes it easier to debug our code.

3. Platform-Independent
 Python is platform-independent. If we write a program, it will run on different platforms
like Windows, Mac and Linux. We don’t need to write them separately for each platform.

4. Free and Open-Source

 Python is freely available. It can be downloaded from the Python Official


Website www.python.org. Python is an open-source programming language. This means
that its source code is available to the public. We can download it, change it, use it, and
distribute it.

6. Object-Oriented

 Python supports procedure-oriented programming as well as object-oriented programming.


In procedure-oriented languages, the program is built around procedures or functions which
are nothing but reusable pieces of programs. In object-oriented languages, the program is
26
built around objects which combine data and functionality. The object-oriented procedure
helps the programmer to write reusable code and develop applications in less code.

7. High-Level Language

 Python has been designed to be a high-level programming language. This means that when
we write a code in Python, we do not need to remember the system architecture as well as
the memory management .
8. Extensible

 A programming language is said to be extensible if it can be extended to other languages.


Python code can also be written in other languages like C++, making it a highly extensible
language.

9. Expressive

 Python needs to use only a few lines of code to perform complex tasks. For example, to
display Hello World, we simply need to type one line - print(“Hello World”). Other languages
like Java or C would take up multiple lines to execute this.

10. Large Standard Library

 Python has a large standard library which provides a rich set of module and functions so
we do not have to write our own code for every single thing. There are many libraries
present in Python such as regular expressions, unit-testing, web browsers, etc.

11. Dynamically Typed Language


 Python is a dynamically-typed language. That means the type (for example- int, double,
long, etc.) for a variable is decided at run time, not in advance. Because of this feature we
don’t need to specify the type of variable.

12. GUI Programming Support

 Graphical User Interface is used for the developing Desktop application. Python has support
for a wide array of GUIs which can easily be imported to the interpreter, thus making this
one of the most favorite languages for developers.

1.6.3 The IDLE Python Development Environment

 IDLE Stands for Integrated Development and Learning Environment.


 An IDE is a bundled set of software tools for program development.
 This typically includes an Editor for creating and modifying programs, a Translator for
executing programs, and a program Debugger.
 A Debugger provides a means of taking control of the execution of a program in finding
program errors.
 Python is most commonly translated by use of an Interpreter. Thus, Python provides the
very useful ability to execute in interactive mode.
 The window that provides this interaction is referred to as the Python Shell.
 A Python Prompt consists of three Greater Than symbols (>>>).
 Example use of the Python Shell is demonstrated in Figure 1-16.

27
Figure 1-16 Python Shell

 Here, the expression 5 + 4 is entered at the Shell Prompt (>>>), which immediately
responds with the result 9.
 Although working in the Python Shell is convenient, the entered code is not saved.
 Thus, for program development, a means of entering, editing, and saving Python programs is
provided by the program editor in IDLE.

1.6.4 The Python Standard Library

 The Python Standard Library is a collection of modules, each provide specific functionality.
 For example, the math module provides additional mathematical functions. The random
module provides the ability to generate random numbers, useful in programming.
 In order to utilize the capabilities of a given module in a specific program, an import
statement is used.
>>>import math
>>>math.factorial(5)
120
 The above example shows the use of the import math statement to gain access to a
particular function in the math module, the factorial function.
 The syntax for using the factorial function is math.factorial(n), for some positive integer n.

1.6.5 Input and Output Functions

input Function

 The Python input function is used to get information from the user.

Syntax:

input(prompt)

where, prompt is a String, representing the default message before the input.

Example:

name = input('What is your name? ')

 Characters within quotes are called strings. This particular use of a string, for requesting
input from the user, is called a prompt. The input function displays the string on the screen
to prompt the user for input,

What is your name? Sam

 The underline is used here to indicate the user’s input.

28
print Function

 The Python print function is used to display information on the screen. This may be used to
display a message.

Syntax:

print(object(s), sep=separator, end=end, file=file, flush=flush)

where:
Parameter Description
object(s) Any object, and as many as you like. Will be converted to string
before printed
sep='separator' Optional. Specify how to separate the objects, if there is more than
one. Default is ' '
end='end' Optional. Specify what to print at the end. Default is '\n' (line feed)
file Optional. An object with a write method. Default is sys.stdout
flush Optional. A Boolean, specifying if the output is flushed (True) or
buffered (False). Default is False
Note: sep, end, file and flush are keyword arguments.
Example:

>>> print('Welcome to Python Programming!')


Welcome to Python Programming!

or used to output the value of a variable,


>>> n = 10
>>> print(n)
10
>>> name = input('What is your name?: ')
What is your name? Sam
>>> print('Hello', name)
Hello Sam

 A comma is used to separate the individual items being printed, causing a space to appear
between each when displayed. Thus, the output of the print function in this case is Hello Sam,
and not HelloSam.

Python Comments
 A Comment in Python starts with the hash character (#) and continues to the end of the line.
 Comments are the descriptions that help the programmers to understand better the
functionality of the program.
 They are completely ignored by the Python Interpreter.

Example:

# This is a Comment
print("Welcome to Python.")

 Comments can also be placed at the end of the line, and Python will ignore the rest of the line:

Example:

print("Welcome to Python.”) # This is the print Statement

29
1.6.6 How to use Python IDLE?

 IDLE (Integrated Development and Learning Environment) is an Integrated Development


Environment (IDE) for Python.
 The Python Installer for Windows contains the IDLE module by default .
 IDLE can be used to execute a single statement just like Python Shell and also to create,
modify and execute Python scripts.
 IDLE provides a fully-featured text editor to create Python scripts that includes features
like syntax highlighting, auto completion and smart indent.
 It also has a Debugger with stepping and breakpoints features.
 To start IDLE interactive shell, search for the IDLE icon in the Start menu and double click
on it.
 This will open IDLE, where we can write Python code and execute it.
 Now, we can execute Python statements in the Python Shell.

>> 4 + 2
6
>>>3 * 3
9

 To create a Python program file, select New File from the File Menu in the Python Shell.
 A new, Untitled program window will appear:

 Type the following in the program window exactly as shown.

# My First Python Program


name=input(‘What is your name?’ )
print(‘Hello’, name)
print(‘Welcome to Python Programming!’)

 Save the program by selecting Save As command from the File menu, and save in the
appropriate folder with the name MyFirstProgram.py.

 Now, press F5 to run the script in the editor window. The IDLE shell will show the output.

 If we have entered the program code correctly, the program should execute as shown below.

What is your name? Sam


Hello Sam
Welcome to Python Programming!
>>>

30
 If we have mistyped part of the program resulting in a syntax error (such as mistyping print),
we will get an error message.
Exercises:

1. Define Computational Problem Solving.


2. What is the Essence of Computational Problem Solving?
3. What are the Limitations of Computational Problem Solving?
4. Define Traveling Salesman Problem.
5. What is meant by “Brute Force Approach”?
6. Define Algorithm.
7. What are the essential properties of an Algorithm?
8. Define Computer Hardware.
9. Write short notes on Digital Computing.
10. Define Binary Number System.
11. Define Bit, Byte and Kilobyte.
12. What is a Digital Computer? What are the components of a Digital Computer?
13. Explain the Block Diagram of a Computer.
14. What is an Operating System? What are its functions?
15. What are the limitations of ICs?
16. Define Moore’s Law.
17. Who is the Father of Computer?
18. Who is the first Computer Programmer in the World?
19. Define Computer Software.
20. Explain the terms Hardware and Software.
21. What are Syntax and Semantics?
22. What is Compiler?
23. What is Interpreter?
24. What is Assembler?
25. What do you mean by “Program Debugging”?
26. Distinguish between Syntax Errors and Semantic Errors.
27. Distinguish between Procedural Programming and Object-Oriented Programming.
28. Explain briefly about Computational Problem Solving.
29. What is Python?
30. Define IDLE.
31. What do you mean by Python Standard Library?
32. What are the input and output functions in Python?
33. Write a Python program to find the sum of two numbers.
34. Write a Python program to find the Area and Perimeter of a Circle.

************************

31
Chapter 2

************************************************************************
Data and Expressions
************************************************************************
Python supports many Operators for combining Data objects into Expressions. An expression
is any sequence of literals (Strings, Numbers, Lists, Sets, Tuples), objects, function calls,
identifiers combined with a variety of operators which results in a value

In this Chapter, we begin a detailed discussion of the concepts and techniques of Computer
Programming.

2.1 Literals

 Python Literals can be defined as data that is given in a variable or constant.

2.1.1 What is a Literal?

 A Literal is a sequence of one of more characters that stands for itself.

2.1.2 Numeric Literals

 A Numeric Literal is a literal containing only the digits 0–9, an optional sign
character (+ or -), and a possible decimal point.
 The letter e is also used in exponential notation.
 If a numeric literal contains a decimal point, then it denotes a floating-point value, or
“float” (e.g., 10.24); otherwise, it denotes an integer value (e.g., 10). Commas are never
used in numeric literals.

Limits of Range in Floating-Point Representation

 There is no limit to the size of an integer that can be represented in Python.


 Floating-Point values, however, have both a limited range and a limited precision.
 Python uses a double-precision standard format (IEEE 754) providing a range of 10-308 to
10308 with 16 to 17 digits of precision.
 To denote such a range of values, floating-points can be represented in scientific notation,

9.0045602e+5 (9.0045602 X 105, 8 digits of precision)


1.006249505236801e8 (1.006249505236801 X 108, 16 digits of precision)
4.239e-16 (4.239 x 10-16, 4 digits of precision)

 Arithmetic Overflow occurs when a calculated result is too large in magnitude to be


represented.
 Arithmetic Underflow occurs when a calculated result is too small in magnitude to be
represented.

Built-in format Function

 The built-in format function can be used to produce a numeric string version of the value
containing a specific number of decimal places,

>>>12/5 >>> 5/7


2.4 0.7142857142857143
>>>format(12/5, '.2f') >>>format(5/7, '.2f')
'2.40' '0.71'

32
 In these examples, the format specifier '.2f' rounds the result to two decimal places of
accuracy in the string produced.
 For very large (or very small) values 'e' can be used as a format specifier,

>>>format(2 ** 100, '.6e')


'1.267651e 1 30'

 A comma in the format specifier adds comma separators to the result.

>>>format(13402.25, ' , .2f')


13,402.24

2.1.3 String Literals

 A String Literal is a sequence of characters enclosed in quotes.


 'Hello', 'Smith, John', "Baltimore, Maryland 21210" are valid String Literals.
 In Python, String Literals may be delimited (surrounded) by a matching pair of either single (')
or double (") quotes.
 Strings must be contained all on one line (except when delimited by triple quotes).

Example:

>>> print('Welcome to Python Programming!')

Welcome to Python Programming!

 A String may contain zero or more characters, including letters, digits, special characters, and
blanks.
 A String consisting of only a pair of matching quotes (with nothing in between) is called the
empty string.
 Strings may also contain quote characters as long as different quotes are used to delimit the
string,
"Jennifer Smith's Friend"

The Representation of Character Values

 The Unicode encoding scheme is intended to be a universal encoding scheme.


 Unicode is actually a collection of different encoding schemes utilizing between 8 and 32 bits
for each character.
 The default encoding in Python uses UTF-8, an 8-bit encoding compatible with ASCII, an
older, still widely used encoding scheme.
 UTF stands for Unicode Transformation Format. The '8' means it uses 8-bit blocks to
represent a character.
 Currently, there are over 100,000 Unicode-defined characters for many of the languages
around the world.
 Unicode is capable of defining more than 4 billion characters.
 A partial listing of the ASCII-compatible UTF-8 encoding scheme is given in Figure 2-1.

32 00100000 space 60 00111100 < 88 01011000 X


33 00100001 ! 61 00111101 = 89 01011001 Y
34 00100010 " 62 00111110 > 90 01011010 Z
35 00100011 # 63 00111111 ? 91 01011011 [
36 00100100 $ 64 01000000 @ 92 01011100 \
37 00100101 % 65 01000001 A 93 01011101 ]
33
38 00100110 & 66 01000010 B 94 01011110 ^
39 00100111 ' 67 01000011 C 95 01011111 _
40 00101000 ( 68 01000100 D 96 01100000 `
41 00101001 ) 69 01000101 E 97 01100001 a
42 00101010 * 70 01000110 F 98 01100010 b
43 00101011 + 71 01000111 G 99 01100011 c
44 00101100 , 72 01001000 H 100 01100100 d
45 00101101 - 73 01001001 I 101 01100101 e
46 00101110 . 74 01001010 J 102 01100110 f
47 00101111 / 75 01001011 K 103 01100111 g
48 00110000 0 76 01001100 L 104 01101000 h
49 00110001 1 77 01001101 M 105 01101001 i
50 00110010 2 78 01001110 N 106 01101010 j
51 00110011 3 79 01001111 O 107 01101011 k
52 00110100 4 80 01010000 P 108 01101100 l
53 00110101 5 81 01010001 Q 109 01101101 m
54 00110110 6 82 01010010 R 110 01101110 n
55 00110111 7 83 01010011 S 111 01101111 o
56 00111000 8 84 01010100 T 112 01110000 p
57 00111001 9 85 01010101 U 113 01110001 q
58 00111010 : 86 01010110 V 114 01110010 r
59 00111011 ; 87 01010111 W 115 01110011 s
116 01110100 t 122 01111010 z
117 01110101 u 123 01111011 {
118 01110110 v 124 01111100 |
119 01110111 w 125 01111101 }
120 01111000 x 126 01111110 ~
121 01111001 y 127 01111111 DEL
Figure 2-1 Partial UTF-8 (ASCII) Code Table

[Encoding is a way to convert data from one format to another. A character


encoding is a way to convert text data into binary numbers.]

2.1.4 Control Characters

 Control Characters are special characters that are not displayed on the screen.
 They can control the display of output.
 Control characters do not have a corresponding Keyboard character. Therefore, they are
represented by a combination of characters called an escape sequence.
 An Escape Sequence is a string of one or more characters used to denote Control
Characters.
34
 The backslash (\) serves as the escape character in Python.
 For example, the escape sequence '\n' represents the newline control character, used to
begin a new screen line. An example of its use is given below,

print('Hello\nAkash Kumar')

which is displayed as follows,


Hello
Akash Kumar

2.1.5 String Formatting

 The Built-in format function is used to control how strings are displayed. The format
function has the form,

format(value, format_specifier)

where value is the value to be displayed, and format_specifier can contain a combination of
formatting options.

 For example, to produce the string 'Hello' left-justified in a field width of 20 characters would
be done as follows,

format('Hello', ' < 20') ➝ 'Hello '

 To right-justify the string, the following would be used,

format('Hello', ' > 20') ➝ ' Hello'

 Formatted strings are left-justified by default. To center the string the '^' character is used:

format('Hello', '^20').

 Another use of the format function is to create strings of blank characters, which is
sometimes useful,

format(' ', '30') ➝ ' '

 Finally blanks, by default, are the fill character for formatted strings. However, a specific fill
character can be specified as shown below,

>>>print('Hello World', format('.', '. < 30'), 'Have a Nice Day!')


Hello World .............................. Have a Nice Day!

2.1.6 Implicit and Explicit Line Joining

 Python recommended a maximum length of 79 characters in a program line.


 There are two ways in Python to deal with the situation if the program line is too long—
implicit and explicit line joining.

Implicit Line Joining

 Expressions in Parentheses, Square Brackets or Curly Braces can be split over more than
one physical line without using backslashes.

Example:

35
month_names = ['Januari', 'Februari', 'Maart', # These are the
'April', 'Mei', 'Juni', # Dutch names
'Juli', 'Augustus', 'September', # for the months
'Oktober', 'November', 'December'] # of the year

 Implicitly continued lines can carry comments.


 The indentation of the continuation lines is not important. Blank continuation lines are allowed.
 There is no NEWLINE token between implicit continuation lines.

Explicit Line Joining

 Program lines may be explicitly joined by use of the backslash (\)


 Program lines that end with a backslash that are not part of a literal string (that is, within
quotes) continue on the following line,

Example:

if 1900 < year < 2100 and 1 <= month <= 12 \


and 1 <= day <= 31 and 0 <= hour < 24 \
and 0 <= minute < 60 and 0 <= second < 60: # Looks like a valid date
return 1

 A line ending in a backslash cannot carry a comment. A backslash does not continue a
comment.
 A backslash does not continue a token except for string literals
2.2 Variables and Identifiers

 A Python Variable is a reserved memory location used to store values. Variables are
containers for storing data values.
 A Python Identifier is a name given to entities like Class, Functions, Variables, etc. It helps
to differentiate one entity from another.

2.2.1 What is a Variable?

 A Variable is a name given to a location in memory where a data value is stored.

Example:

num = 10

 A Variable can be assigned different values during a program’s execution.


 Wherever a variable appears in a program (except on the left-hand side of an assignment
statement), it is the value associated with the variable that is used, and not the variable’s
name,

num + 1 ➝ 10 + 1 ➝ 11

 The Assignment Operator = is used to assign a value to a Variable.

num = 10 num = num + 1

 In computing, an assignment statement, it is used to increment the value of a given variable


by one.

36
 It makes clear that the right side of an assignment is evaluated first and then the result is
assigned to the variable on the left.
 Variables may also be assigned to the value of another variable or expression.
num = 10 k = num

 Variables num and k are both associated with the same literal value 10 in memory. To see
this, the built-in function id can be used.

>>>id(num) >>>id(k)
505494040 505494040

 The id function produces a unique number identifying a specific value (object) in memory.
 An Immutable Value is a value that cannot be changed.
 In Python the same variable can be associated with values of different type during program
execution.

var = 12 integer
var = 12.45 float
var = 'Hello' string

Rules for Python Variables:

 A Variable Name must start with a letter or an underscore character.


 A Variable Name cannot start with a number.
 A Variable Name can only contain alpha-numeric characters and underscores (A-Z, 0-9,
 and _).
 The name of the Variable cannot have special characters such as %, $, # etc.
 Keywords cannot be used as Variable Names.
 A Variable can be of any length.
 Variable Names are case sensitive (age, Age and AGE are three different variables)

#Legal Variable Names


myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"

#Illegal Variable Names


2myvar = "John"
my-var = "John"
my var = "John"
Assigning Multiple Values to Multiple Variables

 Python allows us to assign multiple values to multiple variables in one line:

Example:

x, y, z = "Orange", "Banana", "Cherry"


print(x)
print(y)
print(z)

 And we can assign the same value to multiple variables in one line:

37
x = y = z = "Orange"
print(x)
print(y)
print(z)
2.2.2 Variable Assignment and Keyboard Input

 The value that is assigned to a given variable does not have to be specified in the program.
 The value can come from the user by using the input function.

>>>name = input('What is your name?')

What is your name? Sam

 In this case, the variable name is assigned the string 'Sam'. If the user hit return without
entering any value, name would be assigned to the empty string ('').
 All input values returned by the input function can be string type.
 The Built-in functions int() and float() can be used to convert a string to a numeric
type.

N=int(input(‘Enter the value of N: ’))


Marks=float(input(“Enter the marks : ”))

2.2.3 What is an Identifier?

 An Identifier is a sequence of one or more characters used to provide a name for a given
program element.
 A Python Identifier is a name used to identify a Variable, Function, Class, Module or
other Object.

Rules:

 An Identifier can be a combination of uppercase letters (A-Z), lowercase letters, (a-z),


digits (0-9) or an underscore(_).
 The underscore character, _, is also allowed to aid in the readability of long Identifier
names. It should not be used as the first character, however, as Identifiers beginning with
an underscore have special meaning in Python.
 An Identifier cannot start with a digit.
 Keywords cannot be used as Identifiers.
 The special characters like !, @, #, $, % etc cannot be used in an Identifier.
 An Identifier can be of any length.
 Spaces are not allowed as part of an Identifier.
 Python Identifier names are case sensitive.

Examples of valid and invalid identifiers in Python are given in Figure 2-2.

Valid Identifiers Invalid Identifiers Reason for Invalid


totalSales ‘totalSales’ Quotes not allowed
totalsales total sales Spaces not allowed
salesFor2020 2020Sales Cannot begin with a digit
Sales_for_2020 _2020Sales Could not begin with an underscore

Figure 2-2 Identifier Naming

2.2.4 Keywords and Other Predefined Identifiers in Python

 A Keyword is an Identifier that has predefined meaning in a programming language.


38
 Python Keywords are the words that are reserved. Therefore, Keywords cannot be used as
“regular” identifiers.
 Doing so will result in a syntax error, as demonstrated in the example given below,

>>> and = 10
SyntaxError: invalid syntax

 Keywords in Python are case sensitive.


 The Keywords in Python are listed below. All the Python Keywords contain lowercase letters
only.
 To display the keywords, type help() in the Python Shell, and then type keywords (type 'q' to
quit).

and def False import not True


as del finally in or try
assert elif for is pass while
break else from lambda print with
class except global None raise yield
continue exec if nonlocal return

Figure 2-3 Keywords in Python

2.3 Operators

 Operators are special symbols in Python that carry out arithmetic or logical computation.

2.3.1 What is an Operator?

 An Operator is a symbol that represents an operation that may be performed on one


or more operands.
 The values the operator uses are called Operands.
 An operand is a variable or a value on which we perform the operation.
 For example in the expression 2+3, 2 and 3 are the operands and + is the operator.
 Operators are used to perform operations on variables and values
 Operators that take one Operand are called Unary Operators.
 Operators that take two Operands are called Binary Operators.
2.3.2 Arithmetic Operators
 Arithmetic Operators are used to perform mathematical operations like Addition,
Subtraction, Multiplication, Division etc.
 Python provides the Arithmetic Operators given in Figure 2-4.

Operator Description Example


+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor Division x // y

Figure 2-4 Arithmetic Operators in Python

39
 The + , -, * (multiplication) and / (division) arithmetic operators perform the usual
operations.
 The - symbol is used both as a unary operator (for negation) and a binary operator (for
subtraction).
 Python provides two forms of division. “true” division is denoted by a single slash, /.
Thus, 25 /10 evaluates to 2.5.
 Floor Division or Truncating division is denoted by a double slash, //, providing a
truncated result based on the type of operands applied to.
 When both operands are integer values, the result is a truncated integer referred to as
Integer Division. 125
 When as least one of the operands is a float type, the result is a truncated floating point.
Thus, 25 // 10 evaluates to 2, while 25.0 // 10 becomes 2.0.

2.4 Expressions and Data Types

 Expressions are representations of value. The operators and operands can be combined to
form expressions.
 An Expression is a combination of Values, Variables, Operators, and Calls to Functions.
 Data Types represent a kind of value which determines what operations can be performed
on that data.

2.4.1 What is an Expression?

 An Expression is a combination of symbols that evaluates to a value.


 Expressions, most commonly, consist of a combination of operators and operands,

4 + (3 * k)

 An Expression can also consist of a single literal or variable. Thus, 4, 3, and k are each
expressions.
 This Expression has two sub expressions, 4 and (3 * k). Sub expression (3 * k) itself has two
sub expressions, 3 and k.
 Expressions that evaluate to a numeric type are called Arithmetic Expressions.
 A Sub Expression is any expression that is part of a larger expression. Sub
expressions may be denoted by the use of parentheses, as shown above.
 Thus, for the expression 4 + (3 * 2), the two operands of the addition operator are 4 and (3
* 2), and thus the result it equal to 10. If the expression were instead written as (4 + 3) * 2,
then it would evaluate to 14.
 Since a sub expression is an expression, any sub expression may contain sub expressions of
its own,

4 + (3 * (2 - 1)) ➝ 4 + (3 * 1) ➝ 4 + 3 ➝ 7

 If no parentheses are used, then an expression is evaluated according to the rules of operator
precedence in Python.

2.4.2 Operator Precedence

 Operator Precedence is the order in which the Operators in the Expression are
evaluated.
 The way we commonly represent expressions, in which operators appear between their
operands, is referred to as Infix Notation.
 For example, the expression 4 + 3 is in infix notation since the + operator appears between
its two operands, 4 and 3.

40
 There are other ways of representing expressions called Prefix and Postfix Notation, in
which operators are placed before and after their operands, respectively.
 The expression 4 + (3 * 5) is also in infix notation. It contains two operators, + and *. The
parentheses denote that (3 * 5) is a sub expression. Therefore, 4 and (3 * 5) are the
operands of the addition operator, and thus the overall expression evaluates to 19.
 Each programming language has its own rules for the order that operators are applied, called
Operator Precedence, defined in an Operator Precedence Table.
 The Operator Precedence Table for the Python Arithmetic Operators are given in Figure 2-5.

Operator Associativity
** (exponentiation) right-to-left
- (negation) left-to-right
* (mult), / (div), // (truncating div), % left-to-right
(modulo)
+ (addition), - (subtraction) left-to-right

Figure 2-5 Operator Precedence of Arithmetic Operators in Python

 In the table, higher-priority operators are placed above lower-priority ones. Thus, we see that
multiplication is performed before addition when no parentheses are included,

4 + 3 * 5 ➝ 4 + 15 ➝ 19

2.4.3 Operator Associativity

 Operator Associativity is the order that operators are applied when having the same
level of precedence, specific to each operator.
 For operators following the associative law, the order of evaluation doesn’t matter,

(2 + 3) + 4 ➝ 9 2 + (3 + 4) ➝ 9

 In this case, we get the same results regardless of the order that the operators are applied.
Division and subtraction, however, do not follow the associative law,

(a) (8 - 4) - 2 ➝ 4 - 2 ➝ 2 8 - (4 - 2) ➝ 8 - 2 ➝ 6
(b) (8 / 4) / 2 ➝ 2 / 2 ➝ 1 8 / (4 / 2) ➝ 8 / 2 ➝ 4
(c) 2 ** (3 ** 2) ➝ 512 (2 ** 3) ** 2 ➝ 64

 Each operator has a specified Operator Associativity that defines the order of evaluation.
 All Operators in the figure, except for Exponentiation, have left-to-right associativity—
Exponentiation has right-to-left associativity.

2.4.4 What is a Data Type?

 A Data Type is a set of values, and a set of operators that may be applied to those
values.
 Python has the following Standard or Built-in Data Types:

1. Numeric
2. String
3. List
4. Tuple
5. Dictionary
6. Sets
7. Boolean
41
1. Numeric

 In Python, Numeric Data Type represents the data which has Numeric Value.
 Numeric Value can be Integer, Floating-Point Number or even Complex Numbers. They are
defined as int, float, and complex classes in Python.
 Integers can be of any length, it is only limited by the memory available.
 A Floating-Point number is accurate up to 15 decimal places. 1 is an Integer, 1.0 is a
Floating-Point number.
 Complex Numbers are written in the form, x + yj, where x is the real part and y is the
imaginary part.

Example:

A=5
B=10.5
C=1+2j

2. String

 A String is a sequence of characters enclosed in single, double or triple quotes.

Example:

S1 = ‘Welcome to Python’
S2 = "Welcome to Python”
S3 = '''A Multiline

3. List

 A List is an ordered collection of one or more data items.


 All the items in a list do not need to be of the same type.
 The items in a List are separated by commas and are enclosed within brackets [ ].

Example:

L = [‘Akash’, 20, 90.5]

4. Tuple

 A Tuple is an ordered collection of one or more data items same as a List. The only difference
is that tuples are immutable. Tuples once created cannot be modified.
 The items in a Tuple are separated by commas and are enclosed within parentheses ( ).

Example:

T = (5,'Abilash’, 1+3j)

5. Dictionary

 A Dictionary is an unordered collection Key-Value pairs.


 In Python, dictionaries are defined within braces {} with each item being a pair in the
form Key:Value. Key and Value can be of any type.

Example:

D = {1:'Value','Key':2}

42
6. Sets

 A Set is an unordered collection of unique items.


 Set is defined by values separated by comma inside braces { }.
 Items in a set are not ordered.

Example:

S = {5,2,3,1,4}

7. Boolean

 The Boolean Data Type is used to store True or False values.


 In Python, Boolean Variables are defined by the True and False keywords.
 Integers and Floating-Point Numbers can be converted to the Boolean Data Type using
Python's bool() function.

Example:

A = True
B = False

2.4.5 Mixed-Type Expressions

 A Mixed-Type Expression is an expression containing operands of different type.


 The CPU can perform operations only on operands of the same type.
 Operands of Mixed-Type Expressions therefore must be converted to a common type.
 Values can be converted in one of two ways—by implicit (automatic) conversion, called
Coercion, or by explicit Type Conversion.

Coercion vs. Type Conversion

 Coercion is the implicit (automatic) conversion of operands to a common type.


 Coercion is automatically performed on Mixed-Type Expressions only if the operands can be
safely converted, that is, if no loss of information will result.
 The conversion of integer 2 to floating-point 2.0 below is a safe conversion—the conversion
of 4.5 to integer 4 is not, since the decimal digit would be lost,

2 + 4.5 ➝ 2.0 + 4.5 ➝ 6.5 safe (automatic conversion of int to float)

 Type Conversion is the explicit conversion of operands to a specific type.


 Python provides built-in type conversion functions int() and float(), with the int() function
truncating results as given in Figure 2-6.

float(2) + 4.5 ➝ 2.0 + 4.5 ➝ 6.5


2 + int(4.5) ➝ 2 + 4 ➝ 6

Converted Converted
Conversion Function Conversion Function
Result Result
int() int(10.8) 10 float() float(10) 10.0
int(‘10’) 10 float(‘10’) 10.0
int(’10.8’) ERROR float(’10.8’) 10.8

Figure 2-6 Conversion Functions int() and float() in Python

43
Exercises:

1. What are Literals?


2. Explain the different types of Literals available in Python.
3. What is meant by Arithmetic Overflow and Arithmetic Underflow?
4. What is the use of format() function in Python?
5. How will you represent Character Values?
6. What are Control Characters?
7. What is an Escape Sequence?
8. What do you mean by Implicit and Explicit Line Joining in Python?
9. What is a Variable? What are the rules for forming a Variable in Python?
10. How will you assign multiple values in multiple variables?
11. What is an Identifier? What are the rules for forming an Identifier?
12. What are Keywords in Python?
13. What is an Operator?
14. Explain the various Operators available in Python?
15. What is an Expression?
16. What is meant by Sub Expression?
17. What are Arithmetic Operators?
18. Write about the Precedence of Arithmetic Operators in Python.
19. Write short notes on Operator Associativity.
20. What is a Data Type? Briefly explain the different Data Types available in Python.
21. Write short notes on Mixed-Type Expressions.
22. Define Coercion.
23. Distinguish between Coercion and Type Conversion.

*************************

44
UNIT – II

Chapter 3

************************************************************************
Control Structures
************************************************************************
Control Structures can be considered as the building blocks of Computer Programs. The three
fundamental means of controlling the order of execution of instructions within a program are:
Sequential, Selection, and Iterative Control. Various Control Structures available in Python
are discussed in this Chapter.

3.1 What is a Control Structure?

 A Control Structure determines the order in which statements are executed.


 There are three fundamental forms of control that programming languages provide—
Sequential Control, Selection Control, and Iterative Control.
 Sequential Control is an implicit form of control in which instructions are executed in the
order that they are written. A program consisting of only Sequential Control is referred to as
a “straight-line program.”
 Selection Control is provided by a Control Statement that selectively executes instructions.
 Iterative Control is provided by an Iterative Control Statement that repeatedly executes
instructions. Each is based on a given condition.
 A Control Structure is a set of instructions and the Control Statements controlling their
execution.

3.2 Boolean Expressions (Conditions)

 A Boolean Expression is an expression that evaluates to a Boolean value.


 Boolean Expressions are used to denote the conditions for Selection and Iterative Control
Statements.
 The Boolean Data Type contains two Boolean values, denoted as True and False in Python.

3.2.1 Relational Operators

 Relational Operators in Python are also called as Comparison Operators.


 Relational Operators are used to compare two expressions and return a Boolean
value.
 The Relational Operators in Python are shown in Figure 3-1.

Operator Description Example


== Equal to x == y
!= Not equal to x != y
< Less than x <y
> Greater than x >y
<= Less than or equal to x <= y
>= Greater than or equal to x >= y

Figure 3-1 The Relational Operators

 An Expression created using a Relational Operator is termed a Relational Expression.

3.2.2 Membership Operators


45
 The Membership Operators in Python are used to check whether an item is present in
the Sequence or not.
 Python provides Membership Operators in and not in for determining if a specific
value is in (or not in) a given list of values.
 The Membership Operators are given in Figure 3-2.
 The in Operator returns True if an item is found in the Sequence, otherwise returns False.
 The not in Operator returns True if an item does not found in the Sequence, otherwise
returns False.

Operator Description Example


in Returns True if an item is found in the Sequence. x in y
not in Returns True if an item does not found in the Sequence, x not in y

Figure 3-2 The Membership Operators

 The Membership Operators can also be used to check if a given string occurs within another
string,

>>>'Dr.' in 'Dr. Ashok'


True

3.2.3 Boolean Operators

 Boolean (Logical) Operators in Python are denoted by and, or, and not.
 Logical Operators are used to evaluate expressions and return a Boolean value.
 These Logical Operators can be used to construct arbitrarily complex Boolean Expressions.
 The Boolean Operators are shown in Figure 3-3.

Operator Description Example


and Returns True if both statements are x < 5 and x < 10
true
or Returns True if one of the x < 5 or x < 4
statements is true
not Reverse the result, returns False if not(x < 5 and x < 10)
the result is true

Figure 3-3 Boolean Operators

 In Python, Boolean values True and False have integer values 1 and 0, respectively.
 A Boolean Expression is an expression that results in a Boolean value that is either
True or False.
 Boolean Expressions can compare data of any type as long as both parts of the expression
have the same basic data type.
 Boolean Expressions do not necessarily contain Boolean Operators. For example, 10<= 20 is
a Boolean Expression.
 Boolean literals True and False are never quoted.
 Boolean operations have the lowest priority of all Python operations.

Bitwise Operators

 Bitwise Operators acts on bits and performs bit by bit operation.

46
Operator Description Example
& Bitwise AND x&y
| Bitwise OR x|y
~ Bitwise NOT ~x
^ Bitwise XOR x^y
>> Bitwise right shift x>>
<< Bitwise left shift x<<

Assignment Operators

 Assignment Operators are used to assign values to the variables.

Operator Description Example


= Simple Assignment Operator x=y+z
a+=b a
+= Add AND assignment operator
=a + b
a-
-= Subtract AND assignment operator =b a=
a-b
a*=b a
*= Multiply AND assignment operator
=a * b
a/=b
/= Divide AND assignment operator
a=a/b
a%=b a=
%= Modulus AND assignment operator
a%b
a//=b
//= Divide(floor) AND assignment operator
a=a // b
a**=b a
**= Exponent AND assignment operator
=a**b
a&=b a
&= Bitwise AND assignment operator
=a & b
a|=b
|= Bitwise OR assignment operator
a=a | b
a^=b
^= Bitwise exclusive OR and assignment operator
a=a ^ b
a>>=b
>>= Right shift AND assignment operator
a=a >> b
a <<=
<<= Left shift AND assignment operator b a= a
<< b

Special Operators

 There are some special types of operators in Python. They are:

Identity Operators

 is and is not are the identity operators both are used to check if two values are located on
the same part of the memory.
 Two variables that are equal does not imply that they are identical.

is True if the operands are identical


is not True if the operands are not identical
47
3.2.4 Operator Precedence and Boolean Expressions

 Operator Precedence also applies to Boolean Operators.


 Since Boolean Expressions can contain arithmetic as well as relational and Boolean operators,
the precedence of all operators needs to be collectively applied.
 An updated Operator Precedence table is given in Figure 3-4.

Operator Associativity
** (exponentiation) right-to-left
- (negation) left-to-right
* (mult), / (div), // (truncating div), % (modulo) left-to-right
+ (addition), - (subtraction) left-to-right
<, >, <=, >=, !=, == (relational operators) left-to-right
not left-to-right
and left-to-right
or left-to-right

Figure 3-4 Operator Precedence of Arithmetic, Relational, and Boolean Operators

 In the table, higher-priority operators are placed above lower-priority ones. Thus, we see
that all arithmetic operators are performed before any relational or Boolean operator.

3.2.5 Short-Circuit (Lazy) Evaluation

 Short-Circuit Evaluation means that when evaluating Boolean Expression like AND
and OR, we can stop as soon as we find the first condition which satisfies or
negates the expression.
 In Short-Circuit (lazy) Evaluation, the second operand of Boolean operators and and or is
not evaluated if the value of the Boolean expression can be determined from the first operand
alone.
 Short Circuit explained by official documentation:

Operation Result Description


x or y If x is false, then y else x Only evaluates the second argument (y) if the
first one is false
x and y If x is false, then x else y Only evaluates the second argument (y) if the
first one (x) is True
not x If x is false, then True, Not has a lower priority than non-Boolean
else False Operators

 In the Python programming language, Short-Circuit Evaluation is used.

3.2.6 Logically Equivalent Boolean Expressions

 Boolean Expression (or Logical Expression) evaluates to one of two states True or False.
 Python provides the Boolean type that can be either set to False or True.

Logically Equivalent Boolean Expressions


x<y is equivalent to not (x >=y)
x <= y is equivalent to not (x > y)
x == y is equivalent to not (x != y)
x != y is equivalent to not (x == y)
not (x and y) is equivalent to (not x) or (not y)

48
not (x or y) is equivalent to (not x) and (not y)

Figure 3-5 Forms of Logically Equivalent Boolean Expressions


 The last two equivalences above are referred to as De Morgan’s Laws.

What are Conditional Statements?

 Conditional Statements in Python are used to make decisions based on the


conditions.
 These conditions are specified by a set of Conditional Statements having Boolean
Expressions which are evaluated to a Boolean value True or False.
 Conditional Statements are handled by IF statements in Python.

3.3 Selection Control

 A Selection Control Statement is a Control Statement providing selective execution of


instructions.
 A Selection Control Structure is a given set of instructions and the Selection Control
Statement(s) controlling their execution.

3.3.1 If Statement

 An if statement is a Selection Control Statement based on the value of a given Boolean


expression.
 The if statement is used to execute a block of statements only when a given
condition is true.
 Statements that contain other statements are referred to as a Compound Statement.

Syntax:

if condition:
Statement(s)

 Here, the program evaluates the condition and will execute Statement(s) only if the condition
is True. If the condition is False, the Statement(s) is not executed.
 In Python, the body of the if statement is indicated by the indentation. The body starts with
an indentation and the first un-indented line marks the end.

Flowchart of Python if Statement

Figure 3-6 Operation of if Statement

Example 1:

if grade==100:
49
print(“Perfect Score”)

Example 2:

# Python program to illustrate if statement


Age=int(input("What is your Age? "))
if (Age >= 18):
print ("You are eligible to Vote.")
print ("I am not in If")

Output:

What is your Age? 15


I am not in If

if…else Statement

 The if…else statement executes a block of code if a specified condition is


True. If the condition is False, another block of code can be executed.

Syntax:

if condition:
Statement(s)
else:
Statement(s)

 The if..else statement evaluates test expression and will execute the body of if only when the
test condition is True.
 If the condition is False, the body of else is executed. Indentation (whitespace at the
beginning of a line) is used to separate the blocks.

Python if..else Flowchart

Figure 3.7 Operation of if..else Statement

Example 1:

if grade>=75:
print(“Distinction”)
else:
print(“Falling Grade”)

Example 2:

# Python Program to check if the number is Positive or Negative


50
n=int(input("Enter any number: "))
if n>0:
print("Positive Number")
else:
print("Negative Number")

Output:

Enter any number: 10


Positive Number

3.3.2 Indentation in Python

 Indentation in Python refers to the spaces that are used at the beginning of a
statement.
 The unique aspect of Python is that the amount of indentation of each program line is
significant.
 In most programming languages, indentation has no affect on program logic—it is simply
used to align program lines to aid readability.
 In Python, however, indentation is used to associate and group statements, as shown in
Figure 3-8.

Figure 3-8 Compound Statement in Python

 A header in Python starts with a keyword and ends with a colon.


 The group of statements following a header is called a suite.
 A header and its associated suite are together referred to as a clause.
 A compound statement in Python may consist of one or more clauses.
 While four spaces are commonly used for each level of indentation, any number of
spaces may be used, as shown in Figure 3-9.

Figure 3-9 Compound Statements and Indentation in Python

3.3.3 Multi-Way Selection

 A Multi-Way Selection Statement is used to execute at most ONE of the choices of a


set of statements presented.
 There are two means of constructing Multi-Way Selection in Python—one involving multiple
nested if statements, and the other involving a single if statement and the use of elif headers.
51
Nested if Statements

 If statements can be nested in Python, resulting in Multi-Way Selection.


 Python allows us to nest if statements within if statements. i.e., we can place an if statement
inside another if statement.
 Any number of these statements can be nested inside one another. Indentation is the only
way to figure out the level of nesting.

Syntax:

if condition:
Statements
else:
if condition:
Statements
else:
if condition:
Statements

Example 1:

#Python Program to print the Grade


Avg_Marks=int(input("Enter the marks : "))
if Avg_Marks >= 90:
print("A Grade")
else:
if Avg_Marks >= 80:
print("B Grade")
else:
if Avg_Marks >= 70:
print("C Grade")
else:
if Avg_Marks>=60:
print("D Grade")
else:
print("F Grade")

Output:

Enter the marks : 95


A Grade

Example 2:

# Python Program to check if the number is Positive or Negative or Zero


# Nested if Statement Example

n = float(input("Enter a number: "))


if n >= 0:
if n == 0:
print("Zero")
else:
print("Positive Number")
else:

52
print("Negative Number")

Output 1:

Enter a number: 5
Positive Number
Output 2:

Enter a number: -1
Negative Number

Output 3:

Enter a number: 0
Zero

Write a Python program that prompts the user for a given month (and year for
February), and displays how many days are in the month.

# Python program to print the Number of Days in a given month


Valid_Input=True
month=int(input("Enter the month (1-12): "))
#February
if month == 2:
y=int(input("Please enter the year in 4 digits : "))
if (y%4 == 0) and (not (y%100 == 0) or (y%400 == 0)):
No_of_days=29
else:
No_of_days=28
else:
if month in (1, 3, 5, 7, 8, 10, 12):
No_of_days=31
else:
if month in (4, 6, 9, 11):
No_of_days=30
else:
print("Invalid Month")
Valid_Input=False

if Valid_Input:
print("There are ",No_of_days," days in the month")

Output:

Enter the month (1-12): 6


There are 30 days in the month

The elif Header in Python

 Python has a header called elif (“else-if”) that provides Multi-Way Selection in a single if
statement
 All the headers of an if-elif statement are indented the same amount.

Syntax:

53
if (condition):
Statement
elif (condition):
Statement
.
.
else:
Statement

 The elif is short for else if. The elif statement allows us to check multiple expressions for
True and execute a block of code as soon as one of the conditions evaluates to True.
 If the condition for if is False, it checks the condition of the next elif block and so on.
 If all the conditions are False, the body of else is executed.
 Only one block among the several if...elif...else blocks is executed according to the
condition.
 There can be an arbitrary number of elif statements following an if.
Flowchart of if...elif...else

Figure 3-10 Operation of if...elif....else Statement

Example 1:

#Python Program to print the Grade


Avg_Marks=int(input("Enter the marks : "))
if Avg_Marks >= 90:
print("A Grade")
elif Avg_Marks >= 80:
print("B Grade")
elif Avg_Marks >= 70:
print("C Grade")
elif Avg_Marks>=60:
print("D Grade")
else:
print("F Grade")

Output:

Enter the marks : 82


B Grade

Example 2:

# Python program to display the number of days in a given month


print("This program will determine the number of days in a given month\n")
Valid_Input=True
54
month=int(input("Enter the month (1-12): " ))
# Determine the number of days in a month
# February
if month==2:
year=int(input("Please enter the year: "))
if (year%4==0) and (not (year%100==0) or (year%400==0)):
Num_Days=29
else:
Num_Days=28
# January, March, May, July, August, October, December
elif month in (1, 3, 5, 7, 8, 10, 12):
Num_Days=31
# April, June, September, November
elif month in (4, 6, 9, 11):
Num_Days=30
else:
print("*Invalid Value Entered -", month,"*")
Valid_Input=False

if Valid_Input:
print("There are", Num_Days,"days in the month")

Output:

This program will determine the number of days in a given month

Enter the month (1-12): 12


There are 31 days in the month
----------------------------------
This program will determine the number of days in a given month

Enter the month (1-12): 2


Please enter the year: 2020
There are 29 days in the month

3.4 Iterative Control

 An Iterative Control Statement is a Control Statement that allows for the repeated
execution of a set of statements.
 An Iterative Control Structure is a set of instructions and the Iterative Control Statement(s)
controlling their execution.
 Because of their repeated execution, Iterative Control Structures are commonly referred to as
“Loops.”

3.4.1 While Statement

 The while Statement is an Iterative Control Statement that repeatedly executes a set of
statements based on a provided Boolean expression (condition).
 All Iterative Control needed in a program can be achieved by use of the while statement.

Syntax:

while condition:
Statement(s)

55
 The Statement(s) within the loop are (re)executed as long as the condition of a while
statement is true.
 When the condition becomes false, program control passes to the line immediately following
the loop.
 It is possible that the first time a loop is reached, the condition may be false, and therefore
the loop would never be executed.

Flowchart of while loop

Example 1:

Write a Python program that sums the first n integers, for a given (positive) value n
entered by the user.

# Python program to find the Sum of first n integers


sum = 0
count = 0
n = int(input("Enter n: "))
while count <= n:
sum = sum + count
count = count + 1
print("The Sum is ", sum)

Output:

Enter the value of n: 5


The Sum is 15

Example 2:

Write a Python program to compute the factorial value of a given number.

# Python Program to compute the Factorial value of a number


n = int(input("Enter the Number: "))
i=1
f=1
while i<=n:
f=f*i
i=i+1

print("Factorial Value :", f)

Output:
56
Enter the Number: 5
Factorial Value : 120

While Loop with else clause

 The while loop can also have an optional else block.


 The else statement is executed when the condition becomes false.

Syntax:

while condition:
Statement(s)
else:
Statement(s)

Example:

#Python program to illustrate else with while


count = 0
while count < 5:
print(count, " is less than 5")
count = count + 1
else:
print(count, " is not less than 5")

Output:

0 is less than 5
1 is less than 5
2 is less than 5
3 is less than 5
4 is less than 5
5 is not less than 5

3.4.2 Input Error Checking

 The while statement is well suited for input error checking in a program. This is
demonstrated in the temperature conversion program in Figure 3-11.

# Temperature Conversion Program (Celsius-Fahrenheit / Fahrenheit-Celsius)


print("Enter (F) to convert Fahrenheit to Celsius")
print("Enter (C) to convert Celsius to Fahrenheit")
choice = input("Enter selection: ")
while choice != "F" and choice != "C":
choice = input("Please enter 'F' or 'C': ")
temp = int(input("Enter the temperature to convert: "))
if choice == 'F':
Converted_Temp = format((temp - 32) *5/9, '.1f')
print(temp, "degrees Fahrenheit equals", Converted_Temp, "degrees Celsius")
else:
Converted_Temp = format((9/5 * temp) + 32, '.1f')
print(temp, "degrees Celsius equals", Converted_Temp, "degrees Fahrenheit")

Figure 3-11 Temperature Conversion Program (Invalid Input Checking)

57
 The program continues to prompt the user until a valid temperature conversion, 'F' or 'C',
is entered. Thus, the associated input statement is contained within a while loop that
keeps iterating as long as variable which contains an invalid value.
 Once the user enters a proper value, the loop terminates allowing the program to
continue.
3.4.3 Infinite Loops

 An Infinite Loop is an Iterative Control Structure that never terminates.


 Infinite Loops are generally the result of programming errors.
 For example, if the condition of a while loop can never be false, an infinite loop will result
when executed.

Example:

# Addition of first n integers


sum = 0
count = 0
n = int(input("Enter the value of n : "))
while count <= n:
sum = sum + count

 Such Infinite Loops can cause a program to “hang,” that is, to be unresponsive to the user.
 In such cases, the program must be terminated by use of some special keyboard input (such
as ctrl-C) to interrupt the execution.

3.4.4 Definite vs. Indefinite Loops

 A Definite Loop is a program loop in which the number of times the loop will iterate
can be determined before the loop is executed.
 For example, the following while loop is a definite loop:

sum = 0
count = 1
n = input('Enter value: ')
while count <= n:
sum = sum + count
count = count + 1

 Although it is not known what the value of n will be until the input statement is executed, its
value is known by the time the while loop is reached. Thus, it will execute “n times.”
 An Indefinite Loop is a program loop in which the number of times that the loop will
iterate cannot be determined before the loop is executed.
 Consider the following while loop:

which = input("Enter selection: ")


while which != 'F' and which != 'C':
which = input("Please enter 'F' or 'C': ")

 In this case, the number of times that the loop will be executed depends on how many times
the user mistypes the input.
 Thus, a while statement can be used to construct both definite and indefinite loops.

3.4.5 Boolean Flags and Indefinite Loops

 A single Boolean variable used as the condition of a given control statement is called a
Boolean Flag.
 An Indefinite Loop implemented by a while loop.
58
Example:

# Python program using Boolean Flags and Indefinite Loops


number = 23
running = True
while running:
guess = int(input("Enter an integer: "))
if guess == number:
print("Congratulations, you guessed it.")
running = False # This causes the while loop to stop
elif guess < number:
print ("No, it is a little higher than that.")
else:
print("No, it is a little lower than that.")
else:
print("The while loop is over.")
print("Done")
Output:

Enter an integer: 50
No, it is a little lower than that.
Enter an integer: 22
No, it is a little higher than that.
Enter an integer: 23
Congratulations, you guessed it.
The while loop is over.
Done

Exercises:

1. What is a Control Structure?


2. What is a Control Statement?
3. What is a Boolean Expression?
4. Mention the Relational Operators in Python.
5. What are Membership Operators in Python?
6. What are Boolean Operators in Python?
7. Explain about the Precedence of Operators in Python.
8. What do you mean by Boolean Expression?
9. Write short notes on Short-Circuit (lazy) Evaluation.
10. What do you mean by Selection Control Statement?
11. Explain about the Selection Control Statement in Python.
12. What is meant by Indentation in Python?
13. Explain about the Multi-Way Selection Statement in Python.
14. What is an Iterative Control Statement?
15. Briefly explain about the while statement with syntax and example.
16. Write a brief note on Input Error Checking in Python.
17. What are Infinite Loops?
18. Distinguish between Definite and Indefinite Loops.
19. What is a Boolean Flag?
20. Write Python program to find the biggest among two numbers.
21. Write a Python program to check whether the given number is Odd or Even.
59
22. Write a Python program to add individual digits of an n digit number.

**********************

Chapter 4

************************************************************************
Lists
************************************************************************
Lists are just like Dynamic Sized Arrays. A single list may contain Data Types like Integers,
Strings, as well as Objects. Lists are mutable, and hence, they can be altered even after their
creation. In this Chapter, Lists, Tuples and other Sequences are discussed.

4.1 List Structures

 Lists are used to store data of different data type in a sequential manner.
 A list is a data structure in Python that is a mutable, or changeable, ordered sequence of
elements.

4.1.1 What is a List?

 A List is a Data Structure that holds an ordered collection of items.


 Each element inside the list is called an item.
 The list of items should be enclosed in square brackets.
 The list can contain data of different types.
 Once we have created a list, we can add, remove or search for items in the list.
 Since we can add and remove items, we say that a list is a mutable data type i.e. this
type can be altered.

Example:

MyList = ["Apple", "Orange", "Mango"]


print(MyList))

Output:

['Apple', 'Orange', 'Mango']

4.1.2 Common List Operations

 Operations commonly performed on lists include retrieve, update, insert, delete (remove) and
append.
 Figure 4-1 illustrates these operations on a list of integers.

60
Figure 4.1 Common List Operations
 The operation depicted in (a) retrieves elements of a list by index value. Thus, the value 50 is
retrieved at index 4 (the fifth item in the list).
 The replace operation in (b) updates the current value at index 4, 50, with 55.
 The insert operation in (c) inserts the new value 25 at index 2, thus shifting down all
elements below that point and lengthening the list by one.
 In (d), the remove operation deletes the element at index 6, thus shifting up all elements
below that point and shortening the list by one.
 The append operation in (e) adds a new value, 80, to the end of the list.

4.1.3 Python List Methods

 Python has a set of built-in methods that we can use on lists/arrays.

Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
extend() Add the elements of a list (or any iterable), to the end of the
current list
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the first item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list

Note: Python does not have built-in support for Arrays, but Python Lists can be used instead.

4.1.4 List Traversal

 A List Traversal is a means of accessing, one-by-one, the elements of a list.


 For example, to add up all the elements in a list of integers, each element can be accessed
one-by-one, starting with the first, and ending with the last element.
 Similarly, the list could be traversed starting with the last element and ending with the first.
To find a particular value in a list also requires traversal. We depict the tasks of summing and
searching a list in Figure 4-2.

61
Figure 4-2 List Traversal

4.2 Lists (Sequences) in Python

4.2.1 Python List Type

 A List in Python is a Mutable, Linear Data Structure of variable length, allowing


Mixed-Type elements.
 Mutable means that the contents of the list may be altered.
 Lists in Python use zero based indexing.
 Thus, all lists have index values 0 ... n-1, where n is the number of elements in the list.
 Lists are denoted by a comma-separated list of elements within square brackets as shown
below,

[1, 2, 3] ['One', 'Two', 'Three'] ['Apples', 50, True]

 An empty list is denoted by an empty pair of square brackets, [].


 Elements of a list are accessed by using an index value within square brackets.

lst = [1, 2, 3]

lst[0] ➝ 1 access of first element


lst[1] ➝ 2 access of second element
lst[2] ➝ 3 access of third element

Thus, for example, the following prints the first element of list lst

print(lst[0])

The elements in list lst can be summed as follows,

sum = lst[0] + lst[1] + lst[2]

4.2.2 Tuples

 A Tuple in Python is an immutable linear data structure, denoted by a comma-


separated list of elements within parentheses, allowing mixed-type elements.
 Thus, in contrast to lists, once a tuple is defined, it cannot be altered. Otherwise, tuples and
lists are essentially the same.

62
 To distinguish tuples from lists, tuples are denoted by parentheses instead of square brackets
as given below,
nums = (10, 20, 30)
student = ('John Smith', 48, 'Computer Science', 3.42)

 Another difference between tuples and lists is that tuples of one element must include a
comma following the element. Otherwise, the parenthesized element will not be made into a
tuple, as shown below,

CORRECT WRONG
>>> (1,) >>>(1)
(1) 1

 An empty tuple is represented by a set of empty parentheses, ().


 The elements of tuples are accessed the same as lists, with square brackets,

>>>nums[0] >>>student[0]
10 'John Smith'

 Any attempt to alter a tuple is invalid. Thus, delete, update, insert, and append operations
are not defined on tuples.

4.2.3 Sequences

 A Sequence in Python is a linearly ordered set of elements accessed by an index


number.
 Lists, Tuples, and Strings are all Sequences.
 Strings, like Tuples, are immutable; therefore, they cannot be altered.
 Python supports a variety of operations applicable to all Sequences, including Strings, Lists,
and Tuples.
 The sequence operations common to Strings, lists, and tuples are shown in Figure 4-3.

Figure 4-3 Sequence Operations in Python

 For any sequence s, len(s) gives its length, and s[k] retrieves the element at index k.
 The slice operation, s[index1:index2], returns a subsequence of a sequence, starting with
the first index location up to but not including the second.
 The s[ index :] form of the slice operation returns a string containing all the list elements
starting from the given index location to the end of the sequence.

63
 The count method returns how many instances of a given value occur within a sequence,
and the find method returns the index location of the first occurrence of a specific item,
returning -1 if not found.
 For determining only if a given value occurs within a sequence, without needing to know
where, the in can be used instead.
 The + operator is used to denote concatenation. Since the plus sign also denotes addition,
Python determines which operation to perform based on the operand types. Thus the plus
sign, +, is referred to as an Overloaded Operator. If both operands are numeric types,
addition is performed. If both operands are sequence types, concatenation is performed.
 The min/max operations return the smallest/largest value of a sequence, and sum returns
the sum of all the elements (when of numeric type).
 The comparison operator, == , returns True if the two sequences are the same length, and
their corresponding elements are equal to each other.

4.2.4 Nested Lists

 A Nested List is a List within a List.


 Lists and Tuples can contain elements of any type, including other sequences.
 Thus, Lists and Tuples can be nested to create arbitrarily complex data structures.

Create a Nested List

 A Nested List is created by placing a comma-separated sequence of sublists.

L = ['a', ['bb', ['ccc', 'ddd'], 'ee', 'ff'], 'g', 'h']

Access Nested List Items by Index

 The individual items in a Nested List can be accessed using multiple indexes.
 The indexes for the items in a nested list are illustrated as below:

L = ['a', 'b', ['cc', 'dd', ['eee', 'fff']], 'g', 'h']


print(L[2])
# Prints ['cc', 'dd', ['eee', 'fff']]
print(L[2][2])
# Prints ['eee', 'fff']
print(L[2][2][0])
# Prints eee

Negative List Indexing in a Nested List

 Negative indexes count backward from the end of the List. So, L[-1] refers to the last
item, L[-2] is the second-last, and so on.
 The negative indexes for the items in a nested list are illustrated as below:

64
L = ['a', 'b', ['cc', 'dd', ['eee', 'fff']], 'g', 'h']
print(L[-3])
# Prints ['cc', 'dd', ['eee', 'fff']]
print(L[-3][-1])
# Prints ['eee', 'fff']
print(L[-3][-1][-2])
# Prints eee

Change Nested List Item Value

 The value of a specific item in a Nested List can be changed by referring to its index number.

L = ['a', ['bb', 'cc'], 'd']


L[1][1] = 0
print(L)
# Prints ['a', ['bb', 0], 'd']

Add items to a Nested list

 The append() method is used to add new values at the end of the Nested List.

L = ['a', ['bb', 'cc'], 'd']


L[1].append('xx')
print(L)
# Prints ['a', ['bb', 'cc', 'xx'], 'd']

 The insert() method is used to insert an item at a specific position in a Nested List.

L = ['a', ['bb', 'cc'], 'd']


L[1].insert(0,'xx')
print(L)
# Prints ['a', ['xx', 'bb', 'cc'], 'd']

 The extend() method is used to merge one List into another .

L = ['a', ['bb', 'cc'], 'd']


L[1].extend([1,2,3])
print(L)
# Prints ['a', ['bb', 'cc', 1, 2, 3], 'd']

Remove items from a Nested List

 The pop() method modifies the List and returns the removed item.
L = ['a', ['bb', 'cc', 'dd'], 'e']
x = L[1].pop(1)
print(L)
# Prints ['a', ['bb', 'dd'], 'e']
# Removed item

65
print(x)
# Prints cc

 The del statement removes an element from the List.

L = ['a', ['bb', 'cc', 'dd'], 'e']


del L[1][1]
print(L)
# Prints ['a', ['bb', 'dd'], 'e']

 The remove() method searches for the first instance of the given element and removes it.

L = ['a', ['bb', 'cc', 'dd'], 'e']


L[1].remove('cc')
print(L)
# Prints ['a', ['bb', 'dd'], 'e']

Find Nested List Length

 The built-in len() function is used to find how many items a Nested sublist has.

L = ['a', ['bb', 'cc'], 'd']


print(len(L))
# Prints 3
print(len(L[1]))
# Prints 2

Iterate through a Nested List

 The for loop is used to iterate over the items of a Nested List.

L = [[1, 2, 3],[4, 5, 6],[7, 8, 9]]


for list in L:
for number in list:
print(number, end=' ')
# Prints 1 2 3 4 5 6 7 8 9

4.3 Iterating Over Lists (Sequences) in Python

 Python’s for statement provides a convenient means of iterating over lists (and other
sequences).

4.3.1 For Loops

 A for statement is an Iterative Control Statement that iterates once for each
element in a specified sequence of elements.
 Thus, for loops are used to construct definite loops.

Syntax:

for var in Sequence:


Statement(s)

 Here, var is the variable that takes the value of the item inside the Sequence on each
iteration.

66
 Loop continues until we reach the last item in the Sequence. The body of for loop is separated
from the rest of the code using indentation.

Example 1:

# Python program to illustrate for loop


n = int(input(“Enter n: “))
for i in range(0, n):
print(i)

Output:

Enter n: 5
1
2
3
4
5

Example 2:

# Python program to find the sum of all numbers stored in a list


numbers = [1, 2, 3, 4, 5]
sum = 0
# iterate over the list
for val in numbers:
sum = sum + val
print("The sum is", sum)

Output:

The sum is 15

4.3.2 The Built-in range Function

 The range() function in Python is used for generating a sequence of integers.


 It is used when a user needs to perform an action for a specified number of times.
 The range() function returns a sequence of numbers, starting from 0 by default, and
increments by 1 (by default), and stops before a specified number.
Syntax:
range(start, stop, step)

Parameter Description
Optional. An integer number specifying at which position to start.
start
Default is 0
Required. An integer number specifying at which position to stop
stop
(not included).
step Optional. An integer number specifying the increment. Default is 1

Note: The range(n) function yields the numbers 0, 1, ... n-1.

Example 1:

#Python program using range() function


n=int(input("Enter the value of n : "))

67
for i in range(1, n):
print(i)

Output:

Enter the value of n : 5


1
2
3
4

Example 2:

# Program to iterate through a list using indexing


Fruits = ['Apple', 'Orange', 'Mango']
# Iterate over the list using index
for i in range(len(Fruits)):
print("I like", Fruits[i])

Output:

I like Apple
I like Orange
​ I like Mango

for loop with else

 Python allows the else keyword to be used with the for loop.
 The else statement is optional and executes if the loop iteration completes normally.
 If the loop is terminated with a break statement, the else statement will not be executed.

Syntax:

for var in Sequence:


Statement(s)
else:
Statement(s)

Example 1:

# Python program to print the list of prime numbers up to n


n=int(input("Enter the value of n: "))
for i in range(1,n):
for j in range(2,i):
if i%j == 0:
break
else:
print(i, 'is a prime number')

Output:

Enter the value of n: 5


1 is a prime number
2 is a prime number
3 is a prime number

68
 The for...else statement can be used with the break keyword to run the else block only when
the break keyword was not executed.

Example 2:

# Program to display student's marks from record


student_name = 'Sam'
marks = {'Akash': 90, 'Abilash': 55, 'Ashok': 77}
for student in marks:
if student == student_name:
print(marks[student])
break
else:
print('No entry with that name found.')

Output:

No entry with that name found.

Nested Loops

 A Nested Loop is a loop inside a loop. The "inner loop" will be executed one time for each
iteration of the "outer loop".
 Python programming language allows us to use one loop inside another loop.

The syntax for a nested for loop statement in Python is as follows:

for var in Sequence:


for var in Sequence:
Statements(s)
Statements(s)

Example:

# Python program to illustrate nested for loops


for i in range(1, 5):
for j in range(i):
print(i, end=' ')
print()

Output:

1
22
333
4444

The syntax for a nested while loop statement in Python is as follows:


while expression:
while expression:
Statement(s)
Statement(s)

Example:

69
#Python program to display multiplication table using nested while loop
n=int(input("Enter n : "))
print("\n")
i=1
while i<=n:
j=1
while j<=n:
print(i,"*",j,'=',i*j)
j+=1
i+=1
print("\n")

Output:

Enter n : 3

1*1=1
1*2=2
1*3=3

2*1=2
2*2=4
2*3=6

3*1=3
3*2=6
3*3=9

Loop Control Statements

 Loop Control Statements change execution from its normal sequence.


 Python supports the following Loop Control Statements.

Break Statement

 The break statement in Python terminates the current loop and resumes execution at the
next statement.
 It brings control out of the loop.
 The break statement can be used in both while and for loops.

Syntax:

break

Example:

#Python program using break statement


for letter in 'Python':
if letter == 'h':
break
print('Current Letter:', letter)

Output:

Current Letter: P

70
Current Letter: y
Current Letter: t

Continue Statement

 The continue statement in Python returns the control to the beginning of the loop.
 The continue statement rejects all the remaining statements in the current iteration of the
loop and moves the control to the top of the loop.
 The continue statement can be used in both while and for loops.

Syntax:

continue

Example:

#Python program to illustrate continue statement


for letter in 'Python':
if letter == 'h':
continue
print('Current Letter:', letter)

Output:

Current Letter: P
Current Letter: y
Current Letter: t
Current Letter: o
Current Letter: n

Pass Statement

 The pass statement is a null statement.


 The interpreter does not ignore a pass statement, but nothing happens and the statement
results into no operation.
 To avoid compilation errors, we can use the pass statement.

Syntax:

pass

Example:

#Python program using pass statement


for letter in 'Python':
if letter == 'h':
pass
print('This is pass block')
print('Current Letter:', letter)

print("Good Bye!")

Output:

Current Letter: P
Current Letter: y
Current Letter: t
71
This is pass block
Current Letter: h
Current Letter: o
Current Letter: n
Good Bye!

4.3.3 Iterating Over List Elements vs. List Index Values

 The loop variable of the for loop must iterate over the index values of the list,

for k in range(len(grades)):
grades[k] = grades[k] + 1

 In such cases, the loop variable k is also functioning as an index variable.


 An Index Variable is a variable whose changing value is used to access elements of
an indexed data structure.
 However, there are times when the loop variable must iterate over the index values of a list
instead.
 A comparison of the two approaches is shown in Figure 4-4.

Loop variable iterating over the Loop variable iterating over the
elements of a sequence index values of a sequence
nums = [10, 20, 30, 40, 50, 60] nums = [10, 20, 30, 40, 50, 60]
for k in nums: for k in range(len(nums)):
sum = sum + k sum = sum + nums[k]
Figure 4-4 Iterating Over the Elements vs. the Index Values of a Given Sequence
 The range function may be given only one argument. In that case, the starting value of the
range defaults to 0.
 Thus, range(len(grades)) is equivalent to range(0,len(grades)).

4.3.4 While Loops and Lists (Sequences)

 The While Loop in Python is used to execute a block of statements repeatedly as


long as a condition is true.
 Lists in Python are just like dynamic sized arrays. Each element inside the list is called an
item.
 In Python programming, a List is created by placing all the items (elements) inside square
brackets [], separated by commas.

Example:

# Python program to search an element in the list


# Creating a List
List = []
n=int(input("Enter the total elements in the list: "))
# Adding elements to the List
i=1
while i<=n:
x=int(input("Enter the list element: "))
List.append(x)
i=i+1
print("\nThe List elements are: ")
print(List)
a=int(input("\nEnter the element to search: "))
Found_Item = False
for i in range(len(List)):
if List[i] == a:
72
Found_Item = True
print("\nItem Found")
break

if Found_Item == False:
print("\nItem not Found")

Output:

Enter the total elements in the list: 4


Enter the list element: 34
Enter the list element: 56
Enter the list element: 78
Enter the list element: 90

The List elements are:


[34, 56, 78, 90]

Enter the element to search: 78

Item Found

Exercises:

1. What is a List?
2. Mention the various operations that can be performed on a List.
3. Discuss about the List Methods.
4. What is meant by List Traversal?
5. What are sequences in Python?
6. What are Tuples in Python?
7. List the sequence operations that are common to Strings, Lists, and Tuples in Python.
8. What are Nested Lists?
9. Discuss about for loop in Python.
10. Write short notes on range() function in Python.
11. What are Nested Loops?
12. Explain briefly about the Loop Control Statements in Python.
13. What is an indexed variable?
14. Write a Python program to find the sum of 1 to n Numbers.
15. Write a Python program to print the first ‘n’ terms of the Fibonacci Series.
16. Write a Python program to find the Factorial value of a given Number.

*********************

73
UNIT - III

Chapter 5

*********************************************************************
Functions
*********************************************************************
A Function is a block of code that contains one or more Python statements and used for
performing a specific task. Most programs consist of groups of instructions, each of which
accomplishes a specific task. Such a group of instructions is referred to as a “routine.” Program
routines, called “Functions” in Python, are fundamental building blocks in Software Development.
In this Chapter, the concept of Functions is discussed in detail.

5.1 Program Routines

 A Program Routine is a named group of instructions that accomplishes some task.

5.1.1 What is a Function Routine?

 A Routine is a named group of instructions performing some task.


 A routine can be invoked (called) as many times as needed in a given program (Figure 5.1).

74
Figure 5.1 Program Routine

 When a routine terminates, execution automatically returns to the point from which it was
called.
 Such routines may be predefined in the programming language, or designed and
implemented by the programmer.
 A Function is Python’s version of a Program Routine. Some functions are designed to
return a value, while others are designed for other purposes.

5.1.2 Defining Functions

 A Function is a group of related statements that performs a specific task.


 A function in Python is defined by a def statement.

Syntax:

def function_name(parameters):
"""Docstring"""
Statement(s)
return [expression]

The function definition consists of the following components:

 A Keyword def that marks the start of the function header.


 A function name to uniquely identify the function. Function naming follows the same rules of
writing identifiers in Python.
 Parameters (arguments) through which we pass values to a function. They are optional.
 A colon (:) to mark the end of the function header.
 Optional documentation string (Docstring) to describe what the function does.
 One or more valid Python statements that make up the function body. Statements must have
the same indentation level (usually 4 spaces).
 An optional return statement to return a value from the function.
 Functions are generally defined at the top of a program. However, every function must be
defined before it is called.
 The number of items in a parameter list indicates the number of values that must be passed
to the function, called Actual Arguments (or simply “arguments”),
 Actual Arguments, or simply “arguments,” are the values being passed to a function.
 Formal Parameters, or simply “parameters,” are the receiving variables that are used in a
function.

Example 1:

# Python program to check whether the given number is odd or even


def OddEven( x ):
if (x % 2 == 0):
print("The given number is even")
else:
print("The given number is odd")

75
# Main Program
n=int(input("Enter the number: "))
OddEven(n)

Output:

Enter the number: 10


The given number is even

Example 2:

#Python function to swap two integers


def swap(x,y):
temp = x;
x = y;
y = temp;
print("x=",x)
print("y=",y)
# Main Program
x=int(input("Enter the value of x: "))
y=int(input("Enter the value of y: "))
swap(x,y)

Output:

Enter the value of x: 10


Enter the value of y: 20
x= 20
y= 10

Calling a Function

 The syntax for calling a Python function is as follows:

Function_Name>([<arguments>])

<arguments> are the values passed into the function. They correspond to
the <parameters> in the Python function definition. We can define a function that doesn’t take
any arguments, but the parentheses are still required. Both a function definition and a function
call must always include parentheses, even if they’re empty.

Value-Returning Functions

 Value-Returning Functions returns a value after the function executes.


 This is indicated in the function’s return statement.

The return statement

 The return statement is used to end the execution of the function call and “returns”
the result to the caller.
 The statements after the return statement are not executed.
 If the return statement is used without any expression, then the special value None is
returned.

Syntax:

return [expression]

76
 This statement can contain an expression that gets evaluated and the value is returned.
 If there is no expression in the statement or the return statement itself is not present inside
a function, then the function will return the None object.

Example:

# Python program to demonstrate Value-Returning Functions


def sum(a, b):
# Returns the sum of a and b
return a + b

# Calling Function
a=int(input("Enter a: "))
b=int(input("Enter b: "))
c=sum(a,b)
print("Sum =",c)

Output:

Enter a: 20
Enter b: 30
Sum = 50

Non-Value-Returning Functions

 Non-Value-Returning Functions do not return a value after the function executes.


 There is a fundamental difference in the way that Value-Returning and Non-Value-Returning
functions are called.
 A call to a Value-Returning function is an expression. For Example, c = sum(a, b).
 When Non-Value-Returning functions are called, however, the function call is a statement.
 Since such functions do not have a return value.
 It is incorrect to use a call to a Non-Value-Returning function as an expression.

Example:

# Python program to demonstrate Non-Value-Returning Functions


def DisplayMessage():
print("Sindhi College")
print("Chennai")

# Main Program
DisplayMessage()

Output:

Sindhi College
Chennai

5.1.3 Temperature Conversion Program

#Python Temperature Conversion Program using Functions


def convert_temp(scale=None, source_temp=None):
if scale == "F":
return 'C', (source_temp - 32.0) * (5.0/9.0)
77
elif scale == "C":
return 'F', (source_temp * (9.0/5.0)) + 32.0
else:
print("Needs to be (F) or (C)!")

scale = input("Select (F) or (C): " )


source_temp = int(input("Enter the temperature: " ))
s, m = convert_temp(scale, source_temp)
print(source_temp, "degrees", scale, "is", m, "degrees", s)

Output:

Select (F) or (C): C


Enter the temperature: 45
45 degrees C is 113.0 degrees F
---------------------------------------
Select (F) or (C): F
Enter the temperature: 113
113 degrees F is 45.0 degrees C

5.2 More on Functions

 A Function is a block of code which runs only when it is called.

5.2.1 Calling Value-Returning Functions

 Function calls to Value-Returning Functions can be used anywhere that a function’s return
value is appropriate.
 Most functions take arguments, perform some processing and then return a value to the
caller. In Python this is achieved with the return statement.

Example:

#Program program to find the square of a number


def Square(n):
return n*n

x=int(input("Enter the number: "))


S = Square(x)
print(S)

Output:

Enter the number: 5


25

 Python also has the ability to return multiple values from a function call. In this case the
return values should be a comma-separated list of values and Python then constructs
a tuple and returns this to the caller.

Example:

#Python Function to return multiple values


def Square(x,y):
return x*x, y*y

a=int(input("Enter the value of a: "))


b=int(input("Enter the value of b: "))
78
xsq, ysq = Square(a,b)
print(xsq)
print(ysq)

Output:

Enter the value of a: 10


Enter the value of b: 20
100
400

5.2.2 Calling Non-Value-Returning Functions

 Function calls to Non-Value-Returning Functions can be used anywhere that an executable


statement is allowed.
 Such function calls are statements, and therefore can be used anywhere that an executable
statement is allowed.

Example:

# Python program that does not return any value


def Display_Text():
print("Welcome to Python Programming")

Display_Text()

Output:

Welcome to Python Programming


5.2.3 Parameter Passing
 Parameter Passing is the process of passing arguments to a function.
 The terms parameter and argument can be used for the same thing: information that
are passed into a function.
 A Parameter is the variable listed inside the parentheses in the function definition.
 An Argument is the value that is sent to the function when it is called.
 Information can be passed into functions as arguments.
 Arguments are specified after the function name, inside the parentheses. We can add
as many arguments as we want, just separate them with a comma.

Actual Arguments vs. Formal Parameters


Actual Arguments
 Actual arguments are the values (or variables) / expressions that are used inside
the parentheses of a function call.
Example:
#Program program to find the square of a number
def Square(n): # Here, n in the function definition is the Formal Parameter.
return n*n

x=int(input("Enter the number : "))


S = Square(x) # Here, x in the function call is the Actual Argument
print(S)

Formal Parameters
79
 The Parameters defined as part of the function definition are called Formal
Parameters.
 These are the variables declared in function definition, and receive their values when a call to
that function is made.
 The value(s) of the actual parameters are copied to formal parameters when the call to that
function is made.
 The correspondence of actual arguments and formal parameters is determined by the order
of the arguments passed, and not their names.

Example:

def cube(x):
return x*x*x

Here, x in the function definition is the Formal Parameter.

Mutable vs. Immutable Arguments

Mutable Arguments

 A Mutable Argument can be changed after it is created.


 Parameters passed by calling functions may be modified by called functions.
 This process is known as “Pass-by-reference” or “call-by-reference”.
 In pass-by-reference the variable is passed into the function directly.
 Objects of built-in types like list, set, and dict are mutable.

Example:

# Python program to demonstrate call by reference


# Function Definition
def Add_Item(MyList):
MyList.append(50)
print("Inside Function :", MyList)

# Main Program
MyList = [10,20,30,40]
Add_Item(MyList)
print("Outside Function:", MyList)

Output:

Inside Function : [10, 20, 30, 40, 50]


Outside Function: [10, 20, 30, 40, 50]

Immutable Arguments

 An Immutable Argument cannot be changed after it is created.


 Parameters passed by calling functions cannot be modified by called functions.
 This process is known as ‘Pass-by-value’ or ‘call-by-value’.
 Objects of built-in types like int, float, bool, str, tuple, and Unicode are immutable.
 In Python, scalar values are sent by-value.

Example:

# Python program to demonstrate call by value


string = "Sindhi"
# Function Definition
80
def Test(string):
string = "Sindhi College"
print("Inside Function :", string)

# Main Program
Test(string)
print("Outside Function:", string)

Output:

Inside Function : Sindhi College


Outside Function: Sindhi

5.2.4 Keyword Arguments in Python

 A Positional Argument is an argument that is assigned to a particular parameter


based on its position in the argument list.

def Mortgage_Rate(Amount, Rate, Term):

Monthly_Payment = Mortgage_Rate(350000, 0.06, 20)

 Python provides the option of calling any function by the use of keyword arguments.
 A Keyword Argument is an argument that is specified by parameter name.
 This allows us to skip arguments or place them out of order.
 The Keyword arguments, by convention, do not have a space before or after the equal sign.

def Mortgage_Rate(Amount, Rate, Term):

Monthly_Payment = Mortgage_Rate(Rate=0.06, Term=20, Amount=350000)

 It is possible to call a function with the use of both Positional and Keyword arguments.
However, all positional arguments must come before all keyword arguments in the function
call, as shown below.

def Mortgage_Rate(Amount, Rate, Term):

Monthly_Payment = Mortgage_Rate(35000, Term=20, Rate=0.06)

Example:

# Python Function to illustrate Keyword Arguments


def PrintStr(str):
"This prints a passed string into this function"
print(str)
return

# Calling the PrintStr function


PrintStr(str = "My String")

Output:

My String

81
5.2.5 Default Arguments in Python

 A Default Argument is an argument that assumes a default value if the value is not
provided in the function call for that argument.

def Mortgage_Rate(Amount, Rate, Term = 20):

Monthly_Payment = Mortgage_Rate(35000, 0.62)

 In this case, the third argument in calls to function Mortgage_Rate is optional. If omitted,
parameter term will default to the value 20 (years) as shown.
 If, on the other hand, a third argument is provided, the value passed replaces the default
parameter value.
 All positional arguments must come before any default arguments in a function definition.

Example:

# Python Function using default arguments


def Print_Details(Name, Age = 20):
"This prints a passed info into this function"
print("Name : ", Name)
print("Age : ", Age)
return
# Calling the Print_Details function
Print_Details(Age=52, Name="Sam")
Print_Details(Name="Akash")

Output:

Name : Sam
Age : 52
Name : Akash
Age : 20
5.2.6 Variable Scope
 The Scope of a Variable is the portion of a program where the variable is
recognized
Local Scope and Local Variables
 A Local Variable is a variable that can be accessed only inside the function.
 Such variables are said to have Local Scope.
 The variables defined within a function are called Local Variables.

Example:

# Python function that uses the Local Variable S


def Func():
S="India is My Country"
print(S)

# Calling Function
Func()

Output:

India is My Country

82
 The Lifetime of a Variable is the period throughout which the variable exists in the
memory.
 Local Variables are automatically created (allocated memory) when a function is called, and
destroyed (deallocated) when the function terminates.
 Thus, the Lifetime of a Local Variable is equal to the duration of its function’s execution.

Global Variables and Global Scope

 A Global Variable is a variable that is defined outside of any function definition.


 Such variables are said to have Global Scope.
 A global variable can be accessed inside or outside of the function.

Example:

# Python function that uses Global Variable S


def Func():
print(S)

# Global Scope
S = "India is My Country"
Func()

Output:

India is My Country

 The use of global variables is considered bad programming practice.


 Another reason that the use of global variables is bad practice is related to code reuse. If a
function is to be reused in another program, the function will not work properly if it is reliant
on the existence of global variables that are nonexistent in the new program.
 Thus, it is good programming practice to design functions so all data needed for a function
(other than its local variables) are explicitly passed as arguments, and not accessed through
global variables.
The global Keyword
 The global Keyword is used to create a global variable inside a function.
 If we use the global keyword, the variable belongs to the global scope
Example:
# Python Function using global keyword
def MyFunc():
global x
x = "Wonderful"

# Calling Function
MyFunc()
print("Python is " + x)
Output:
Python is Wonderful
Exercises:

1. What is a Function Routine?


2. Write the syntax of defining a function in Python.
3. What are Actual Arguments?
4. How will you call a function?
83
5. What is the use of return statement in Python?
6. What is meant by Parameter Passing?
7. Distinguish between Actual Arguments and Formal Parameters.
8. What are Mutable and immutable Arguments?
9. What are Keyword Arguments in Python?
10. What are Default Arguments in Python?
11. Briefly explain about Variable Scope.
12. What are Local and Global variables?
13. Write a Python program to find the Factorial Value of a given number using functions.
14. Write a Python program to input an ‘n’ digit number and find its reverse using functions.

*********************

84
UNIT - IV

Chapter 6

*********************************************************************
Objects and Their Use
*********************************************************************
In Procedural Programming, Functions are the primary building blocks of program design. In
Object-Oriented Programming, Objects are the fundamental building blocks in which functions
(methods) are a component. In this Chapter, the concept of an Object and Turtle Graphics are
discussed.
6.1 Software Objects
 Objects are the fundamental component of Object-Oriented Programming.
 All values in Python are represented as Objects.
 This includes, for example, lists, as well as numeric values.
 The notion of software objects derives from objects in the real world.

6.1.1 What is an Object?

 An Object contains a set of attributes, stored in a set of instance variables, and a


set of functions called methods that provide its behavior.
 All objects have certain attributes and behavior.
 The attributes of a car, for example, include its color, number of miles driven, current location,
and so on. Its behaviors include driving the car (changing the number of miles driven
attribute) and painting the car (changing its color attribute), for example.
6.1.2 Object References
 Python is an Object-Oriented Programming language. Almost everything in Python is
an Object, with its properties and methods.
References in Python
 In Python, objects are represented as a reference to an object in memory.
 A reference is a value that references, or “points to,” the location of another entity.
 Thus, when a new object in Python is created, two entities are stored—the object, and a
variable holding a reference to the object. All access to the object is through the reference
value. This is shown in Figure 6-1 below.

Figure 6-1 Object References to Python Values


 The value that a reference points to is called the dereferenced value. This is the
value that the variable represents as shown in Figure 6-2.

Figure 6-2 Variables’ Dereferenced Values


 The reference value of a variable (that is, the location in which the corresponding
object is stored) can be determined by using the built-in function id.
85
>>> id(n) >>>id(k) >>> id(s)
505498136 505498136 505498296
 We see that the dereferenced values of n and k, 10, is stored in the same memory location
(505498136), whereas the dereferenced value of s, 20, is stored in a different location
(505498296).
 Even though n and k are each separately assigned literal value 10, they reference the same
instance of 10 in memory (505498136).
 Since integer values are immutable, it assigned both n and k to the same instance. This saves
memory and reduces the number of reference locations that Python must maintain.
The Assignment of References
 When one variable is assigned to another, it is the reference value that is assigned, not the
dereferenced value.
 When variable n is assigned to k, it is the reference value of k that is assigned, not the
dereferenced value 20, as shown in Figure 6-3.

k=20
n=k
>>>n
20
Figure 6-3 The Assignment of References
 To verify that two variables refer to the same object instance, we can either compare the two
id values by using the comparison operator, or make use of the provided is operator (which
performs id(k) == id(n)).

>>> id(k) >>>id(k) == id(n)


505498136 True
>>>id(n) >>>n is k
505498136 True

 Thus, both n and k reference the same instance of literal value 20.
 This occurred in the above example when n and k were separately assigned 20 because
integers are an immutable type, and Python makes attempts to save memory.
 In this case, however, n and k reference the same instance of 20 because assignment in
Python assigns reference values.
 When assigning variables referencing mutable values, such as lists, both variables reference
the same list instance as well.

Memory Deallocation and Garbage Collection

 Memory Allocation can be defined as allocating a block of space in the computer memory to
a program.
 Memory Deallocation is a process performed by the Operating System where a block of
information is released from memory so that it may be used by a different program
 To deallocate a memory location means to change its status from “currently in use” to
“available for reuse.”
 In Python, memory deallocation is automatically performed by a process called Garbage
Collection.
 Garbage Collection is a method of automatically determining which locations in
memory are no longer in use and deallocating them.
86
 The garbage collection process is ongoing during the execution of a Python program.

List Assignment and Copying

 Assignment with an = on lists does not make a copy. Instead, assignment makes the two
variables point to the one list in memory (Figure 6-4).

Figure 6-4 List Assignment

 Thus, any changes to the elements of list1 results in changes to list2,

>>>list1[0] = 5
>>>list2[0]
5

 A copy of the list can be made as follows,

>>>list2 = list(list1)

 list() is referred to as a list constructor. The result of the copying is depicted in Figure 6-5.

Figure 6-5 Copying of Lists by Use of the List Constructor

 A copy of the list structure has been made. Therefore, changes to the list elements of list1
will not result in changes in list2.

>>>list1[0] = 5
>>>list2[0]
10

 A Shallow Copy constructs a new compound object and then inserts references into
it to the objects found in the original.
 Shallow copy is different from assignment in that it creates a new object. So, if we make
changes to the new list, such as adding or removing items, it won’t affect the original list.

a = [[1, 2], [2, 4]]


b = a[:] # Shallow Copy

>> b.append([3, 6])


>> b
>> [[1, 2], [2, 4], [3, 6]]

>> a
>> [[1, 2], [2, 4]]

 A Deep Copy constructs a new compound object and then, recursively,


inserts copies into it of the objects found in the original.
 A Deep Copy operation makes a complete copy of a list.

87
 A deep copy operator is provided by the deepcopy() method of the copy module in Python.
 Creating a deep copy is slower, because we are making new copies for everything.

a = [[1, 2], [2, 4]]


>> import copy
>> b = copy.deepcopy(a) # Deep Copy
>> b[0].append(3) # Edit the first element (i.e. [1, 2])>> b
>> [[1, 2, 3], [2, 4]]

>> a
>> [[1, 2], [2, 4]] # Does not affect the original list

Differences between Shallow Copy and Deep Copy

 Deep Copy stores copies of an object's values, whereas Shallow Copy stores references to
the original memory address.
 Deep Copy doesn't reflect changes made to the new/copied object in the original object;
whereas, Shallow Copy does.

Example:

# Python program to copy a list using the built-in function list()


def Cloning(List1):
List_Copy = list(List1)
return List_Copy

# Main Program
List1 = [10, 20, 30, 40, 50]
List2 = Cloning(List1)
print("Original List :", List1)
print("After Cloning:", List2)

Output:
Original List : [10, 20, 30, 40, 50]
After Cloning: [10, 20, 30, 40, 50]

6.2 Turtle Graphics

 Turtle Graphics refers to a means of controlling a graphical entity (a “turtle”) in a


graphics window with x, y coordinates.
 A turtle can be used to draw lines as it travels, therefore having the ability to create various
graphical designs.
 Turtle Graphics was first developed for a language named Logo in the 1960s for teaching
children how to program.
 Python provides the capability of turtle graphics in the turtle Python Standard Library module.
 There may be more than one turtle on the screen at once.
 Each turtle is represented by a distinct object. Thus, each can be individually controlled by
the methods available for turtle objects.
 Turtle Graphics is introduced here for two reasons—first, to provide a means of better
understanding objects in programming, and second, to have some fun.

6.2.1 Creating a Turtle Graphics Window

 The onscreen pen that we use for drawing is called the turtle.

88
 The first step in the use of turtle graphics is the creation of a turtle graphics window (a turtle
screen).
 Figure 6-6 shows how to create a turtle screen of a certain size with an appropriate title bar.

Example:

# Python Program to create a Turtle Graphics Window with Specified Size


# Turt_Win.py
import turtle # Loads the turtle module
turtle.setup(500, 300) # Set the window size to 500 by 300 pixels
wn = turtle.Screen() # Creates a graphics window
wn.bgcolor("Cyan")
wn.title("Turtle Graphics Window")

Output:

Figure 6-6 Creating a Turtle Graphics Window

 If the import turtle form of import is used, each of the turtle graphics methods must be called
in the form turtle.methodname.
 The setup() method creates a graphics window of the specified size (in pixels). In this case,
a window of size 500 pixels wide by 300 pixels high is created.
 The center point of the window is at coordinate (0,0). Thus, x-coordinate values to the right
of the center point are positive values, and those to the left are negative values. Similarly, y-
coordinate values above the center point are positive values, and those below are negative
values.
 The bgcolor() method is used to change the background color of the turtle window from the
default white background color.

window = turtle.Screen()
window.bgcolor('blue')

6.2.2 The “Default” Turtle

 A “turtle” is an entity in a turtle graphics window that can be controlled in various ways.
 Turtles are objects like the graphics window.
 A “default” turtle is created when the setup method is called.
 The reference to this turtle object can be obtained by,
the_turtle = turtle.getturtle()
 The getturtle() method returns the reference to the default turtle and causes it to appear on
the screen.
 The initial position of all turtles is the center of the screen at coordinate (0,0), as shown in
Figure 6-7.

89
Figure 6-7 The Default Turtle

 The default turtle shape is an arrowhead.


 A turtle’s shape can be set to basic geometric shapes, or even made from a provided image
file.

6.2.3 Fundamental Turtle Attributes and Behavior

 Objects have both attributes and behavior.


 Turtle objects have three fundamental attributes: position, heading (orientation), and pen
attributes.

Absolute Positioning

 The setposition() method is used to change the turtle’s position through absolute
positioning by moving the turtle to a specific x, y coordinate location (Figure 6-8).

Example:

# Python Program to implement Absolute Positioning in Turtle Graphics


import turtle

# Set Window Size


window = turtle.Screen()
window.title("Absolute Positioning")

# Get Default Turtle and Hide


My_Turtle=turtle.getturtle()
My_Turtle.hideturtle()

#Create Square (Absolute Positioning)


My_Turtle.setposition(100, 0)
My_Turtle.setposition(100, 100)
My_Turtle.setposition(0, 100)
My_Turtle.setposition(0, 0)

Output:

Figure 6-8 Absolute Positioning of Turtle

 The hideturtle() method is used to hide the turtle.

90
 Since newly created turtles are positioned at coordinates (0, 0), the square will be displayed
near the middle of the turtle window.
 To draw the square, the turtle is first positioned at coordinates (100, 0), 100 pixels to the
right of its current position.
 Since the turtle’s pen is down, a line will be drawn from location (0, 0) to location (100, 0).
 The turtle is then positioned at coordinates (100, 100), which draws a line from the bottom-
right corner to the top-right corner of the square.
 Positioning the turtle to coordinates (0, 100) draws a line from the top-right corner to the
top-left corner.
 Finally, positioning the turtle back to coordinates (0, 0) draws the final line from the top-left
corner to the bottom-left corner.

Turtle Heading and Relative Positioning

 A turtle’s position can also be changed through relative positioning.


 In this case, the location that a turtle moves to is determined by its second fundamental
attribute, its heading.
 A newly created turtle’s heading is to the right, at 0 degrees.
 A turtle’s heading can be changed by turning the turtle a given number of degrees left,
left(90), or right, right(90).
 The forward() method moves a turtle in the direction that it is currently heading. An
example of relative positioning is given in Figure 6-9.

Example:

# Python Program to implement Relative Positioning in Turtle Graphics


import turtle

# Set Window Size


window = turtle.Screen()
window.title("Absolute Positioning")

# Get Default Turtle and Hide


My_Turtle=turtle.getturtle()
My_Turtle.hideturtle()

# Create Box (Relative Positioning)


My_Turtle.forward(100)
My_Turtle.left(90)
My_Turtle.forward(100)
My_Turtle.left(90)
My_Turtle.forward(100)
My_Turtle.left(90)
My_Turtle.forward(100)

Output:

Figure 6-9 Relative Positioning of Turtle

91
 Since turtles are initially positioned at coordinates (0, 0) with an initial heading of 0 degrees,
the first step is to move the turtle forward 100 pixels. That draws the bottom line of the
square.
 The turtle is then turned left 90 degrees and again moved forward 100 pixels. This draws the
line of the right side of the square.
 These steps continue until the turtle arrives back at the original coordinates (0, 0),
completing the square.
 The left() and right() methods change the turtle’s heading relative to its current heading.
 A turtle’s heading can also be set to a specific heading by use of method setheading:
the_turtle.setheading(90).
 In addition, method heading can be used to determine a turtle’s current heading.

 A turtle’s position can be changed using relative positioning by use of methods


setheading, left, right, and forward.

Pen Attributes

 The pen attribute of a turtle object is related to its drawing capabilities.


 The most fundamental of these attributes is whether the pen is currently “up” or “down,”
controlled by methods penup() and pendown().
 When the pen attribute value is “up,” the turtle can be moved to another location without
lines being drawn.
 This is especially needed when drawing graphical images with disconnected segments.
 The use of these methods is given in Figure 6-10.

Example:

# Python Program to implement penup and pendown methods in Turtle Graphics


import turtle

# Set Window Size


turtle.setup(800, 600)
window = turtle.Screen()
window.title("Drawing an A")

# Get Default Turtle and Hide


My_Turtle=turtle.getturtle()
My_Turtle.hideturtle()
My_Turtle.penup()
My_Turtle.setposition(-100, 0)
My_Turtle.pendown()
My_Turtle.setposition(0, 250)
My_Turtle.setposition(100, 0)
My_Turtle.penup()
My_Turtle.setposition(-64, 90)
My_Turtle.pendown()
My_Turtle.setposition(64, 90)

Output:

92
Figure 6-10 Example for penup and pendown Methods

 In this example, the turtle is hidden so that only the needed lines appear.
 Since the initial location of the turtle is at coordinate (0, 0), the pen is set to “up” so that the
position of the turtle can be set to (-100, 0) without a line being drawn as it moves.
 This puts the turtle at the bottom of the left side of the letter.
 The pen is then set to “down” and the turtle is moved to coordinate (0, 250), drawing as it
moves. This therefore draws a line from the bottom of the left side to the top of the “A.”
 The turtle is then moved (with its pen still down) to the location of the bottom of the right
side of the letter, coordinate (100, 0).
 To cross the “A,” the pen is again set to “up” and the turtle is moved to the location of the
left end of the crossing line, coordinate (-64, 90).
 The pen is then set to “down” and moved to the end of the crossing line, at coordinate (64,
90), to finish the letter.
 The pen size of a turtle determines the width of the lines drawn when the pen attribute is
“down.”
 The pensize() method is used to control the size of the pen.

My_Turtle.pensize(5)

 The width is given in pixels, and is limited only by the size of the turtle screen. Example pen
sizes are depicted in Figure 6-11.

pensize (1)
pensize(11)
prmsize(21)
pensize(41)

Figure 6-11 Example Turtle Pen Sizes

 The pencolor() method is used to select the color of the pen.

My_Turtle.pencolor('blue')
 The name of any common color can be used, for example 'white', 'red', 'blue', 'green', 'yellow',
'gray', and 'black'.
 Colors can also be specified in RGB (red/green/blue) component values.
 These values can be specified in the range 0–255 if the color mode attribute of the turtle
window is set as given below,

turtle.colormode(255)
My_Turtle.pencolor(238, 130, 238) # Violet

This provides a means for a full spectrum of colors to be displayed.

Example:

# Python program to implement pencolor method


import turtle
93
Colors = [ "red","purple","blue","green","orange","yellow"]
My_Pen = turtle.Pen()
turtle.bgcolor("black")
for x in range(360):
My_Pen.pencolor(Colors[x % 6])
My_Pen.width(x/100 + 1)
My_Pen.forward(x)
My_Pen.left(59)
Output:

6.2.4 Additional Turtle Attributes

 The details on the other attributes of a turtle that may be controlled are provided here.
 This includes whether the turtle is visible or not, the size, shape, and fill color of the turtle,
the turtle’s speed, and the tilt of the turtle.

Turtle Visibility

 The hideturtle() and showturtle() methods are used to control the turtle’s visibility.
 A turtle may be made invisible while being repositioned on the screen. In gaming, a turtle
might be made invisible when it meets its “demise.”

Turtle Size

 The resizemode() and turtlesize() methods are used to control the size of a turtle shape
(Figure 6-12).

# Set to allow user to change turtle size


My_Turtle.resizemode(‘user’)

# Set a new turtle size


My_Turtle.turtlesize(3, 3)

Figure 6-12 Changing the Size of a Turtle

Turtle Shape

 A turtle’s shape may be set to one of the provided shapes, a described polygon (or
collection of polygons), or an image.
 There are a number of ways that a turtle’s shape (and fillcolor) may be defined rather than
the default shape (the arrowhead) and fillcolor (black).
 A turtle may be assigned one of the following provided shapes: 'arrow', 'turtle', 'circle',
'square', 'triangle', and 'classic' (the default arrowhead shape), as shown in Figure 6-13.

94
Figure 6-13 Available Turtle Shapes

 The shape() and fillcolor() methods are used to set the shape and fill colors.

My_Turtle.turtle.shape('circle')
My_Turtle.fillcolor('white')

 New shapes may be created and added to the turtle screen’s shape dictionary.
 One way of creating a new is shape by providing a set of coordinates denoting a polygon, as
shown in Figure 6-14.

Example:

# Python Program to draw a Polygon


import turtle

# Set Window Size


turtle.setup(800, 600)
window = turtle.Screen()
window.title("My Polygon")

# Get Default Turtle


My_Turtle=turtle.getturtle()
turtle.register_shape('mypolygon', ((0, 0), (100, 0), (140, 40)))
My_Turtle.shape('mypolygon')
My_Turtle.fillcolor('white')

Output:

Figure 6-14 Creating a New Polygon Turtle Shape

 The register_shape() method is used to register the new turtle shape with the name
mypolygon.
 The new shape is provided by the tuple of coordinates in the second argument.
 These coordinates define the polygon shown in the figure.
 Once the new shape is defined, a turtle can be set to that shape by calling the shape()
method with the desired shape’s name.
 The fillcolor() method is then called to make the fill color of the polygon white.
 It is also possible to create turtle shapes composed of various individual polygons called
compound shapes.
 A turtle is able to stamp its shape on the screen, which remains there even after the turtle is
repositioned (or relocated).
 That means that we can create all sorts interesting graphic patterns by appropriately
repositioning the turtle, as shown in Figure 6-15.

95
Example:

# Python Program to draw a Polygon Design


import turtle

# Set Window Size


turtle.setup(800, 600)
window = turtle.Screen()
window.title("My Polygon Design")
# Get Default Turtle
My_Turtle=turtle.getturtle()
turtle.register_shape('mypolygon', ((0, 0), (100, 0), (140, 40)))
My_Turtle.shape('mypolygon')
My_Turtle.fillcolor('white')

for angle in range(0, 360, 10):


My_Turtle.setheading(angle)
My_Turtle.stamp()

Output:

Figure 6-15 Creating a Design from a Turtle using a Polygon Shape

 The for loop in the figure iterates variable angle over the complete range of degrees, 0 to
360, by increments of 10 degrees.
 Within the loop the turtle’s heading is set to the current angle.
 The stamp() method is used to stamp the polygon shape at the turtle’s current position.
 By varying the shape of the polygon and the angles that the turtle is set to, a wide range of
such designs may be produced.
 Another way that a turtle shape can be created is by use of an image. The image file used
must be a “gif file” (with file extension .gif).
 The name of the file is then registered and the shape of the turtle set to the registered name,

register_shape('image1.gif')
My_Turtle.shape('image1.gif')

Turtle Speed

 The speed() method is used to control the speed of a turtle.


 A turtle’s speed can be set to a range of speed values from 0 to 10, with a “normal” speed
being around 6.
 The following speed values can be set using a descriptive rather than a numeric value,
10: 'fast' 6: 'normal' 3: 'slow' 1: 'slowest' 0: 'fastest'

 Thus, a normal speed can also be set by the_turtle.speed('normal').

96
6.2.5 Creating Multiple Turtles

 It is possible to create and control any number of turtle objects.


 The Turtle() method can be used to create any number of turtle objects.
 For Example, to create a new turtle

turtle1 = turtle.Turtle()
turtle2 = turtle.Turtle()

 By storing turtle objects in a list, any number of turtles may be maintained,

turtles = []
turtles.append(turtle.Turtle())
turtles.append(turtle.Turtle())

Turtle Methods
Method Description

Turtle() It creates and returns a new turtle object


forward(x) It moves the turtle forward by the specified amount
backward(x) It moves the turtle backward by the specified amount
right(x) It turns the turtle clockwise
left(x) It turns the turtle counter clockwise
penup() It picks up the turtle’s Pen
pendown() Puts down the turtle’s Pen
up() Picks up the turtle’s Pen
down() Puts down the turtle’s Pen
color(x) Changes the color of the turtle’s pen
fillcolor(x) Changes the color of the turtle will use to fill a polygon
heading() It returns the current heading
position() It returns the current position
goto(x, y) It moves the turtle to position x, y
begin_fill() Remember the starting point for a filled polygon
end_fill() It closes the polygon and fills with the current fill color
dot() Leaves the dot at the current position
stamp() Leaves an impression of a turtle shape at the current location
shape(x) Should be ‘arrow’, ‘classic’, ‘turtle’ or ‘circle’

Exercises:

1. What is an Object?
2. What are Object References in Python?
3. What is meant by Garbage Collection?
4. What is meant by Shallow Copy in Python?
5. What is meant by Deep Copy in Python?
6. Distinguish between Shallow Copy and Deep Copy in Python.
7. Define Turtle Graphics.
8. What are pen attributes?
9. Explain the various methods used in Turtle Graphics.
10. Write a Python program to draw a square inside another square box.
11. Write a Python program to draw a Hexagon.
12. Write a Python program to draw a Star.
13. Write a Python program to draw concentric circles.
14. Write a Python program to draw a Human Face.

97
***********************

Chapter 7

************************************************************************
Modular Design
************************************************************************
Modules, like Functions, are the fundamental building block in Software Development. In
complex software systems, programs are organized at a higher level as a set of Modules, each
module containing a set of functions (or objects). The concept of Modular Design are discussed in
this chapter.

7.1 Modules

 Modules are Python .py files that consist of Python code. Any Python file can be referenced as
a module.
 A Python file called hello.py has the module name of hello that can be imported into other
Python files or used on the Python command line interpreter.
 Modules can define functions, classes, and variables that we can reference in other
Python .py files or via the Python command line interpreter.

7.1.1 What is a Module?

 A Module is a file consisting of Python code.


 An important aspect of well-designed software is that programs are designed as a collection
of modules.
 Modules generally consist of a collection of functions (or other entities).
 The Python turtle module is an example of a software module.
 The use of modules has a number of advantages (Figure 7.1).

 SOFTWARE DESIGN
- Provides a means for the development of well-designed programs
 SOFTWARE DEVELOPMENT
- Provides a natural means of dividing up programming tasks
- Provides a means for the reuse of program code
 SOFTWARE TESTING
- Provides a means of separately testing parts of a program
- Provides a means of integrating parts of a program during testing
 SOFTWARE MODIFICATION AND MAINTENANCE
- Facilitates the modification of specific program functionalities

Figure 7.1 Advantages of Modular Programming

 Modular design allows large programs to be broken down into manageable size parts, in
which each part (module) provides a clearly specified capability.
 It aids the software development process by providing an effective way of separating
programming tasks among various individuals or teams.
 It allows modules to be individually developed and tested, and eventually integrated as a part
of a complete system.
98
 Modular design facilitates program modification since the code responsible for a given aspect
of the software is contained within specific modules, and not distributed throughout the
program.

7.1.2 Module Specification

 Every module needs to provide a specification of how it is to be used. This is referred to as


the module’s interface.
 Any program code making use of a particular module is referred to as a client of the module.
 A module’s specification should be sufficiently clear and complete so that its clients can
effectively utilize it.
 For example, numPrimes is a function that returns the number of primes in a given integer
range, as shown in Figure 7-2.

def numPrimes(start, end):


“””Returns the number of primes between start and end. “””

Figure 7-2 docstring Specification

 The function’s specification is provided by the line immediately following the function header,
called a docstring in Python.
 A docstring is a string literal denoted by triple quotes given as the first line of certain
program elements.
 The docstring of a particular program element can be displayed by use of the __doc__
extension,

>>>print(numPrimes.__doc__)

Returns the number of primes between start and end.

 This provides a convenient way for discovering how to use a particular function without
having to look at the function definition itself.
 Some software development tools also make use of docstrings.
 A more complete docstring specification is given in Figure 7-3.

def numPrimes(start, end):


“””Returns the number of primes between start and end, inclusive,

Returns -1 if start is greater than end.


“””
Figure 7-3 A More Complete docstring Specification

 This docstring follows the Python convention of putting a blank line after the first line of the
docstring, which should be an overall description of what the function does, followed by an
arbitrary number of lines providing additional details.
 These additional lines must be indented at the same level, as shown in the figure. Appropriate
use of this function by a client is given below. .
.
first_num = int(input('Enter the start of the range: '))
second_num = int(input('Enter the end of the range: '))
result = numprimes(first_num, second_num)
if result == -1:
print('* Invalid range entered *')
else:
print('The number of primes between', first_num, 'and', second_num, 'is', result)

 In this example, the user inputs a start and end value for the range of integers to check.

99
 Since the user may inappropriately enter a start value greater than the value of the end value,
a check is made for a returned value of -1 after the call to numprimes.
 If - 1 is found, then an error message is output; otherwise, the result is displayed.

7.2 Top-Down Design

 Top-Down Design is an approach for deriving a modular design in which the overall
design of a system is developed first, deferring the specification of more detailed
aspects of the design until later steps.

7.2.1 Developing a Modular Design of the Calendar Year Program

 The goal of modular design is that each module provides clearly defined
functionality, which collectively provides all of the required functionality of the
program.
 To develop a modular design for the calendar year program using a top-down design
approach, the three overall steps of the program are getting the requested year from the
user, creating the calendar year structure, and displaying the year. This is depicted in Figure
7-4.

Figure 7-4 First Stage of a Modular Design of the Calendar Year Program

 Modules get year and display calendar year are not complex enough to require further
breakdown. Module construct calendar year, on the other hand, is where most of the work is
done, and is therefore further broken down. Figure 7-5 contains the modules of this next
design step.

Figure 7-5 Second Stage of Modular Design of a Calendar Year Program

 In order to construct a calendar year, it must be determined whether the year is a leap year,
what day of the week January 1st of that year falls on, and how many days are in each
month (accounting for leap years).
 Thus, modules leap year, day of week January1, and num days in month are added as
submodules of module construct calendar year.
 The calendar month for each of the twelve months must then be individually constructed,
handled by module construct calendar month.

7.2.2 Specification of the Calendar Year Program Modules

100
 The modular design of the calendar year program provides a high-level view of the program.
However, there are many issues yet to resolve in the design.
 Since each module is to be implemented as a function, we need to specify the details of each
function.
 For example, for each function it needs to be decided if it is a value-returning function or a
non-value-returning function; what parameters it will take; and what results it will produce.
 We give such a specification in Figure 7-6 using Python docstrings.
 This stage of the design provides sufficient detail from which to implement the program.

101
Figure 7-6 Calendar Year Module Specification

 The main module provides the overall construction of the program. It simply displays the
program greeting, calls module getYear to get the year from the user, calls module
constructCalYear to construct the year, and finally calls module displayCalendar to display
the calendar year. The only detail that the main module is concerned with is allowing the
user to keep displaying another calendar year, or enter 21 to terminate the program. This is
controlled by Boolean variable terminate.

 The first module called, getYear, returns the integer value entered by the user. The
module’s specification indicates that it returns an integer value between 1800 and 2099,
inclusive; or 21 (if the user decides to terminate the program). Therefore, it is the
responsibility of the module to ensure that no other value is returned. This relieves the
main module of having to check for bad input.

 The next module that the main module uses is module constructCalYear. This module
returns a list of twelve sublists, one for each month, in which each sublist begins with the
name of the month (as a string value), followed by each of the weeks in the month, each
week formatted as a single string. The module’s specification indicates that it is to be
passed a year between 1800 and 2099, inclusive. Therefore, any year given to it that is
outside that range violates its condition for use, and therefore the results are not
guaranteed.

 The last module called from the main module is module displayCalendar. It is given a
constructed calendar year, as constructed by module constructCalMonth.

 Based on the modular design of the calendar year program, constructCalYear is the only
module relying on the use of submodules, specifi cally modules leapYear, dayOfWeekJan1,
numDaysInMonth, and constructCal. The leapYear module determines whether a given a
year is a leap year or not, returning a Boolean result. Module dayOfWeekJan1 returns the
day of the week for January 1st of the provided year. Boolean value leap_year must also be
provided to the module, needed in the day of the week algorithm on which the module is
based. Module numDaysInMonth must be passed an integer in the range 1–12, as well as a
Boolean value for leap_year. This is so that the module can determine the number of days
in the month for the month of February.

 Finally, constructCalMonth is given a month number, the day of the week of the fi rst day of
the month (1-Sun, 2-Mon, . . ., 0-Sat) and the number of days in the month. With this
information, module constructCalYear can construct the calendar list and its sublists to be
displayed. Finally, module displayCalendarMonth is given a formatted calendar year. Its job
is to display the calendar year three months across.

7.3 Python Modules


102
7.3.1 What is a Python Module?

 A Python Module is a file containing Python definitions and statements. When a


Python file is directly executed, it is considered the main module of a program.
 Main modules are given the special name __main__. Main modules provide the basis for a
complete Python program.
 They may import (include) any number of other modules (and each of those modules import
other modules, etc.).
 Main modules are not meant to be imported into other modules.
 The imported modules may contain a set of statements. The statements of imported modules
are executed only once, the first time that the module is imported.
 The Python Standard Library contains a set of predefined Standard (built-in)
modules.
 Python modules provide all the benefits of modular software design.
 By convention, modules are named using all lower case letters and optional underscore
characters.

7.3.2 Modules and Namespaces

 A Namespace is a container that provides a named context for a set of identifiers.


 Every module in Python has its own namespace.
 Namespaces enable programs to avoid potential name clashes by associating each identifier
with the namespace from which it originates.
 A Name Clash is when two distinct entities with the same name become part of the
same scope.
 Name clashes can occur, for example, if two or more Python modules contain identifiers with
the same name and are imported into the same program, as shown in Figure 7-7.

Figure 7-7 Example Name Clash of Imported Functions

 In this example, module1 and module2 are imported into the same program. Each module
contains an identifier named double, which return very different results. When the function
call double(num_list) is executed in main, there is a name clash. Thus, it cannot be
determined which of these two functions should be called. Namespaces provide a means for
resolving such problems.
 In Python, each module has its own namespace. This includes the names of all items in the
module, including functions and global variables—variables defined within the module and
outside the scope of any of its functions.
103
 Thus, two instances of identifier double, each defined in their own module, are distinguished
by being fully qualified with the name of the module in which each is defined:
module1.double and module2.double. Figure 7-8 illustrates the use of fully qualified
identifiers for calls to function double.

Figure 7-8 Example Use of Fully Qualified Function Names

7.3.3 Importing Modules

 In Python, the main module of any program is the first (“top-level”) module
executed.
 When working interactively in the Python shell, the Python interpreter functions as the main
module, containing the global namespace.
 The namespace is reset every time the interpreter is started (or when selecting Shell ➝
Restart Shell.
 The module __builtins__ is automatically imported in Python programs, providing all the
built-in constants, functions, and classes.

The import Statement

 The import statement is used to import the module in a Python program.


 An import statement is made up of the import keyword along with the name of the module.
 In a Python file, this will be declared at the top of the code.

Syntax:

import modulename

Example:

import math
print(math.pi)

Output:

3.141592653589793

 The import statement allows us to import one or more modules into our Python program,
letting us make use of the definitions constructed in those modules.

The “from-import” Form of Import

 Python also provides an alternate import statement of the form

104
from modulename import something

where something can be a list of identifiers, a single renamed identifier, or an asterisk, as


shown below,

(a) from modulename import func1, func2


(b) from modulename import func1 as new_func1
(c) from modulename import *

 In example (a), only identifiers func1 and func2 are imported.


 In example (b), only identifier func1 is imported, renamed as new_func1 in the
importing module.
 In example (c), all of the identifiers are imported, except for those that begin with two
underscore characters, which are meant to be private in the module,

 With the from-import form of import, imported identifiers become part of the importing
module’s namespace. Because of the possibility of name clashes, import modulename is the
preferred form of import in Python.

Example 1:

from math import pi


# In the above example, we used math.pi. Here we have used pi directly.
print(pi)

Output:
3.141592653589793

Example 2:

#Python program to find factorial


from math import *
print(pi)
print(factorial(5))

Output:
3.141592653589793
120

Differences between the import modulename and from modulename import forms of
Python

 While using import modulename, the namespace of the imported module does not become
part of the namespace of the importing module.
 Therefore, identifiers of the imported module must be fully qualified in the importing module.
 In contrast, when using from-import, the imported module’s namespace becomes part of the
importing module’s namespace.
 Thus, imported identifiers are referenced without being fully qualified.
 The from modulename import func1 as new_func1 form of import is used when identifiers in
the imported module’s namespace are known to be identical to identifiers of the importing
module.
 In such cases, the renamed imported function can be used without needing to be fully
qualified.

105
 Finally, using the from modulename import * form of import in example (c), although
convenient, makes name clashes more likely.
 This is because the names of the imported identifiers are not explicitly listed in the import
statement, creating a greater chance that the programmer will unintentionally define an
identifier with the same name as in the importing module.
 And since the from-import form of import allows imported identifiers to be accessed without
being fully qualified, it is unclear in the importing module where these identifiers come from.

Aliasing Modules
 It is possible to modify the names of modules and their functions within Python by using the
as keyword.
 The construction of this statement looks like this:

import [module] as [another_name]

Example:

import math as m
print(m.pi)
print(m.e)
Within the program, we now refer to the pi constant as m.pi rather than math.pi.

Note: We can also create our own modules for ourselves and for other programmers to use in
future programs.

Module Private Variables

 In Python, all identifiers in a module are “public” which can be accessed by any other module
that imports it.
 Variables beginning with two underscores are said to be Private Variables.
 Such entities, therefore, should not be accessed.
 It does not mean that they cannot be accessed, however. There is one situation in which
access to private variables is restricted.
 When the from modulename import * form of import is used to import all the identifiers of a
module’s namespace, names beginning with double underscores are not imported.
 Thus, such entities become inaccessible from within the importing module.

7.3.4 Module Loading and Execution

 Each imported module of a Python program needs to be located and loaded into memory.
Python first searches for modules in the current directory.
 If the module is not found, it searches the directories specified in the PYTHONPATH
environment variable.
 If the module is still not found (or PYTHONPATH is not defined), a Python installation-specific
path is searched (e.g., C:\Python32\Lib).
 If the program still does not find the module, an error (ImportError exception) is reported.
 If we wish to develop a module made available to other programs, then the module can be
saved in our own Python modules directory specified in the PYTHONPATH, or stored in the
particular Python installation Lib directory.
 When a module is loaded, a compiled version of the module with file extension .pyc
is automatically produced.
 Then, the next time that module is imported, the compiled .pyc file is loaded, rather than
the .py file, to save the time of recompiling.
 The reload() function reloads a previously imported module.

106
Built-in Function dir()

 The dir() function is a built-in function used to list all the function names (or variable names)
in a module.

Syntax:

dir ([object])

Example 1:

>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__',
'__spec__']

Example 2:

# Python dir() function example


lang = ("C","C++","Java","Python")
# Calling function
att = dir(lang)
# Displaying result
print(att)

Output:

['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__',


'__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__',
'__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__',
'__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__',
'__sizeof__', '__str__', '__subclasshook__', 'count', 'index']

7.3.5 Local, Global, and Built-in Namespaces in Python

 A Namespace in Python is a collection of names.


 The three namespaces that are referenced (“active”) during a Python program’s execution are:
the local namespace, the global namespace, and the built-in namespace,
 The Local Namespace is the namespace of the currently executing function (if any).
 The Global Namespace contains the identifiers of the currently executing module.
 The Built-in Namespace contains the names of all the built-in functions, constants, and so
on, in Python.

 When Python looks for an identifier, it first searches the local namespace (if defined), then
the global namespace, and finally the built-in namespace.
 Thus, if the same identifier is defined in more than one of these namespaces, it becomes
masked, as depicted in Figure 7-9.

107
Figure 7-9 Local, Global, and Built-in Namespaces of Python

 Functions sum and max are built-in functions in Python, and thus in the built-in namespace.
 Built-in function sum returns the sum of a sequence (list or tuple) or integers. Built-in
function max returns the largest value of a string, list, tuple, and other types.

7.3.6 A Programmer-Defined Stack Module

 A Stack is a Linear Data Structure that stores items in a Last-In-First-Out (LIFO)


manner.
 In Stack, a new element is added at one end and an element is removed from that end only.
 Stacks are used to temporarily store and retrieve data.
 There are two types of operations in Stack-

 Push– adds an element at the top of the stack


 Pop– removes an element from the top of the stack.

 A stack can be viewed as a list that can be accessed only at one end, as depicted in Figure
7-10.

Figure 7-10 Stack Mechanism

 In the above example, three items are pushed on the stack, denoted by A, B, and C.
 First, item A is pushed, followed by item B, and then item C.
 After the three items have been placed on the stack, the only item that can be accessed or
removed is item C, located at the top of stack .
 When C is retrieved, it is said to be popped from the stack, leaving item B as the top of stack.
 Once item B is popped, item A becomes the top of stack.
 Finally, when item A is popped, the stack becomes empty. It is an error to attempt to pop an
empty stack.

Example:

# Python program to implement stack operation using list


Stack = []
while True:
print('1. Push')
print('2. Pop')
print('3. Display')
print('4. Quit')
ch = int(input("Enter your choice : "))

108
if ch == 1:
x=input("Enter the element to push : ")
Stack.append(x)
elif ch==2:
print("Popped value: ", Stack.pop())
elif ch==3:
print("The Stack elements are")
print(Stack)
elif ch==4:
break

Output:

1. Push
2. Pop
3. Display
4. Quit
Enter your choice : 1

Enter the element to push : A


1. Push
2. Pop
3. Display
4. Quit
Enter your choice : 1
Enter the element to push : B
1. Push
2. Pop
3. Display
4. Quit
Enter your choice : 1
Enter the element to push : C
1. Push
2. Pop
3. Display
4. Quit
Enter your choice : 3
The Stack elements are
['A', 'B', 'C']
1. Push
2. Pop
3. Display
4. Quit
Enter your choice : 2
Popped value: C
1. Push
2. Pop
3. Display

7.3.7 A Palindrome Checker Program

Write a Python program to determine if a given string is a palindrome.

The palindrome is a word, phrase or number that reads the same backward as forward, i.e., any
number or a word is said to be a palindrome if the original value and the reverse of it are the
same.

109
# Python program using function to check whether the given string is palindrome or not
def Check_Palindrome(S):
if len(S) < 1:
return True
else:
if S[0] == S[-1]:
return Check_Palindrome(S[1:-1])
else:
return False
n=str(input("Enter the string : "))
if (Check_Palindrome(n)==True):
print("The given string is a palindrome.")
else:
print("The given string is not a palindrome.")

Output:

Enter the string : mom


The given string is a palindrome.
---------------------------------------------
Enter the string : hello
The given string is not a palindrome.
Exercises:

1. What is a Module?
2. What are the advantages of using modules?
3. What do you mean by module specification?
4. Define Top-Down Design.
5. What is a Python Module?
6. What is a Namespace?
7. How will you import modules into your Python programs?
8. What do you mean by Aliasing Modules?
9. What are Module Private Variables?
10. How will you Load and Execute the Module?
11. Write short notes on dir() function in Python.
12. What are Local, Global, and Built-in Namespaces in Python?
13. Define Stack.
14. Write a Python program to implement the stack operations using Lists.
15. Write a Python program to check whether the given string is Palindrome or not.

************************

110
Chapter 8

**************************************************************************************
Text Files
**************************************************************************************
Files are named locations on disk to store related information. They are used to store data
permanently on a Non-Volatile Memory, such as Hard Disks. Python makes it easy to work with
Files and Text.

Text Files are structured as a sequence of lines, where each line includes a sequence of
characters. Python provides some built-in functions for reading, writing, or accessing files. In this
chapter, we discuss the various operations that can be performed on Text Files.

8.1 What is a Text File?

 A Text File contains the data in the form of sequence of characters.


 In addition to printable characters, text files also contain the nonprinting newline character,
\n, to denote the end of each text line.
 The newline character causes the screen cursor to move to the beginning of the next screen
line.
 Thus, text files can be directly viewed and created using a text editor.

 A Binary File contains the data in the form of 0 and 1 (series of binary values).
 Image files such as .jpg, .png, .gif, etc., and documents such as .doc, .xls, .pdf, etc., all of
them constitute binary files.

8.2 Using Text Files

 Fundamental operations of all types of files include opening a file, closing a file, reading from
a file and writing to a file.

8.2.1 Opening Text Files

 The built-in open() function is used to open a file for reading or writing.
 All files must first be opened before they can be used.
 In Python, when a file is opened, a file object is created that provides methods for accessing
the file.

Syntax:

File_Object = open("File_Name","Access_Mode")

Here,

 The File_Name refers to the file which we want to open.


 The Access_Mode specifies the mode in which the file has to be opened.

File Access Modes

 Access Modes govern the type of operations possible in the opened file. There are 6 access
modes in python.

1. Read Only (‘r’): Open the file for reading.


2. Read and Write (‘r+’): Open the file for reading and writing.
3. Write Only (‘w’): Open the file for writing.
111
4. Write and Read (‘w+’): Open the file for reading and writing.
5. Append Only (‘a’): Open the file for writing. The data being written will be inserted at the
end, after the existing data.
6. Append and Read (‘a+’): Open the file for reading and writing. The data being written will
be inserted at the end, after the existing data.

Opening a file for Reading

 The open() function is used to open a file for reading.

fp = open('MyFile.txt','r')

 The first argument is the file name to be opened, 'MyFile.txt'. The second argument, 'r',
indicates that the file is to be opened for reading.

Opening a file for Writing

 To open a file for writing, the open function is used as shown below,

fp = open('MyFile.txt','w')

 In this case, 'w' is used to indicate that the file is to be opened for writing. If the file already
exists, it will be overwritten.
 When using a second argument of 'a', the output will be appended to an existing file.
 When opening files for writing, there is not much chance of an I/O error occurring. The
provided file name does not need to exist since it is being created (or overwritten).
 Thus, the only error that may occur is if the file system (such as the hard disk) is full.

8.2.2 Closing Text Files

 The close() function is used to close the file.


 This method closes the file and frees the memory space acquired by that file.
 A closed file cannot be read or written any more.

Syntax:

File_Object.close()

Example:

MyFile.close()

8.2.3 Reading Text Files

 There are three ways to read the data from a text file.

i) read()

 The read() function reads the specified number of bytes from the file. If no n specified, reads
the entire file.

Syntax:

File_Object.read([n])

112
ii) readline()

 The readline() function reads one complete line from the file. It has a trailing newline ("\n")
at the end of the string returned. It takes a parameter n, which specifies the maximum
number of bytes that will be read. When the end-of-file is reached, it returns an empty string.

Syntax:

File_Object.readline([n])

iii) readlines()

 The readlines() function reads all the lines and returns a list containing the lines. An empty
string is returned only when EOF is encountered immediately.

Syntax:

File_Object.readlines()

Note: ‘\n’ is treated as a special character of two bytes

Example:

# Python program to read a file


fp = open('MyFile.txt',”r”)
while True:
line = fp.readline()
print(line)
# Check if line is not empty
if not line:
break
fp.close()

Output:

This is Delhi

This is Paris

This is London

8.2.4 Writing Text Files

 There are two ways to write in a file.

i) write()

 The write() function writes a string str to the file. There is no return value.
Syntax:

File_Object.write(str)

ii) writelines()

 The writelines() function writes a sequence of strings to the file. The sequence can be
typically a list of strings. There is no return value.
113
Syntax:

File_Object.writelines(sequence)

Example:

# Program to write data in a file


fp = open("MyFile.txt","w")
L = ["This is Delhi \n","This is Paris \n","This is London \n"]
fp.writelines(L)
fp.close()

Methods of File Handling in Python

 There are different file handling methods in Python which are as follows:
1. rename(): This method is used to rename a file.

import os
os.rename(existing file_name, new file_name)
2. remove(): This method is used to delete a file in Python.

import os
os.remove(“abc.txt”)

3. chdir(): This method is used to change the current directory.

import os
os.chdir(“New directory path”)

4. mkdir(): This method is used to create a new directory.

import os
os.mkdir(“New directory path “)
5. rmdir(): This method is used to remove a directory.

import os
os.rmdir(“New directory path”)
6. getcwd(): This method is used to show the current working directory.

import os
print(os.getcwd())
Other Methods of File Handling in Python

Method Description
flush() To flush the write buffer of the file stream
seek(offset,from=SEEK_SET) It changes the file position to offset bytes, in reference
to (start, current, or end)
tell() It returns the current file location
writable() It returns true if the file stream can be written to

114
8.3 String Processing

 A String in Python is a sequence of characters.


 String Processing refers to the operations performed on strings that allow them to be
accessed, analyzed, and updated.
 For example, str[k] can be used for accessing individual characters, and len(str) for getting
the length of a string.

8.3.1 String Traversal

 Processing a String character by character at a time is known as String Traversal.


 The String Traversal can be usually done by the use of for loop.

Example:

# Python program to read a line of a text file and determine the number of blank
# characters it contains

space = ' '


num_spaces = 0
line = input_file.readline()
for k in range(0,len(line)):
if line[k] == space:
num_spaces = num_spaces + 1

 The characters in a string can be easily traversed, without the use of an explicit index
variable, using the for chr in string form of the for statement.

for chr in line:


if chr == space:
num_spaces = num_spaces + 1

8.3.2 String-Applicable Sequence Operations

 A String is a sequence of characters enclosed in quotation marks.


 Strings are immutable. This means that elements of a string cannot be changed once they
have been assigned.
 For example, one cannot add, delete, or replace characters of a string.
 Therefore, all string operations that “modify” a string return a new string that is a modified
version of the original string.
 Sequence operations relevant to string processing are given in Figure 8-1.
Sequences Operations Applicable to Strings
Length len(str)
Select s[index_val]
Slice s[start:end]
Count s.count(char)
Index s.index(char)
Membership ‘h’ in s
Concatenation s+w
Minimum Value min(s)
Maximum Value max(s)
115
Comparison s == w
Figure 8-1 Sequence Operations on Strings
 In lists, the slice operator s[start:end] returns the substring starting with index start, up to
but not including end index.
 Also, s.index(chr) returns the index of the first occurrence of chr in s.
 The min and max as applied to strings return the smallest (largest) character based on the
underlying Unicode encoding. Thus, for example, all lowercase letters are larger (have a
larger Unicode value) than all uppercase letters.

Examples:

S = 'Hello Goodbye!'
>>>len(S) >>>S.count('o')
14 3

>>> S[6] >>>S.index('b') >>>min(S)


'G' 10 ''

>>>S[6:10] >>>'a' in S >>>max(S)


'Good' False 'y'

8.3.3 String Methods

 Python provides a number of methods specific to strings, in addition to the general sequence
operations.
Checking the Contents of a String
str.isalpha() Returns True if str s=’Hello’ s.isalpha() -> True
contains only characters
s=’Hello!’ s.isalpha() -> False
str.isdigit() Returns True if str s=’123’ s.isdigit() -> True
contains only digits
s=’123A’ s.isdigit() -> False
str.islower() Returns True if str s=’hello’ s.islower() -> True
str.isupper() contains only lower
s=’Hello’ s.isupper() -> False
(upper) case letters
str.lower() Returns lower (upper) s=’Hello!’ s.lower() -> ‘hello!’
str.upper() case version of str
s=’hello!’ s.upper() -> ‘HELLO’
Searching the Contents of a String
str.find(w) Returns the index of the s=’Hello!’ s.find(‘l’) -> 2
first occurrence of w in
s=’Goodbye’ s.find(‘l’) -> -1
str. Returns -1 if not
found.
Replacing the Contents of a String
str.replace(w,t) Returns a copy of str with s=’Hello’ s.replace(‘H’,’J’) -> ‘Jello!’
all occurrences of w
replaced with t. s=’Hello’ s.replace(‘ll,’r’) -> ‘Hero’

Removing the Contents of a String


str.strip(w) Returns a copy of str with s=’ Hello! ’ s.strip(‘ ! ‘) -> ‘Hello’
all leading and trailing
characters that appear in s=’Hello\n’ s.strip(‘\n‘) -> ‘Hello’
w removed
Splitting a String
str.split(w) Returns a list containing s=’Suja, Sam’ s.split(‘,’) -> [‘Suja’, ‘Sam’]
116
all strings in str delimited
by w
Figure 8-2 String Methods in Python
Checking the Contents of a String

 There are times when the individual character in a string (or substring) needs to be checked.
 For example, to check whether a character is an appropriate denotation of a musical note, we
could do the following,

if char not in ('A', 'B', 'C', 'D', 'E', 'F', 'G'):


print('Invalid Data Found')

Searching and Modifying Strings

 The find, replace, and strip methods in Python can be used to search and produce modified
strings.
 The find() method returns the index location of the first occurrence of a specified substring.
 The replace() method produces a new string with every occurrence of a given substring
within the original string replaced with another.

>>>word = 'common' >>>word = 'common'


>>>word.replace('m', 't') >>>word = word.replace('m', 't')
'cotton' 'cotton'
>>>word >>>word
'common' 'cotton'

 The strip() method removes all the leading and trailing spaces from a string. This is
especially useful for stripping off the newline character, \n, from the end of a line in text
processing if needed, \n'

>>>line = 'Hello\n' >>>line = 'Hello\n'


>>>print(line) >>>print(line.strip('\n'))
'Hello' 'Hello'
>>> >>>

8.3.4 String Operators

Operator Description
It is known as concatenation operator used to join the strings given either
+
side of the operator.
It is known as repetition operator. It concatenates the multiple copies of
*
the same string.
It is known as slice operator. It is used to access the sub-strings of a
[]
particular string.
It is known as range slice operator. It is used to access the characters
[:]
from the specified range.
It is known as membership operator. It returns if a particular sub-string is
in
present in the specified string.
It is also a membership operator and does the exact reverse of in. It
not in
returns true if a particular substring is not present in the specified string.
It is used to specify the raw string. Raw strings are used in the cases
where we need to print the actual meaning of escape characters such as
r/R
"C://python". To define any string as a raw string, the character r or R is
followed by the string.
It is used to perform string formatting. It makes use of the format
% specifiers used in C programming like %d or %f to map their values in
python. We will discuss how formatting is done in python.
117
Example:

# Python Program using Python Operators.


str = "Hello"
str1 = " world"
print(str*3) # prints HelloHelloHello
print(str+str1)# prints Hello world
print(str[4]) # prints o
print(str[2:4]); # prints ll
print('w' in str) # prints false as w is not present in str
print('wo' not in str1) # prints false as wo is present in str1.
print(r'C://python37') # prints C://python37 as it is written
print("The string str : %s"%(str)) # prints The string str : Hello

Output:

HelloHelloHello
Hello world
o
ll
False
False
C://python37
The string str : Hello

8.4 Exception Handling

 Exception Handling is a construct in some programming languages to handle or deal


with errors automatically.
 Various error messages can occur while executing Python programs. Such errors are called
exceptions.
 Python handles these errors by reporting them on the screen.
 Exceptions can be “caught” and “handled” by a program, either to correct the error and
continue execution, or terminate the program.

8.4.1 What is an Exception?

 An Exception is an error that happens during the execution of a program.


 Some of the Standard Exceptions Python are listed in Figure 8-3.

Sl. No. Exception Description


1 AssertionError Raised when an assert statement fails.
2 AttributeError Raised when attribute assignment or reference fails.
3 EOFError Raised when the input() function hits end-of-file condition.
4 FloatingPointError Raised when a floating point operation fails.
5 GeneratorExit Raise when a generator's close() method is called.
6 ImportError Raised when the imported module is not found.
7 IndexError Raised when the index of a sequence is out of range.
8 IOError Raised when an input/output operation fails (e.g., “file not
found”
9 KeyError Raised when a key is not found in a dictionary.
10 KeyboardInterrupt Raised when the user hits the interrupt key (Ctrl+C or
Delete).

118
11 MemoryError Raised when an operation runs out of memory.
12 NameError Raised when a variable is not found in local or global scope.
13 NotImplementedError Raised by abstract methods.
14 OSError Raised when system operation causes system related error.
15 OverflowError Raised when the result of an arithmetic operation is too
large to be represented.
16 ReferenceError Raised when a weak reference proxy is used to access a
garbage collected referent.
17 RuntimeError Raised when an error does not fall under any other
category.
18 StopIteration Raised by next() function to indicate that there is no
further item to be returned by iterator.
19 SyntaxError Raised by parser when syntax error is encountered.
20 IndentationError Raised when there is incorrect indentation.
21 TabError Raised when indentation consists of inconsistent tabs and
spaces.
22 SystemError Raised when interpreter detects internal error.
23 SystemExit Raised by sys.exit() function.
24 TypeError Raised when an operation is applied to an object of
incorrect type.
25 UnboundLocalError Raised when a reference is made to a local variable in a
function or method, but no value has been bound to that
variable.
26 UnicodeError Raised when a Unicode-related encoding or decoding error
occurs.
27 UnicodeEncodeError Raised when a Unicode-related error occurs during
encoding.
28 UnicodeDecodeError Raised when a Unicode-related error occurs during
decoding.
29 UnicodeTranslateError Raised when a Unicode-related error occurs during
translating.
30 ValueError Raised when a function gets an argument of correct type
but improper value.
31 ZeroDivisionError Raised when the second operand of division or modulo
operation is zero.
Figure 8-3 Some Standard Exceptions in Python

 The standard exceptions are defined within the exceptions module of the Python Standard
Library, which is automatically imported into Python programs.

8.4.2 The Propagation of Raised Exceptions

 Python’s try statement establishes exception handlers via its except clauses. The handlers
deal with exceptions raised in the body of the try clause, as well as exceptions propagating
from any of the functions called by that code, directly or indirectly.
 If an exception is raised within a try clause that has an applicable except handler,
the try clause terminates and the handler executes. When the handler finishes, execution
continues with the statement after the try statement.
 If an exception is thrown all the way back to the main module (and not handled), the
program terminates displaying the details of the exception.
 Programmer-defined functions may raise exceptions in addition to the exceptions raised by
the built-in functions of Python.
 When an exception is raised, it moves from function to function until someone handles it.
 If it is never handled, it is printed to the screen and the program terminates.
 In Python programming, exceptions are raised when errors occur at runtime. We can also
manually raise exceptions using the raise keyword.

119
8.4.3 Catching and Handling Exceptions

 The try…except block in Python can be used to catch and handle exceptions.
Syntax:

try:
Statements
except:
Statements
else:
Statements

finally:
Statements
 The try block is used to test a block of code for errors.
 The except block is used to catch the exceptions and handle them.
 The code inside the else block must be executed if the try clause does not raise an
exception.
 The finally block is always executed whether an exception has occurred or not. The finally
clause is optional. The finally block is used to close resources and perform clean-up activities

Example 1:

# Python code to illustrate working of try


def divide(x, y):
try:
z=x/y
print("Your answer is :", z)
except ZeroDivisionError:
print("Sorry ! You are dividing by zero ")
# Main Program
x=int(input("Enter the value of x : "))
y=int(input("Enter the value of y : "))
divide(x, y)

Output:

Enter the value of x : 10


Enter the value of y : 2
Your answer is : 5.0
-------------------------------------
Enter the value of x : 5
Enter the value of y : 0
Sorry ! You are dividing by zero

Example 2:

# Python program to demonstrate finally


try:
a=int(input("Enter a: "))
b=int(input("Enter b: "))
c = a/b
print(c)
except ZeroDivisionError:

120
print("Can't divide by zero")
finally:
print("This is finally block")

Output:

Enter a: 10
Enter b: 5
2.0
This is finally block
---------------------------------
Enter a: 10
Enter b: 0
Can't divide by zero
This is finally block

Example 3:

# Python program to demonstrate else block


try:
a = int(input("Enter a: "))
b = int(input("Enter b: "))
c = a/b;
except:
print("Can't divide by zero")
else:
print("I am in else block")
print(c)

Output:

Enter a: 10
Enter b: 0
Can't divide by zero
------------------------------
Enter a: 10
Enter b: 5
I am in else block
2.0

Declaring Multiple Exceptions

 Python allows us to declare multiple exceptions with the except clause.


 Declaring multiple exceptions is useful in cases where a try block throws multiple exceptions.

Syntax:

try:
#block of code

except (<Exception 1>,<Exception 2>,<Exception 3>,...<Exception n>)


#block of code

else:
#block of code

121
Example:

# Python program with multiple exceptions


try:
a = int(input("Enter a: "))
b = int(input("Enter b: "))
c = a/b;
except(ArithmeticError, IOError):
print("Arithmetic Exception")
else:
print(c)
Output:

Enter a: 10
Enter b: 5
2.0
-----------------------------------------
Enter a: 10
Enter b: 0
Arithmetic Exception

Handling Multiple Exceptions in a single try Block

 A try block can have multiple except blocks. However, only one will be executed in case an
exception occurs.

Example:

# Python program for handling multiple exceptions in a single try block


import math
def Square(x):
if int(x) is 0:
raise ValueError('Input argument cannot be zero')
if int(x) < 0:
raise TypeError('Input argument must be positive integer')
return math.pow(int(x), 2)

while True:
try:
n = input('Please enter a number\n')
S = Square(n)
print(S)
except ValueError as ve:
print(type(ve), '::', ve)
except TypeError as te: print(type(te), '::', te)

Output:

Please enter a number


10
100.0
Please enter a number
-5
122
<class 'TypeError'> :: Input argument must be positive integer
Please enter a number
0
<class 'ValueError'> :: Input argument cannot be zero
Please enter a number
^D
Traceback (most recent call last):
File "C:/Users/admin/AppData/Local/Programs/Python/Python38-32/Multiple_Except_Try.py",
line 12, in <module>
n = input('Please enter a number\n')
EOFError: EOF when reading a line
>>>

Raising an Exception

 The raise statement is used to raise an exception.


 We can define what kind of error to raise, and the text to print to the user.
 Programmer-defined functions may raise exceptions in addition to the exceptions raised by
the built-in functions of Python.

Syntax:

raise [Exception [, args [, traceback]]]

Here, Exception is the type of exception (for example, NameError) and argument is a
value for the exception argument.
The argument is optional; if not supplied, the exception argument is None.
The final argument, traceback, is also optional (and rarely used in practice), and if present,
is the traceback object used for the exception.
Example 1:

# Python program to illustrate the raise statement


try:
age = int(input("Enter your age:"))
if (age<18):
raise ValueError
else:
print("You are eligible to Vote")
except ValueError:
print("You are not eligible to Vote")

Output:

Enter your age: 18


You are eligible to Vote
--------------------------
Enter your age: 15
You are not eligible to Vote

Example 2:

# Python program to raise the exception with message


try:
n = int(input("Enter a positive integer: "))
if(n < 0):

123
raise ValueError("This is a negative number")
except ValueError as e:
print(e)

Output:

Enter a positive integer: -5


This is a negative number

Example 3:

# Python program using Arithmetic Error


try:
a = int(input("Enter a: "))
b = int(input("Enter b: "))
c=a/b
if b is 0:
raise ArithmeticError
else:
print(c)
except ArithmeticError:
print("The value of b can't be 0")

Output:

Enter a: 10
Enter b: 0
The value of b can't be 0
------------------------------------------------
Enter a: 10
Enter b: 5
2.0

Nested try-except Blocks

 A try…except block within another try…except block is known as nested try…except block.

Example:

# Python program to implement nested try…except block


x = int(input("Enter a: "))
y = int(input("Enter b: "))
try:
print("Outer try block")
try:
print("Nested try block")
print(x / y)
except TypeError as te:
print("Nested except block")
print(te)
except ZeroDivisionError as ze:
print("Outer except block")
print(ze)

Output:

124
Enter a: 10
Enter b: 0
Outer try block
Nested try block
Outer except block
division by zero
----------------------------
Enter a: 10
Enter b: 5
Outer try block
Nested try block
2.0

8.4.4 Exception Handling and User Input

 Programmer-defined functions may raise exceptions in addition to the exceptions raised by


the built-in functions of Python.
 The input function will return whatever is entered as a string.

Example 1:

# Python program for Input Error Checking


valid = False
while not valid:
try:
month = int(input("Enter the month (1-12): "))
while month < 1 or month > 12:
print("Invalid Input – Must be in the range 1-12")
month = int(input("Enter the month (1-12): "))
valid = True
print("The month you have entered is",month)
except ValueError:
print("Invalid Month")

Output:

Enter the month (1-12): 13


Invalid Input – Must be in the range 1-12
Enter the month (1-12): 11
The month you have entered is 11

Example 2:

# Python program using exception handling


while True:
try:
n = input("Please enter an integer: ")
n = int(n)
break
except ValueError:
print("Not a valid integer! Please try again ...")
print("Great, you successfully entered an integer!")

Output:

Please enter an integer: abc

125
Not a valid integer! Please try again ...
Please enter an integer: 42.0
Not a valid integer! Please try again ...
Please enter an integer: 42
Great, you successfully entered an integer!
8.4.5 Exception Handling and File Processing

 Python supports File Handling and allows users to handle files.


 When the file is opened for reading, an exception is raised if the file cannot be found.
 In this case, the standard IOError exception is raised and the program terminates with a 'No
such file or directory' error message.
 IOError exception is raised as a result of a file open error can be caught and handled.

Example 1:

# Python program for handling exception and file processing


try:
fp = open("testfile", "w")
fp.write("This is my test file for exception handling!!")
except IOError:
print("Error: can\'t open the file")
else:
print("The content has been written into the file successfully")
fp.close()

Output:

The content has been written into the file successfully

Example 2:

# Python Exception Handling program using Files


try:
fp = open("testfile", "w")
fp.write("This is my test file for exception handling!!")
except IOError:
print("Error: can\'t open the file"
finally:
print("Going to close the file")
fp.close()

8.4.6 Python Built-in Exceptions

 Some of the common built-in exceptions in Python programming are listed below:

Exception Description
AssertionError Raised when an assert statement fails.
AttributeError Raised when attribute assignment or reference fails.
EOFError Raised when the input() function hits end-of-file condition.
FloatingPointError Raised when a floating point operation fails.
GeneratorExit Raise when a generator's close() method is called.
ImportError Raised when the imported module is not found.
IndexError Raised when the index of a sequence is out of range.
KeyError Raised when a key is not found in a dictionary.
KeyboardInterrupt Raised when the user hits the interrupt key (Ctrl+C or Delete).
MemoryError Raised when an operation runs out of memory.
126
NameError Raised when a variable is not found in local or global scope.
NotImplementedError Raised by abstract methods.
OSError Raised when system operation causes system related error.
OverflowError Raised when the result of an arithmetic operation is too large
to be represented.
ReferenceError Raised when a weak reference proxy is used to access a
garbage collected referent.
RuntimeError Raised when an error does not fall under any other category.
StopIteration Raised by next() function to indicate that there is no further
item to be returned by iterator.
SyntaxError Raised by parser when syntax error is encountered.
IndentationError Raised when there is incorrect indentation.
TabError Raised when indentation consists of inconsistent tabs and
spaces.
SystemError Raised when interpreter detects internal error.
SystemExit Raised by sys.exit() function.
TypeError Raised when a function or operation is applied to an object of
incorrect type.
UnboundLocalError Raised when a reference is made to a local variable in a
function or method, but no value has been bound to that
variable.
UnicodeError Raised when a Unicode-related encoding or decoding error
occurs.
UnicodeEncodeError Raised when a Unicode-related error occurs during encoding.
UnicodeDecodeError Raised when a Unicode-related error occurs during decoding.
UnicodeTranslateError Raised when a Unicode-related error occurs during translating.
ValueError Raised when a function gets an argument of correct type but
improper value.
ZeroDivisionError Raised when the second operand of division or modulo
operation is zero.

8.4.7 User-Defined Exceptions

 Python also allows us to create our own exceptions by deriving classes from the standard
built-in exceptions.

Example:

# Python program for creating child class from base class Exception
class Error(Exception):
pass # Dummy function
class InvalidNumberError(Error):
def __init__(self,statement,s): # Constructor
self.statement=statement
self.s=s
n=int(input('Enter a Number: '))

try:
if n<1:
raise InvalidNumberError('You have entered a negative number.',n)
else:
print('The square root of the number:',(n)**0.5)
except InvalidNumberError as e: #User Defined Exception Handling
print(e.statement)

Output:

127
Enter a Number: 5
The square root of the number: 2.23606797749979
----------------------------------------------------------
Enter a Number: -5
You have entered a negative number.

Exercises:

1. How many types of Files are there in Python?


2. How do Text Files work in Python?
3. What is File Handling in Python?
4. What is a Text File?
5. What is a Binary File?
6. Distinguish between Text Files and Binary Files.
7. How to open a file? What are the modes for opening a file?
8. How will you close a file?
9. Write the procedures for reading data from a file.
10. How will you write the data to a file?
11. Explain the various operations that can be performed on Text Files.
12. What are the various methods used for handling files in Python?
13. How will you rename a file in Python?
14. How will you delete a file in Python?
15. What is a String?
16. What is meant by String Processing?
17. What do you mean by String Traversal?
18. Mention the various Sequence Operations that are applicable to Strings.
19. Discuss briefly the various String Methods used in Python.
20. Write short notes on String Operators.
21. What is Exception Handling?
22. What is an Exception? Explain with examples.
23. How do you handle exceptions in Python?
24. List some Standard Exceptions used in Python.
25. Explain about try…except statement in Python with syntax and example.
26. What is finally block? What is the syntax for try…finally block?
27. How will you declare multiple exceptions with the except clause?
28. How does Python handle multiple exceptions?
29. How to raise an exception in Python?
30. Write a brief note on nested try…except block in Python.
31. How will you handle Exception Handling while accepting user input?
32. Discuss briefly about how Exception Handling is used in File Processing.
33. What are the types of exceptions in Python?
34. List out the Built-in Exceptions available in Python.
35. What are User-Defined Exceptions? Give an example.
36. Write a Python program to create a text file.
37. Write a Python program to read an entire text file.
38. Write a program segment that opens and reads a text file and displays how many lines of
text are in the file.
39. Write a Python program that takes a text file as input and returns the number of words of a
given text file.
40. Write a Python program to append text to a file and display the text.
41. Write a Python program to count the number of lines in a text file.
42. Write a Python program to copy the contents of a file to another file.
43. Write a Python program to arrange a set of names in alphabetical order.
44. Write a Python program to reverse the given string.
45. Write a Python program to check whether the given string is Palindrome or not.
46. Write a Python program to count the number of Vowels, Consonants, Words and
Whitespaces in a given line of text.
47. Write a Python program to demonstrate Exception Handling.
128
48. Write a Python program to write data in a file.
49. Write a Python program to demonstrate file and file I/O operations.

***********************

129
UNIT - V

Chapter 9

**************************************************************************************
Dictionaries and Sets
**************************************************************************************
Dictionaries are Python’s implementation of a Data Structure that is more generally known as an
Associative Array. A Dictionary consists of a collection of key-value pairs.

Imagine a dictionary in the real world... when we need to look up the meaning of a word, we try
to find the meaning using the word itself and not the possible index of the word. Python
dictionaries work with the same concept, the word whose meaning we are looking for is the Key
and the meaning of the word is the Value.

A Set is an unordered collection data type that is iterable, mutable and has no duplicate
elements. In Python Sets are written with curly brackets.

Both Dictionaries and Sets in Python are discussed in this chapter.

9.1 Dictionary Type in Python

 A Dictionary is a mutable, associative data structure of variable length. The syntax for
declaring dictionaries in Python is given below.

a = {'Apple': 'Fruit', 'Beetroot': 'Vegetable', 'Cake': 'BlackForest,’Dog’:’Animal’}


print(a['Apple'])

Fruit

 Strings are often used as key values.

9.1.1 What is a Dictionary?

 A Python Dictionary is an unordered collection of items.


 Each item of a Dictionary has a Key/Value pair.
 The values of a Dictionary can be any Python Data Type.

9.1.2 Creating a Dictionary

 A Dictionary can be created by placing sequence of elements within curly {} braces,


separated by ‘comma’.
 Dictionary holds a pair of values, one being the Key and the other corresponding pair element
being its Key:Value.
 Values in a dictionary can be of any data type and can be duplicated, whereas keys can’t be
repeated and must be immutable.

Syntax:

dict = { Key1:Value1, Key2:Value2,...KeyN:ValueN }

The following declares a dictionary object.

>>> capitals={"USA":"Washington, D.C.", "France":"Paris", "India":"New Delhi"}

130
 In the above example, capitals is a dictionary object. The left side of : is a key and
right side of : is a value. The key should be an immutable object. A number, string
or tuple can be used as key.

Example:

# Python Program to create a dictionary


# Dict_Create.py
# Creating the dictionary class
class my_dictionary(dict):
def __init__(self): # The “__init__" method is used to initialize the object
self = dict() # The "self" keyword represents the same object or instance of the class
# Function to add Key:Value
def add(self, Key, Value):
self[Key]=Value
# Main Program
dict_obj = my_dictionary()
n=int(input("Enter the no of Key / Value pair in a dictionary: "))
i=1
while i<=n:
dict_obj.Key = input("Enter the Key: ")
dict_obj.Value = int(input("Enter the Value: "))
dict_obj.add(dict_obj.Key, dict_obj.Value)
i=i+1
print("The Dictionary Object is")
print(dict_obj)

Output:

Enter the no of Key / Value pair in a dictionary: 3


Enter the Key: a
Enter the Value: 100
Enter the Key: b
Enter the Value: 200
Enter the Key: c
Enter the Value: 300
The Dictionary Object is
{'a': 100, 'b': 200, 'c': 300}

9.1.3 Accessing Values in a Dictionary

 The value in a dictionary can be retrieved by specifying its corresponding key in square
brackets ([]):

Example:

dict = {'Name': 'Abilash', 'Age': 15, 'Class': 'First'}


print "dict['Name']: ", dict['Name']
print "dict['Age'] : ", dict['Age']

Output:

dict['Name']: Abilash
dict['Age'] : 15

131
 The get() method is used to access the value in a dictionary using the associative
key.

>>>capitals={"USA":"New York", "France":"Paris", "Japan":"Tokyo", "India":"New Delhi"}


>>>capitals.get("France")
'Paris'

 The for loop is used to iterate a dictionary in the Python Script.

capitals={"USA":"Washington, D.C.", "France":"Paris", "Japan":"Tokyo", "India":"New Delhi"}

for key in capitals:


print("Key = " + key + ", Value = " + capitals[key])

Output:

Key = 'USA', Value = 'Washington, D.C.'


Key = 'France', Value = 'Paris'
Key = 'Japan', Value = 'Tokyo'
Key = 'India', Value = 'New Delhi'

9.1.4 Updating a Dictionary

 The key cannot appear more than once. Use the same key and assign a new value
to it to update the dictionary object.

>>> captains={"England":"Root", "Australia":"Smith", "India":"Dhoni"}


>>> captains['India']='Virat'
>>> captains['Australia']='Paine'
>>> captains
{'England': 'Root', 'Australia': 'Paine', 'India': 'Virat'}

 Use a new key and assign a value to it. The dictionary will show an additional key-
value pair in it.

>>> captains['SouthAfrica']='Plessis'
>>> captains
{'England': 'Root', 'Australia': 'Paine', 'India': 'Virat', 'SouthAfrica': 'Plessis'}

9.1.5 Deleting Elements from a Dictionary

 The del keyword is used to remove individual items or the entire dictionary itself.

 The pop() method can be used to remove a particular item from the dictionary. This method
removes an item with the provided key and returns the value.

 The popitem() method can be used to remove and return an arbitrary (key, value) item pair
from the dictionary.

 The clear() method removes all the items or elements from a dictionary at once. When this
operation is performed, the dictionary becomes an empty dictionary.

Example:

# Python program to delete elements from a dictionary


Squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# Remove a particular item, returns its value
132
print(Squares.pop(4))

print(Squares)

# Remove an arbitrary item, return (key,value)


print(Squares.popitem())

print(Squares)

# Remove all items


Squares.clear()

print(Squares)

# Delete the dictionary itself


del Squares

# Throws Error
print(Squares)

Output:

16
{1: 1, 2: 4, 3: 9, 5: 25}
(5, 25)
{1: 1, 2: 4, 3: 9}
{}
Traceback (most recent call last):
File "<string>", line 30, in <module>
print(Squares)
NameError: name 'Squares' is not defined

9.1.6 View Keys and Values

 The keys() and values() methods of Python Dictionary class returns a list of
keys or values explicitly.

>>> d1 = {'name': 'Steve', 'age': 21, 'marks': 60, 'course': 'Computer Engg'}
>>>d1.keys()
dict_keys(['name', 'age', 'marks', 'course'])

 The keys() method returns a list of all the available keys in the dictionary.
 If a new key-value pair is added, the view object is automatically updated. The view
object contains the keys of the dictionary, as a list.

>>> keys=d1.keys()
>>> keys
dict_keys(['name', 'age', 'marks', 'course'])
>>>d1.update({"college":"IITB"})
>>> keys
dict_keys(['name', 'age', 'marks', 'course', 'college'])

This is similar for the values() method.

>>> d1= {'name': 'Steve', 'age': 21, 'marks': 60, 'course': 'Computer Engg'}
>>>values=d1.values()
dict_values(['Steve', 21, 60, 'Computer Engg'])
133
 The values() method returns a list of all the values available in a given dictionary.
 If a new key-value pair is added, the view object is dynamically updated. The view object
contains the values of the dictionary, as a list.

>>> d1.update({"college":"IITB"})
>>> values
dict_values(['Steve', 21, 60, 'Computer Engg', 'IITB'])

9.1.7 Dictionary Methods

 Python has a set of built-in methods that we can use on dictionaries.

Method Description
clear() Removes all the elements from the dictionary
copy() Returns a copy of the dictionary
fromkeys() Returns a dictionary with the specified keys and value
get() Returns the value of the specified key
items() Returns a list containing a tuple for each key value pair
keys() Returns a list containing the dictionary's keys
pop() Removes the element with the specified key
popitem() Removes the last inserted key-value pair
setdefault() Returns the value of the specified key. If the key does not exist: insert
the key, with the specified value
update() Updates the dictionary with the specified key-value pairs
values() Returns a list of all the values in the dictionary

9.1.8 Dictionary Built-in Functions

 Built-in functions like all(), any(), len(), cmp(), sorted(), etc. are commonly used with
dictionaries to perform different tasks.

Function Description
Return True if all keys of the dictionary are True (or if the dictionary is
all()
empty).
Return True if any key of the dictionary is true. If the dictionary is
any()
empty, return False.
len() Return the length (the number of items) in the dictionary.
cmp() Compares items of two dictionaries. (Not available in Python 3)
sorted() Return a new sorted list of keys in the dictionary.

14.2 Set Data Type

 Set is an unordered collection of unique items.


 Set is defined by values separated by comma inside braces { }. Items in a set are not
ordered.

134
12.2.1 The Set Data Type in Python

 A Set is an unordered collection data type that is iterable, mutable and has no
duplicate elements.
 A Frozenset is an immutable set type.

Set Operators
 Sets and frozen sets support the following operators -

key in s # containment check


key not in s # non-containment check
s1 == s2 # s1 is equivalent to s2
s1 != s2 # s1 is not equivalent to s2
s1 <= s2 # s1 is subset of s2
s1 < s2 # s1 is proper subset of s2
s1 >= s2 # s1is superset of s2
s1 > s2 # s1 is proper superset of s2
s1 | s2 # the union of s1 and s2
s1 & s2 # the intersection of s1 and s2
s1 – s2 # the set of elements in s1 but not s2
s1 ˆ s2 # the set of elements in precisely one of s1 or s2

Creating a Set

 A set is created by using the set() function or placing all the elements within a pair of curly
braces.

Example:

# Python program to create a set


Days=set(["Mon","Tue","Wed","Thu","Fri","Sat","Sun"])
Months={"Jan","Feb","Mar"}
Dates={21,22,17}
print(Days)
print(Months)
print(Dates)

Output:

set(['Wed', 'Sun', 'Fri', 'Tue', 'Mon', 'Thu', 'Sat'])


set(['Jan', 'Mar', 'Feb'])
set([17, 21, 22])

Accessing Values in a Set

 Set items cannot be accessed by referring to an index, since Sets are unordered the items
has no index. But we can loop through the Set items using a for loop.

Example:

# Python program to access values in a set


Days=set(["Mon","Tue","Wed","Thu","Fri","Sat","Sun"])
for d in Days:
print(d)

135
Output:

Wed
Sun
Fri
Tue
Mon
Thu
Sat

Adding Elements to a Set

 The add() method is used to add elements to a Set. There is no specific index attached
to the newly added element.

Example:

# Python program to add elements in a Set


# Creating a Set
MySet = set()
print("Initial blank Set: ")
print(MySet)
n=int(input("Enter the number of elements in the set: "))
# Adding elements to the Set using Iterator
for i in range(1, n):
x=input("Enter the element to add: ")
MySet.add(x)
print("\nSet after Addition of n elements: ")
print(MySet)

Output:

Initial blank Set:


set()
Enter the number of elements in the set: 5
Enter the element to add: 1
Enter the element to add: 2
Enter the element to add: 3
Enter the element to add: 4

Set after Addition of n elements:


{'3', '1', '4', '2'}

Removing Elements from a Set

 The discard() and remove() methods are used to remove a particular item from a
Set.
 The only difference between the two is that the discard() function leaves a Set unchanged if
the element is not present in the Set. On the other hand, the remove() function will raise an
error in such a condition (if the element is not present in the Set).

Example 1:

# Python program to remove an element from the set


Days=set(["Mon","Tue","Wed","Thu","Fri","Sat"])
Days.discard("Sun")
print(Days)

136
Output:

set(['Wed', 'Fri', 'Tue', 'Mon', 'Thu', 'Sat'])

Example 2:

# Python program to illustrate the difference between discard() and remove()


My_Set = {1, 3, 4, 5, 6}
print(My_Set)

# Discard an element
My_Set.discard(4)
print(My_Set)

# Remove an element
My_Set.remove(6)
print(My_Set)

# Discard an element not present in My_Set


My_Set.discard(2)
print(My_Set)

# Remove an element not present in My_Set. You will get an error.


# Output: KeyError

My_Set.remove(2)

Output:

{1, 3, 4, 5, 6}
{1, 3, 5, 6}
{1, 3, 5}
{1, 3, 5}
Traceback (most recent call last):
File "<string>", line 28, in <module>
KeyError: 2

 The pop() method is used to remove and return an item from a Set.
 The clear() method is used to remove all the items from a Set.

Example:

# Python program to remove the items from the set


My_Set = set("HelloWorld")
print(My_Set)

# Pop an element
print(My_Set.pop())

# Pop another element


My_Set.pop()
print(My_Set)

# Clear My_Set
My_Set.clear()
print(My_Set)
print(My_Set)

137
Output:

{'H', 'l', 'r', 'W', 'o', 'd', 'e'}


H
{'r', 'W', 'o', 'd', 'e'}
set()

9.2.2 Set Operations

 The Sets in Python are typically used for mathematical operations like Union, Intersection,
Difference and Complement etc.

i) Union of Sets

 The Union operation on two Sets produces a new Set containing all the distinct
elements from both the Sets.
 The Set Union operation can be performed by using an | operator.
 The same thing can be accomplished by using the union() method.

Example 1:

# Python program to implement the Set Union operation


A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}

# Using the | operator


print(A | B)

Output:

{1, 2, 3, 4, 5, 6, 7, 8}

Try the following example on the Python Shell.

# Using the union function


>>> A.union(B)
{1, 2, 3, 4, 5, 6, 7, 8}

ii) Intersection of Sets

 The Intersection operation on two Sets produces a new Set containing only the
common elements from both the Sets.
 The Set Intersection operation can be performed by using the & operator.
 The same thing can be accomplished by using the intersection() method.

Example:

# Python program to implement the Set Intersection Operation


A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# Using the & operator
print(A & B)

Output:

{4, 5}

138
Try the following example on the Python Shell.

# Using intersection function on A


>>> A.intersection(B)
{4, 5}

iii) Difference of Sets

 The Difference operation on two Sets produces a new Set containing only the
elements from the first Set and none from the second Set.
 The Set Difference operation can be performed by using the - operator.
 The same thing can be accomplished by using the difference() method.

Example:

# Python program to implement the Set Difference Operation


A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# Using the - operator
print(A - B)

Output:

{1, 2, 3}

Try the following example on Python Shell.

# Using the difference function on A


>>> A.difference(B)
{1, 2, 3}

iv) Set Symmetric Difference

 The Symmetric Difference on two Sets produces a new Set is a set of elements
in the first Set and the second Set but not in both the Sets (excluding the
intersection).
 The Symmetric Difference can be performed by using ^ operator.
 The same thing can be accomplished by using the symmetric_difference().

Example:

# Python program to implement the Symmetric Difference of two sets


A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}

# Using the ^ Operator


print(A ^ B)

Output:

{1, 2, 3, 6, 7, 8}

Try the following example on Python Shell.

# Using the symmetric_difference function on A

>>> A.symmetric_difference(B)

139
{1, 2, 3, 6, 7, 8}
Other Set Operations

Set Membership Test

 The in keyword is used to test if an item exists in a Set or not.

Example:

# Python program using in keyword in a set


My_Set = set("apple")

# Check if 'a' is present


print('a' in My_Set)

# Check if 'p' is present


print('p' not in My_Set)

Output:

True
False

Iterating Through a Set

 The for loop is used to iterate through each item in a Set.

Example:

# Python program for creating a set using string


My_Place = set("Chennai")

# Iterating using for loop


for val in My_Place:
print(val)

Output:

h
a
e
i
n
C

9.2.3 Set Methods

 Python has a set of built-in methods that we can use on sets.

Method Description
add() Adds an element to the set
clear() Removes all elements from the set
copy() Returns a copy of the set
difference() Returns the difference of two or more sets as a new set
difference_update() Removes all elements of another set from this set
discard() Removes an element from the set if it is a member.

140
(Do nothing if the element is not in set)
intersection() Returns the intersection of two sets as a new set
Updates the set with the intersection of itself and
intersection_update()
another
isdisjoint() Returns True if two sets have a null intersection
issubset() Returns True if another set contains this set
issuperset() Returns True if this set contains another set
Removes and returns an arbitrary set element. Raises
pop()
KeyError if the set is empty
Removes an element from the set. If the element is not
remove()
a member, raises a KeyError
Returns the symmetric difference of two sets as a new
symmetric_difference()
set
Updates a set with the symmetric difference of itself
symmetric_difference_update()
and another
union() Returns the union of sets in a new set
update() Updates the set with the union of itself and others

9.2.4 Built-in Functions with Set

 Built-in functions like all(), any(), enumerate(), len(), max(), min(), sorted(), sum() etc. are
commonly used with sets to perform different tasks.

Function Description
all() Returns True if all elements of the set are true (or if the set is empty).
Returns True if any element of the set is true. If the set is empty, returns
any()
False.
Returns an enumerate object. It contains the index and value for all the
enumerate()
items of the set as a pair.
len() Returns the length (the number of items) in the set.
max() Returns the largest item in the set.
min() Returns the smallest item in the set.
Returns a new sorted list from elements in the set(does not sort the set
sorted()
itself).
sum() Returns the sum of all elements in the set.

9.2.5 Frozenset

 Frozenset is a new class that has the characteristics of a Set, but its elements
cannot be changed once assigned.
 Frozensets are immutable Sets.
 Frozensets can be created using the frozenset() function.
 This data type supports methods like copy(), difference(), intersection(), isdisjoint(),
issubset(), issuperset(), symmetric_difference() and union(). Being immutable, it does not
have methods that add or remove elements.

Example:

# Python program to implement Frozensets


A = frozenset([1, 2, 3, 4])
B = frozenset([3, 4, 5, 6])

Try these examples on Python shell.

>>> A.isdisjoint(B)
False

141
>>> A.difference(B)
frozenset({1, 2})
>>> A | B
frozenset({1, 2, 3, 4, 5, 6})
>>> A.add(3)
...
AttributeError: 'frozenset' object has no attribute 'add'

Exercises:

1. What is a Dictionary in Python?


2. How will you create a Dictionary in Python?
3. What are the different methods used in deleting elements from a Dictionary?
4. What is a Dictionary? Explain with example.
5. What are the different operations performed on the Dictionary?
6. List the various Dictionary methods used in Python.
7. What are the Built-in Dictionary Functions?
8. What is a Set?
9. What is a frozenset?
10. List the various Set Operators available in Python.
11. How will you create a Set in Python?
12. Explain briefly about Set Data Type in Python.
13. Explain the various Operations that can be performed on Sets.
14. List the various Set methods used in Python.
15. What are the Built-in Set Functions?
16. Write a Python program to sort (ascending and descending) a dictionary by value.
17. Write a Python program to add a key to a dictionary.
18. Write a Python program to concatenate following dictionaries to create a new
one. Sample Dictionary:
dic1={1:10, 2:20}
dic2={3:30, 4:40}
dic3={5:50,6:60}

19. Write a Python program to check whether a given key already exists in a dictionary.
20. Write a Python program to iterate over dictionaries using for loops.
21. Write a Python program to generate and print a dictionary that contains a number (between
1 and n) in the form (x, x*x).

Sample Dictionary (n = 5):

Expected Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

22. Write a Python program to merge two dictionaries.


23. Write a Python program to iterate over dictionaries using for loops.
24. Write a Python program to sum all the items in a dictionary.
25. Write a Python program to multiply all the items in a dictionary.
26. Write a Python program to remove a key from a dictionary.
27. Write a Python program to sort a dictionary by key.
28. Write a Python program to get the maximum and minimum value in a dictionary.
29. Write a Python program to remove duplicates from Dictionary.
30. Write a Python program to check a dictionary is empty or not.
31. Write a Python program to combine two dictionary adding values for common keys.

d1 = {'a': 100, 'b': 200, 'c':300}

142
d2 = {'a': 300, 'b': 200, 'd':400}

Sample output: Counter({'a': 400, 'b': 400, 'd': 400, 'c': 300})

32. Write a Python program to print a dictionary in table format.


33. Write a Python program to sort a list alphabetically in a dictionary.
34. Write a Python program to get the key, value and item in a dictionary.
35. Write a Python program to print a dictionary line by line.
36. Write a Python program to create a Set.
37. Write a Python program to iterate over Sets.
38. Write a Python program to add member(s) in a Set.
39. Write a Python program to remove item(s) from a Set.
40. Write a Python program to remove an item from a set if it is present in the Set.
41. Write a Python program to create an intersection of Sets.
42. Write a Python program to create a union of Sets.
43. Write a Python program to create Set difference.
44. Write a Python program to create a symmetric difference.
45. Write a Python program to check if a set is a subset of another Set.
46. Write a Python program to create a shallow copy of Sets.
47. Write a Python program to clear a Set.
48. Write a Python program to implement frozensets.
49. Write a Python program to find maximum and the minimum value in a Set.
50. Write a Python program to find the length of a Set.
51. Write a Python program to check if a given value is present in a Set or not.
52. Write a Python program to check if two given Sets have no elements in common.
53. Write a Python program to check if a given Set is superset of itself and superset of another
given Set.

************************

143
Chapter 10

*********************************************************************
Object-Oriented Programming
*********************************************************************
Python is an Object-Oriented Programming language. It allows us to develop applications using
an Object-Oriented approach.

This means that almost all the code is implemented using a special construct called classes.
Programmers use classes to keep related things together. This is done using the keyword “class,”
which is a grouping of object-oriented constructs.

Almost everything in Python is an Object, with its properties and methods.

A Class is a "blueprint" for creating objects.

There are predefined classes in Python, as well as the ability of programmers to define their own.
In this chapter, we see how to define and use classes in Python.

10.1 What is Object-Oriented Programming?

 Object-Oriented Programming (OOP) is a method of structuring a program by bundling


related properties and behaviors into individual Objects.
 An Object-Oriented paradigm is to design the program using Classes and Objects.
 The Object is related to real-world entities such as book, house, pencil, etc.
 The OOPs concept focuses on writing the reusable code. It is a widespread technique to solve
the problem by creating Objects.

Some important terms in OOP are as follows:

 Class − A class is a blueprint for the object. The attributes are data members (class
variables and instance variables) and methods, accessed via dot notation.
 Class Variable − A variable that is defined in the class and can be used by all the
instances of that class.
 Data Member − A class variable or instance variable that holds data associated with a
class and its objects.
 Instance Variable − A variable that is defined inside a method and belongs only to the
current instance of a class.
 Instance − An object is an instance of the class.
 Instantiation − The process of creating a new object from a class is known as
instantiation.
 Method – Methods are functions defined inside the body of a class. They are used to
define the behaviors of an object.
 Object − An Object is an instance of a Class. An object comprises both data members
(class variables and instance variables) and methods.
 Operator Overloading − The assignment of more than one function to a particular
operator.

10.1.1 What is a Class?

 A class specifies the set of instance variables and methods that are “bundled
together” for defining a type of object.
 A class is a blueprint from which objects are created.

144
 The class can be defined as a collection of objects. It is a logical entity that has some specific
attributes and methods.

10.1.2 Three Fundamental Features of Object-Oriented Programming

 Python provides three fundamental features that support Object-Oriented Programming. They
are Encapsulation, Inheritance, and Polymorphism.
 Message Passing occurs when a method of one object calls a method of another
(Figure 10-1). For example, if Object B were a list and B1 a sorting method, then a call to B1
is a message (or request) for it to become sorted. A message to one object can result in the
propagation of messages among many other objects in order to accomplish a request.

Figure 10-1 Message Passing in Object-Oriented Programming

10.2 Encapsulation

10.2.1 What is Encapsulation?

 Encapsulation is a means of bundling together instance variables and methods to


form a given type (class).
 Encapsulation is one of the fundamental concepts in Object-Oriented Programming (OOP).
 Encapsulation is used to restrict access to methods and variables
 A class is an example of encapsulation as it encapsulates all the data that is member
functions, variables, etc.

10.2.2 Defining Classes in Python

 The class keyword is used to define a class in Python.


 All lines following the class declaration line are indented.
 Instance variables are initialized in the __init__ special method.
 Class members beginning with two underscore characters are intended to be
private members of a class.
 This is effectively accomplished in Python by the use of name mangling.

Syntax:

class ClassName:
<statement-1>
.
.
.
<statement-N>

 Class definitions, like function definitions (def statements) must be executed before they have
any effect.
 In practice, the statements inside a class definition will usually be function definitions, but
other statements are allowed, and sometimes useful.

145
Example:

# Python program to create a class


class Person:
"This is a person class"
Name=’Akash’
Age = 20

def greet(self):
print('Hello')

print(Person.Name)
print(Person.Age)
print(Person.greet)
print(Person.__doc__)

Output:

Akash
20
<function Person.greet at 0x7fc78c6e8160>
This is a person class

 All private class members are automatically renamed to begin with a single underscore
character followed by the class name. Such renaming of identifiers is called name mangling.
 Unless the variable or method is accessed with its complete (mangled) name, it will not be
found.
 Name Mangling prevents unintentional access of private members of a class, while
still allowing access when needed.
 The methods of a class, are essentially functions meant to operate on the instance variables
of the class.
 In Python, functions serving as a method must have an extra first parameter, by convention
named self. This parameter contains a reference to the object instance to which the method
belongs.
 When a method accesses any other member of the same class, the member name must be
preceded by 'self'.
 Getter and Setter methods are also defined.

10.2.3 Creating an Object in Python

 An Object is an instance of a Class. A class is like a blueprint while an instance is a copy


of the class with actual values.
 An object is simply a collection of data (variables) and methods (functions) that act on
those data.
 The class object could be used to access different attributes.
 It can also be used to create new object instances (instantiation) of that class. The procedure
to create an object is similar to a function call.

>>> P = Person()

 This will create a new object instance named P. We can access the attributes of objects using
the object name prefix.
 Attributes may be data or method. Methods of an object are corresponding functions of that
class.

146
Example:

# Python program using a class and an object


class Person:
"This is a person class"
Name="Akash"
Age = 20

def greet(self):
print("Hello")

# Create a new object of Person class


P = Person()
print(P.Name)
print(P.Age)
P.greet()

Output:

Akash
20
Hello

10.2.4 Special Methods in Python

 Method names that begin and end with two underscore characters are called special
methods in Python.
 Special methods are automatically called.

1) The __init__ method

 The "__init__" is a reserved method in Python classes.


 It is known as a Constructor in Object-Oriented Programming.
 This method is called when an object is created from the class and it allows the class
to initialize the attributes of a class.

2) The self Parameter

 The self parameter is a reference to the current instance of the class, and is used to
access the variables that belong to the class.
 It has to be the first parameter of any function in the class.

Example:

# Python program to implement init method

class Person:
def __init__(self, Name, Age):
self.Name = Name
self.Age = Age

def MyFunc(self):
print("Hello My Name is " + self.Name)

P = Person("Sam", 50)
P.MyFunc()
147
Output:

Hello My Name is Sam

Note: The __init__() function is called automatically every time the class is being used to
create a new object.
10.2.5 Python Constructors

 A Constructor is a special type of method (function) which is used to initialize the


members of the class.
 In Python, the __init__() method is called the constructor and is always called when an
object is created.
 It accepts the self keyword as the first argument which allows accessing the attributes or
method of the class.
 Every class must have a Constructor, even if it simply relies on the Default Constructor.

Syntax:

def __init__(self):
# Body of the Constructor

Types of Constructors

 Constructors can be of two types.

1) Default Constructor
2) Parameterized Constructor

1) Default Constructor

 A Constructor that has no Parameters is known as Default Constructor.


 The Default Constructor uses only self as an argument.
 It does not perform any task but initializes the objects.

Example:

# Python program to implement Default Constructor


class Student:
# Default Constructor
def __init__(self):
print("This is Default Constructor")
def Show(self, name):
print("Hello", name)
Stud = Student()
Stud.Show("Sam")

Output:

This is Default Constructor


Hello Sam

2) Parameterized Constructor

 A Constructor that has Parameters is known as Parameterized Constructor.


 The parameterized constructor has multiple parameters along with the self.

148
Example:

# Python program to implement Parameterized Constructor


class Student:
# Parameterized Constructor
def __init__(self, Name):
print("This is Parameterized Constructor")
self.Name = Name
def Show(self):
print("Hello", self.Name)
Stud = Student("Sam")
Stud.Show()

Output:

This is Parameterized Constructor


Hello Sam

Note: The Constructor Overloading is not allowed in Python.

10.2.6 Built-in class Functions

 The built-in functions defined in the class are described in the following table.

SN Function Description
1 getattr(obj,name,default) It is used to access the attribute of the object.
2 setattr(obj, name,value) It is used to set a particular value to the specific
attribute of an object.
3 delattr(obj, name) It is used to delete a specific attribute.
4 hasattr(obj, name) It returns true if the object contains some specific
attribute.

Example:

#Python Program to implement the built-in class functions


class Student:
def __init__(self, Name, Id, Age):
self.Name = Name
self.Id = Id
self.Age = Age
# Creates the object of the class Student
S = Student("Akash", 1001, 20)

# Prints the attribute name of the object S


print(getattr(S, 'Name'))

# Reset the value of attribute Age to 25


setattr(S, "Age", 25)

# Prints the modified value of age


print(getattr(S, 'Age'))

# Prints true if the student contains the attribute with name Id

print(hasattr(S, 'Id'))

149
# Deletes the attribute age
delattr(S, 'Age')

# This will give an error since the attribute age has been deleted.
print(S.Age)

Output:

Akash
25
True
Traceback (most recent call last):
File "C:/Users/admin/AppData/Local/Programs/Python/Python38-32/Class_Fns.py", line 28,
in <module>
print(S.Age)
AttributeError: 'Student' object has no attribute 'Age'

10.2.7 Built-in class Attributes

 A Python class contains some built-in class attributes which provide information about the
class.
 The built-in class attributes are given in the table below.

SN Attribute Description
1 __dict__ It provides the dictionary containing the information about the class
namespace.
2 __doc__ It contains a string which has the class documentation
3 __name__ It is used to access the class name.
4 __module__ It is used to access the module in which, this class is defined.
5 __bases__ It contains a tuple including all base classes.

Example 1:

# Python program to implement the Built-in class attributes


class Student:
def __init__(self, Name, Id, Age):
self.Name = Name;
self.Id = Id;
self.Age = Age
def Display_Details(self):
print("Name:%s, Id:%d, Age:%d"%(self.Name, self.Id, self.Age))
S = Student("Akash", 1001, 20)
print(S.__doc__)
print(S.__dict__)
print(S.__module__)

Output:

None
{'Name': 'Akash', 'Id': 1001, 'Age': 20}
__main__

Example 2:

# Python program to implement Encapsulation


class Person:
def __init__(self, Name, Age=0):
150
self.Name = Name
self.Age = Age

def Display(self):
print(self.Name)
print(self.Age)

P = Person('Sam', 50)
# Accessing using class method
P.Display()
# Accessing directly from outside
print(P.Name)
print(P.Age)

Output:

Sam
50
Sam
50

10.2.8 Abstraction

 Abstraction means hiding the complexity and showing only the essential features of
the object.
 A TV set where we enjoy programs without knowing the inner details of how TV works.
 Selected members of a class can be made inaccessible (“hidden”) from its clients, referred to
as information hiding. Information Hiding is a form of abstraction.
 Abstraction is one of the fundamental OOP concepts.
 Abstraction in Python is achieved by using abstract classes and interfaces.

Abstract Class

 A class which contains one or more abstract methods is called an abstract class.
 An abstract method is a method that is declared, but contains no implementation.
 Abstract classes may not be instantiated, and its abstract methods must be implemented
by its subclasses.
 Abstract classes includes attributes in addition to methods, we can require the attributes in
concrete classes by defining them with @abstractproperty.

Example:

# Python program to implement abstract class

from abc import ABC, abstractmethod

class Polygon(ABC):

# Abstract method
def No_Of_Sides(self):
pass

class Triangle(Polygon):

# Overriding abstract method


def No_Of_Sides(self):
print("Number of Sides = 3")

151
class Pentagon(Polygon):

# Overriding abstract method


def No_Of_Sides(self):
print("Number of Sides = 5")

class Hexagon(Polygon):

# Overriding abstract method


def No_Of_Sides(self):
print("Number of Sides = 6")

class Rectangle(Polygon):

# Overriding abstract method


def No_Of_Sides(self):
print("Number of Sides = 4")

# Main Program
T = Triangle()
T.No_Of_Sides()

R = Rectangle()
R.No_Of_Sides()

P = Pentagon()
P.No_Of_Sides()

H = Hexagon()
H.No_Of_Sides()

Output:

Number of Sides = 3
Number of Sides = 4
Number of Sides = 5
Number of Sides = 6

10.3 Inheritance

 Inheritance is a powerful feature in Object-Oriented Programming.


 Inheritance in Python allows one class to inherit all the properties of another class.
 Inheriting all the properties refers to the ability of a child class to access all the variables and
methods defined inside a parent class.

10.3.1 What is Inheritance?

 The ability to create a new class from an existing class is called Inheritance.
 The new class is called the subclass (also called “derived class” or “child class”), and the old
class is called the superclass (also called “base class” or “parent class”).
 Following are the benefits of inheritance.

1. Inheritance provides code re-usability.


2. Inheritance reduces the code repetition.
3. It represents a real world relationship between parent class and child class.

152
Syntax:

class DerivedClassName(BaseClassName):
<Statement-1>
.
.
.
<Statement-N>

Types of Inheritance

 Python supports 5 types of inheritance namely,

i) Single Inheritance
ii) Multiple Inheritance
iii) Multilevel Inheritance
iv) Hierarchical Inheritance
v) Hybrid Inheritance

i) Single Inheritance

 A child class derived from only one parent class is called Single Inheritance (Figure
10-2).

Figure 10-2 Single Inheritance

Example:

# Python program to implement Single Inheritance


class Father:
def __init__(self, FirstName, LastName):
self.FirstName = FirstName
self.LastName = LastName
def PrintName(self):
print(self.FirstName, self.LastName)

class Son(Father):
def __init__(self, FirstName, LastName):
Father.__init__(self, FirstName, LastName)

X = Son("Radha", "Krishnan")
X.PrintName()

Output:

Radha Krishnan

153
ii) Multiple Inheritance

 A class that can be derived from more than one base class is called Multiple
Inheritance (Figure 10-3).
 In Multiple Inheritance, the features of all the base classes are inherited into the derived class.

Figure 10-3 Multiple Inheritance

Example:

# Python program to implement Multiple Inheritance


class Base1(object):
def __init__(self):
self.Str1 = "Hello"
print("Base1")

class Base2(object):
def __init__(self):
self.Str2 = "World"
print("Base2")
class Derived(Base1, Base2):
def __init__(self):
# Calling Constructors of Base1 and Base2 classes
Base1.__init__(self)
Base2.__init__(self)
print("Derived")

def PrintString(self):
print(self.Str1, self.Str2)

Ob = Derived()
Ob.PrintString()

Output:

Base1
Base2
Derived
Hello World

iii) Multilevel Inheritance

 Multilevel Inheritance is achieved when a derived class inherits another derived


class (Figure 10-4).
 There is no limit on the number of levels up to which, the multilevel inheritance is achieved in
Python.

154
Figure 10-4 Multilevel Inheritance

Example:

# Python program to implement Multilevel Inheritance


class Family:
def Show_Family(self):
print("This is our Family:")

# Father class inherited from Family


class Father(Family):
FatherName = ""

def Show_Father(self):
print(self.FatherName)

# Mother class inherited from Family


class Mother(Family):
MotherName = ""

def Show_Mother(self):
print(self.MotherName)

# Son class inherited from Father and Mother classes


class Son(Father, Mother):
def Show_Parent(self):
print("Father :", self.FatherName)
print("Mother :", self.MotherName)

S = Son() # Object of Son class


S.FatherName = "Ashok"
S.MotherName = "Sita”

S.Show_Family()
S.Show_Parent()

Output:

This is our Family:


Father : Ashok
Mother : Sita

iv) Hierarchical Inheritance

 Hierarchical inheritance involves multiple inheritance from the same base or parent class.
 When more than one derived classes are created from a single base this type of
inheritance is called Hierarchical Inheritance (Figure 10-5).

155
Figure 10–5 Hierarchical Inheritance

Example:

# Python program to implement Hierarchical Inheritance


# Base Class
class Parent:
def Func1(self):
print("This function is in Parent Class.")

# Derived Class1
class Child1(Parent):
def Func2(self):
print("This function is in Child1.")

# Derived Class2
class Child2(Parent):
def Func3(self):
print("This function is in Child2.")

# Main Program
Object1 = Child1()
Object2 = Child2()
Object1.Func1()
Object1.Func2()
Object2.Func1()
Object2.Func3()

Output:

This function is in Parent Class.


This function is in Child1.
This function is in Parent Class.
This function is in Child2.

v) Hybrid Inheritance

 Hybrid Inheritance is a combination of Multiple and Multilevel Inheritance.


 More than one child class inherits a parent class (Figure 10-6).

Figure 10-6 Hybrid Inheritance

156
Example:

# Python program to implement Hybrid Inheritance


class School:
def Func1(self):
print("This function is in School.")

class Student1(School):
def Func2(self):
print("This function is in Student1. ")

class Student2(School):
def Func3(self):
print("This function is in Student2.")

class Student3(Student1, School):


def Func4(self):
print("This function is in Student 4.")

# Main Program
Stud_Obj = Student3()
Stud_Obj.Func1()
Stud_Obj.Func2()

Output:

This function is in School.


This function is in Student1.
super() Function
 The super() function is used to give access to methods and properties of a
parent or sibling class.
 The super() function returns an object that represents the parent class.

Syntax:

super()

Example:

# Python program to implement super()function


class Parent:
def __init__(self, Str):
self.Message = Str

def Display(self):
print(self.Message)

class Child(Parent):
def __init__(self, Str):
super().__init__(Str)

X = Child("Honesty is the Best Policy.")


X.Display()

157
Output:

Honesty is the Best Policy.


>>>

10.3.3 Subtypes

 A Subtype is something that can be substituted for and behave as its parent type.
 There are important differences between subtypes and subclasses in supporting reuse.
 Subclasses allow one to reuse the code inside classes - both instance variable declarations
and method definitions. Thus they are useful in supporting code reuse inside a class.
 Subtyping on the other hand is useful in supporting reuse externally, giving rise to a form of
polymorphism. That is, once a data type is determined to be a subtype of another, any
function or procedure that could be applied to elements of the supertype can also be applied
to elements of the subtype.

10.3.4 Defining Subclasses in Python

 The string class can be used as a subclass of the built-in string class, and look at whether an
exploded string can be substituted as a string type.

Class Names of the Built-in Types in Python

 The Built-in function type can be used to determine the type (class name) of any value in
Python.
 The Built-in function help can be used to invoke the built-in Python help system.
The help() method takes a maximum of one parameter.

Example:

>>>type(12) >>>type(12.4) >>>type('')


<class 'int'> <class 'float' > <class 'str'>

>>>type([]) >>>type(()) >>>type({})


<class 'list'> <class 'tuple'> <class 'dict'>

 The resulting expression, <class classname> gives the associated class name for any value.
 A detailed description of a built-in class can be displayed by use of the help function,

>>>help(int) >>>help(str)

>>> help(print)
Help on built-in function print in module builtins:

print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

Prints the values to a stream, or to sys.stdout by default.


Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.

158
10.4 Polymorphism

 Polymorphism means the ability to take more than one form.


 Polymorphism is a powerful feature of Object-Oriented Programming languages.

10.4.1 What is Polymorphism?

 Polymorphism is taken from the Greek words Poly (many) and morphism (forms).
 The word polymorphism means having many forms.
 Polymorphism in Python allows us to define methods in the child class with the same name as
defined in their parent class.
 For example, consider the Shape class and its subclasses given in Figure 10-7.

Figure 10-7 Polymorphic Shape Class

 All Shape objects have an x, y coordinate (with corresponding getter and setter methods). In
addition, Shape objects can also calculate their areas. How a shape’s area is computed,
however, Subclasses of the Shape class must implement the calcArea method, otherwise a
Not-ImplementedError exception is raised.

10.4.2 The Use of Polymorphism

 Polymorphism is a very important concept in Object-Oriented Programming.


 It refers to the use of a single type entity (Method, Operator or Object) to represent different
types in different scenarios.

Polymorphism with Function and Objects

 It is also possible to create a function that can take any object, allowing for polymorphism.

Example:

# Python program using Polymorphism with Function and Objects


class Tomato():
def Type(self):
print("Vegetable")
def Color(self):
print("Red")
class Apple():
def Type(self):
print("Fruit")
def Color(self):
print("Red")

def Func(Obj):
Obj.Type()
Obj.Color()
159
Obj_Tomato = Tomato()
Obj_Apple = Apple()
Func(Obj_Tomato)
Func(Obj_Apple)

Output:

Vegetable
Red
Fruit
Red

Polymorphism with Class Methods

 Python allows different classes to have methods with the same name.

Example:

# Python program to implement Polymorphism With Class Methods

class India():
def Capital(self):
print("New Delhi is the capital of India.")

def Language(self):
print("Hindi is the most widely spoken language of India.")

def Type(self):
print("India is a developing country.")

class USA():
def Capital(self):
print("Washington, D.C. is the capital of USA.")

def Language(self):
print("English is the primary language of USA.")

def Type(self):
print("USA is a developed country.")

Obj_Ind = India()
Obj_Usa = USA()
for Country in (Obj_Ind, Obj_Usa):
Country.Capital()
Country.Language()
Country.Type()

Output:

New Delhi is the capital of India.


Hindi is the most widely spoken language of India.
India is a developing country.
Washington, D.C. is the capital of USA.
English is the primary language of USA.
USA is a developed country.

160
Polymorphism with Inheritance

 In Python, Polymorphism lets us define methods in the child class that have the same name
as the methods in the parent class. In inheritance, the child class inherits the methods from
the parent class.

Example:

#Python program to implement Polymorphism with Inheritance

class Bird:
def Intro(self):
print("There are many types of birds.")

def Flight(self):
print("Most of the birds can fly but some cannot.")

class Sparrow(Bird):
def Flight(self):
print("Sparrows can fly.")

class Ostrich(Bird):
def Flight(self):
print("Ostriches cannot fly.")

Obj_Bird = Bird()
Obj_Spr = Sparrow()
Obj_Ost = Ostrich()

Obj_Bird.Intro()
Obj_Bird.Flight()

Obj_Spr.Intro()
Obj_Spr.Flight()

Obj_Ost.Intro()
Obj_Ost.Flight()

Output:

There are many types of birds.


Most of the birds can fly but some cannot.
There are many types of birds.
Sparrows can fly.
There are many types of birds.
Ostriches cannot fly.

10.4.3 Method Overriding

 Method Overriding means having two methods with the same method name and
parameters.
 In Python, method overriding occurs by simply defining in the child class a method with
the same name of a method in the parent class.

Example:

# Python program to implement Method Overriding


# Defining Parent class
161
class Parent():
def __init__(self):
self.Value = "Inside Parent Class"
def Show(self):
print(self.Value)

# Defining Child class


class Child(Parent):
def __init__(self):
self.Value = "Inside Child Class"

def Show(self):
print(self.Value)

# Main Program
Obj1 = Parent()
Obj2 = Child()
Obj1.Show()
Obj2.Show()

Output:

Inside Parent Class


Inside Child Class

Exercises:

1. What is meant by OOP in Python?


2. What is a class?
3. What are the three fundamental features of Object-Oriented Programming?
4. What is Encapsulation?
5. What is Abstraction?
6. How will you define a class in Python?
7. How will you create an object in Python?
8. What are the special methods used in Python classes?
9. What are Constructors in Python?
10. What is Inheritance?
11. What are the different types of Inheritance?
12. Explain the concept of Polymorphism in Object-Oriented Programming.
13. Explain the advantages of using Polymorphism in program design.
14. How will you define subclasses in Python?
15. Explain the use of name mangling in Python.
16. What is Polymorphism?
17. Mention the use of Polymorphism.
18. What is an Abstract class?
19. What is Method Overriding? Give example.
20. Write a Python class to reverse a string word by word.
21. Write a Python class named Rectangle constructed by a length and width and a method
which will compute the area of a rectangle.
22. Write a Python class named Circle constructed by a radius and two methods which will
compute the area and the perimeter of a circle.

**********************

162
UNIT – 5
PYTHON PACKAGES

A python package is a collection of modules. Modules that are related to each other are mainly
put in the same package. When a module from an external package is required in a program, that
package can be imported and its modules can be put to use. A package is a directory of Python
modules that contains an additional __init__.py file, which distinguishes a package from a
directory that is supposed to contain multiple Python scripts. Packages can be nested to multiple
depths if each corresponding directory contains its own __init__.py file.

Code

For example, let’s take the datetime module, which has a submodule called date.
When datetime is imported, it’ll result in an error, as shown below:

import datetime
date.today()
The correct way to use the date module is shown below:
from datetime import date
print date.today()

1. Matplotlib
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a
multi-platform data visualization library built on NumPy arrays and designed to work with the
broader SciPy stack. It was introduced by John Hunter in the year 2002. One of the greatest
benefits of visualization is that it allows us visual access to huge amounts of data in easily
digestible visuals. Matplotlib consists of several plots like line, bar, scatter, histogram etc.

Installation: Windows, Linux and macOS distributions have matplotlib and most of its
dependencies as wheel packages. Run the following command to install matplotlib package.
command to install Matplotlib is
python -mpip install -U matplotlib
Importing matplotlib
After successfully installing matplotlib , You can run this command to import matplotlib on
your system.
Import matplotlib

Basic plots in Matplotlib


Matplotlib comes with a wide variety of plots. Plots help to understand trends, and patterns,
and to make correlations.

a) Line plot using Matplotlib


By importing the matplotlib module, defines x and y values for a plots, plots the data using
the plot() function and it helps to display the plot by using the show() function . The plot()
creates a line plot by connecting the points defined by x and y values.
Example:

# importing matplotlib module

from matplotlib import pyplot as plt

# x-axis values

x = [5, 2, 9, 4, 7]

# Y-axis values

y = [10, 5, 8, 4, 2]

# Function to plot

plt.plot(x,y)

# function to show the plot

plt.show()

Output :
b) Bar plot using Matplotlib
By using matplotlib library in python , it allows us to access the functions and classes
provided by the library for plotting. There are tow list x and y are defined . This function
creates a bar plot by taking x-axis and y-axis values as arguments and generates the bar
plot based on those values.

Example:
# importing matplotlib module
from matplotlib import pyplot as plt
# x-axis values
x = [5, 2, 9, 4, 7]
# Y-axis values
y = [10, 5, 8, 4, 2]
# Function to plot the bar
plt.bar(x,y)
# function to show the plot
plt.show()

Output:

c) Histogram using Matplotlib


By using the matplotlib module defines the y-axis values for a histogram plot. Plots in
histogram using the hist() function and displays the plot using the show() function. The hist()
function creates a histogram plot based on the values in the y-axis list.
Example:
# importing matplotlib module
from matplotlib import pyplot as plt
# Y-axis values
y = [10, 5, 8, 4, 2]
# Function to plot histogram
plt.hist(y)
# Function to show the plot
plt.show()
Output:

====================================================================
2. PANDAS
Pandas is an open-source library in Python that is made mainly for working with relational
or labeled data both easily and intuitively. It provides various data structures and operations
for manipulating numerical data and time series. This library is built on top of
the NumPy library of Python. Pandas is fast and it has high performance & productivity for
users.
Why Use Pandas?
 Fast and efficient for manipulating and analyzing data.
 Data from different file objects can be easily loaded.
 Flexible reshaping and pivoting of data sets
 Provides time-series functionality.
Usage of Pandas
 Data set cleaning, merging, and joining.
 Easy handling of missing data (represented as NaN) in floating point as well as non-
floating point data.
 Columns can be inserted and deleted from DataFrame and higher dimensional objects.
 Powerful group by functionality for performing split-apply-combine operations on data
sets.
 Data Visulaization

Installing Pandas
The first step of working in pandas is to ensure whether it is installed in the system or not. If
not then we need to install it in our system using the pip command. Type the cmd
command in the search box and locate the folder using the cd command where python-pip
file has been installed. After locating it, type the command:
pip install pandas

Importing Pandas
After the pandas have been installed into the system, you need to import the library. This
module is generally imported as follows:
import pandas as pd
Pandas Data Structures
Pandas generally provide two data structures for manipulating data, They are:
 Series
 DataFrame

Series
Pandas Series is a one-dimensional labeled array capable of holding data of any type
(integer, string, float, python objects, etc.). The axis labels are collectively called indexes.
Pandas Series is nothing but a column in an Excel sheet. Labels need not be unique but
must be a hashable type. The object supports both integer and label-based indexing and
provides a host of methods for performing operations involving the index.

Series Data Frame


Creating a Series
In the real world, a Pandas Series will be created by loading the datasets from existing
storage, storage can be SQL Database, CSV file, or an Excel file. Pandas Series can be
created from lists, dictionaries, and from scalar values, etc.
Example:

import pandas as pd

import numpy as np

# Creating empty series

ser = pd.Series()

print("Pandas Series: ", ser)

# simple array

data = np.array(['g', 'e', 'e', 'k', 's'])

ser = pd.Series(data)

print("Pandas Series:\n", ser)


Output:
Pandas Series: Series([], dtype: float64)
Pandas Series:
0 g
1 e
2 e
3 k
4 s
dtype: object

DataFrame
Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular
data structure with labeled axes (rows and columns). A Data frame is a two-dimensional
data structure, i.e., data is aligned in a tabular fashion in rows and columns. Pandas
DataFrame consists of three principal components, the data, rows, and columns.

Creating Data Frame


In the real world, a Pandas DataFrame will be created by loading the datasets from existing
storage, storage can be SQL Database, CSV file, or an Excel file. Pandas DataFrame can
be created from lists, dictionaries, and from a list of dictionaries, etc.
Example:

import pandas as pd

# Calling DataFrame constructor

df = pd.DataFrame()

print(df)

# list of strings

lst = ['Geeks', 'For', 'Geeks', 'is', 'portal', 'for', 'Geeks']


# Calling DataFrame constructor on list

df = pd.DataFrame(lst)

print(df)
Output:
Empty DataFrame
Columns: []
Index: []
0
0 Geeks
1 For
2 Geeks
3 is
4 portal
5 for
6 Geeks
====================================================================

3. Python Numpy
Numpy is a general-purpose array-processing package. It provides a high-performance
multidimensional array object, and tools for working with these arrays. It is the fundamental
package for scientific computing with Python.
Besides its obvious scientific uses, Numpy can also be used as an efficient multi-dimensional
container of generic data.
Arrays in Numpy

Array in Numpy is a table of elements (usually numbers), all of the same type, indexed by a tuple of
positive integers. In Numpy, number of dimensions of the array is called rank of the array.A tuple of
integers giving the size of the array along each dimension is known as shape of the array. An array
class in Numpy is called as ndarray. Elements in Numpy arrays are accessed by using square
brackets and can be initialized by using nested Python Lists.

Creating a Numpy Array


Arrays in Numpy can be created by multiple ways, with various number of Ranks, defining the size
of the Array. Arrays can also be created with the use of various data types such as lists, tuples, etc.
The type of the resultant array is deduced from the type of the elements in the sequences.
Note: Type of array can be explicitly defined while creating the array.
# Python program for Creation of Arrays
import numpy as np
# Creating a rank 1 Array
arr = np.array([1, 2, 3])
print("Array with Rank 1: \n",arr)

# Creating a rank 2 Array


arr = np.array([[1, 2, 3],[4, 5, 6]])
print("Array with Rank 2: \n", arr)

# Creating an array from tuple


arr = np.array((1, 3, 2))
print("\nArray created using "
"passed tuple:\n", arr)

Output:
Array with Rank 1:
[1 2 3]
Array with Rank 2:
[[1 2 3]
[4 5 6]]

Array created using passed tuple:


[1 3 2]

Basic Array Operations


In numpy, arrays allow a wide range of operations which can be performed on a particular array or
a combination of Arrays. These operations include some basic Mathematical operation as well as
Unary and Binary operations.
# Python program to demonstrate
# basic operations on single array
import numpy as np

# Defining Array 1
a = np.array([[1, 2],[3, 4]])

# Defining Array 2
b = np.array([[4, 3],[2, 1]])

# Adding 1 to every element


print ("Adding 1 to every element:", a + 1)

# Subtracting 2 from each element


print ("\nSubtracting 2 from each element:", b - 2)
# sum of array elements
# Performing Unary operations
print ("\nSum of all array "
"elements: ", a.sum())

# Adding two arrays


# Performing Binary operations
print ("\nArray sum:\n", a + b)

Output:
Adding 1 to every element:
[[2 3]
[4 5]]

Subtracting 2 from each element:


[[ 2 1]
[ 0 -1]]

Sum of all array elements: 10

Array sum:
[[5 5]
[5 5]]

You might also like