120c1a Python Notes
120c1a Python Notes
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
Learning Resources:
Recommended Texts
Reference Books
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
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.
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
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.
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
2) Digital Computer
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
11
2) Minicomputer
3) Mainframe Computer
4) Supercomputer
1. Input Unit
2. Central Processing Unit
3. Output Unit
The Central Processing Unit (CPU) is known as the Brain of the Computer.
The Central processing unit (CPU) again consists of 3 parts:
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.
13
1.1.1 The Essence of Computational Problem Solving
May 2020
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.
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.
Properties of Algorithms
Flowchart
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::
16
2) Draw a Flowchart to find the biggest among two numbers.
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.
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.
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.
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
Example:
Read upwards the sequence of remainders and this will give the Binary equivalent of the
Decimal number.
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.
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.
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.
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.
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.
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.
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.
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.
Compiler
Interpreter
Assembler
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,
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.
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.
Problem Analysis involves identifying the problem and establishing the causes and effects
related to that problem.
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
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,
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.
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.
There are many features in Python. Some of the essential features of Python are listed below.
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.
6. Object-Oriented
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
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.
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.
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.
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.
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.
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:
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,
28
print Function
The Python print function is used to display information on the screen. This may be used to
display a message.
Syntax:
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:
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:
29
1.6.6 How to use Python IDLE?
>> 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:
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.
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:
************************
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
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.
The built-in format function can be used to produce a numeric string version of the value
containing a specific number of decimal places,
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,
Example:
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"
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')
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,
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,
Finally blanks, by default, are the fill character for formatted strings. However, a specific fill
character can be specified as shown below,
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
Example:
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.
Example:
num = 10
num + 1 ➝ 10 + 1 ➝ 11
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
Example:
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.
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.
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:
Examples of valid and invalid identifiers in Python are given in Figure 2-2.
>>> and = 10
SyntaxError: invalid syntax
2.3 Operators
Operators are special symbols in Python that carry out arithmetic or logical computation.
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.
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.
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.
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
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
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.
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
Example:
S1 = ‘Welcome to Python’
S2 = "Welcome to Python”
S3 = '''A Multiline
3. List
Example:
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
Example:
D = {1:'Value','Key':2}
42
6. Sets
Example:
S = {5,2,3,1,4}
7. Boolean
Example:
A = True
B = False
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
43
Exercises:
*************************
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.
The Membership Operators can also be used to check if a given string occurs within another
string,
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.
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
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
Special Operators
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.
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
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.
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:
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.
48
not (x or y) is equivalent to (not x) and (not y)
3.3.1 If 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.
Example 1:
if grade==100:
49
print(“Perfect Score”)
Example 2:
Output:
if…else Statement
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.
Example 1:
if grade>=75:
print(“Distinction”)
else:
print(“Falling Grade”)
Example 2:
Output:
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.
Syntax:
if condition:
Statements
else:
if condition:
Statements
else:
if condition:
Statements
Example 1:
Output:
Example 2:
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.
if Valid_Input:
print("There are ",No_of_days," days in the month")
Output:
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
Example 1:
Output:
Example 2:
if Valid_Input:
print("There are", Num_Days,"days in the month")
Output:
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.”
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.
Example 1:
Write a Python program that sums the first n integers, for a given (positive) value n
entered by the user.
Output:
Example 2:
Output:
56
Enter the Number: 5
Factorial Value : 120
Syntax:
while condition:
Statement(s)
else:
Statement(s)
Example:
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
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.
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
Example:
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.
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:
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.
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:
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:
**********************
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.
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.
Example:
Output:
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.
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.
61
Figure 4-2 List Traversal
lst = [1, 2, 3]
Thus, for example, the following prints the first element of list lst
print(lst[0])
4.2.2 Tuples
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
>>>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
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.
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:
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
The value of a specific item in a Nested List can be changed by referring to its index number.
The append() method is used to add new values at the end of the Nested List.
The insert() method is used to insert an item at a specific position in 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 remove() method searches for the first instance of the given element and removes it.
The built-in len() function is used to find how many items a Nested sublist has.
The for loop is used to iterate over the items of a Nested List.
Python’s for statement provides a convenient means of iterating over lists (and other
sequences).
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:
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:
Output:
Enter n: 5
1
2
3
4
5
Example 2:
Output:
The sum is 15
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
Example 1:
67
for i in range(1, n):
print(i)
Output:
Example 2:
Output:
I like Apple
I like Orange
I like Mango
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:
Example 1:
Output:
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:
Output:
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.
Example:
Output:
1
22
333
4444
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
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:
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:
Output:
Current Letter: P
Current Letter: y
Current Letter: t
Current Letter: o
Current Letter: n
Pass Statement
Syntax:
pass
Example:
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!
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
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)).
Example:
if Found_Item == False:
print("\nItem not Found")
Output:
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.
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.
Syntax:
def function_name(parameters):
"""Docstring"""
Statement(s)
return [expression]
Example 1:
75
# Main Program
n=int(input("Enter the number: "))
OddEven(n)
Output:
Example 2:
Output:
Calling a Function
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
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:
# 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
Example:
# Main Program
DisplayMessage()
Output:
Sindhi College
Chennai
Output:
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:
Output:
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:
Output:
Example:
Display_Text()
Output:
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
Mutable Arguments
Example:
# Main Program
MyList = [10,20,30,40]
Add_Item(MyList)
print("Outside Function:", MyList)
Output:
Immutable Arguments
Example:
# Main Program
Test(string)
print("Outside Function:", string)
Output:
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.
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.
Example:
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.
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:
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:
# 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.
Example:
# Global Scope
S = "India is My Country"
Func()
Output:
India is My Country
# Calling Function
MyFunc()
print("Python is " + x)
Output:
Python is Wonderful
Exercises:
*********************
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.
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)).
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 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.
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).
>>>list1[0] = 5
>>>list2[0]
5
>>>list2 = list(list1)
list() is referred to as a list constructor. The result of the copying is depicted in Figure 6-5.
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]]
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]] # Does not affect the original list
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:
# 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]
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:
Output:
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')
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
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:
Output:
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.
Example:
Output:
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.
Pen Attributes
Example:
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)
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
Example:
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).
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:
Output:
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:
Output:
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
96
6.2.5 Creating Multiple Turtles
turtle1 = turtle.Turtle()
turtle2 = turtle.Turtle()
turtles = []
turtles.append(turtle.Turtle())
turtles.append(turtle.Turtle())
Turtle Methods
Method Description
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.
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
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.
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__)
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.
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.
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.
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.
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.
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.
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.
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.
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.
104
from modulename import something
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:
Output:
3.141592653589793
Example 2:
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:
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.
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.
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:
Output:
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.
A stack can be viewed as a list that can be accessed only at one end, as depicted in Figure
7-10.
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:
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
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:
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.
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.
Fundamental operations of all types of files include opening a file, closing a file, reading from
a file and writing to a file.
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,
Access Modes govern the type of operations possible in the opened file. There are 6 access
modes in python.
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.
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.
Syntax:
File_Object.close()
Example:
MyFile.close()
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()
Example:
Output:
This is Delhi
This is Paris
This is London
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:
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”)
import os
os.chdir(“New directory path”)
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
Example:
# Python program to read a line of a text file and determine the number of blank
# characters it contains
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.
Examples:
S = 'Hello Goodbye!'
>>>len(S) >>>S.count('o')
14 3
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’
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,
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.
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'
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:
Output:
HelloHelloHello
Hello world
o
ll
False
False
C://python37
The string str : Hello
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.
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:
Output:
Example 2:
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:
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
Syntax:
try:
#block of code
else:
#block of code
121
Example:
Enter a: 10
Enter b: 5
2.0
-----------------------------------------
Enter a: 10
Enter b: 0
Arithmetic Exception
A try block can have multiple except blocks. However, only one will be executed in case an
exception occurs.
Example:
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:
Raising an Exception
Syntax:
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:
Output:
Example 2:
123
raise ValueError("This is a negative number")
except ValueError as e:
print(e)
Output:
Example 3:
Output:
Enter a: 10
Enter b: 0
The value of b can't be 0
------------------------------------------------
Enter a: 10
Enter b: 5
2.0
A try…except block within another try…except block is known as nested try…except block.
Example:
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
Example 1:
Output:
Example 2:
Output:
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
Example 1:
Output:
Example 2:
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.
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:
***********************
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.
A Dictionary is a mutable, associative data structure of variable length. The syntax for
declaring dictionaries in Python is given below.
Fruit
Syntax:
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:
Output:
The value in a dictionary can be retrieved by specifying its corresponding key in square
brackets ([]):
Example:
Output:
dict['Name']: Abilash
dict['Age'] : 15
131
The get() method is used to access the value in a dictionary using the associative
key.
Output:
The key cannot appear more than once. Use the same key and assign a new value
to it to update the dictionary object.
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'}
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:
print(Squares)
print(Squares)
print(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
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'])
>>> 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'])
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
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.
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 -
Creating a Set
A set is created by using the set() function or placing all the elements within a pair of curly
braces.
Example:
Output:
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:
135
Output:
Wed
Sun
Fri
Tue
Mon
Thu
Sat
The add() method is used to add elements to a Set. There is no specific index attached
to the newly added element.
Example:
Output:
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:
136
Output:
Example 2:
# Discard an element
My_Set.discard(4)
print(My_Set)
# Remove an element
My_Set.remove(6)
print(My_Set)
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:
# Pop an element
print(My_Set.pop())
# Clear My_Set
My_Set.clear()
print(My_Set)
print(My_Set)
137
Output:
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:
Output:
{1, 2, 3, 4, 5, 6, 7, 8}
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:
Output:
{4, 5}
138
Try the following example on the Python Shell.
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:
Output:
{1, 2, 3}
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:
Output:
{1, 2, 3, 6, 7, 8}
>>> A.symmetric_difference(B)
139
{1, 2, 3, 6, 7, 8}
Other Set Operations
Example:
Output:
True
False
Example:
Output:
h
a
e
i
n
C
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
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:
>>> 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:
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).
142
d2 = {'a': 300, 'b': 200, 'd':400}
Sample output: Counter({'a': 400, 'b': 400, 'd': 400, 'c': 300})
************************
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.
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.
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.
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.
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.
10.2 Encapsulation
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:
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.
>>> 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:
def greet(self):
print("Hello")
Output:
Akash
20
Hello
Method names that begin and end with two underscore characters are called special
methods in Python.
Special methods are automatically called.
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:
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:
Note: The __init__() function is called automatically every time the class is being used to
create a new object.
10.2.5 Python Constructors
Syntax:
def __init__(self):
# Body of the Constructor
Types of Constructors
1) Default Constructor
2) Parameterized Constructor
1) Default Constructor
Example:
Output:
2) Parameterized Constructor
148
Example:
Output:
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:
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'
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:
Output:
None
{'Name': 'Akash', 'Id': 1001, 'Age': 20}
__main__
Example 2:
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:
class Polygon(ABC):
# Abstract method
def No_Of_Sides(self):
pass
class Triangle(Polygon):
151
class Pentagon(Polygon):
class Hexagon(Polygon):
class Rectangle(Polygon):
# 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
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.
152
Syntax:
class DerivedClassName(BaseClassName):
<Statement-1>
.
.
.
<Statement-N>
Types of Inheritance
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).
Example:
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.
Example:
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
154
Figure 10-4 Multilevel Inheritance
Example:
def Show_Father(self):
print(self.FatherName)
def Show_Mother(self):
print(self.MotherName)
S.Show_Family()
S.Show_Parent()
Output:
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:
# 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:
v) Hybrid Inheritance
156
Example:
class Student1(School):
def Func2(self):
print("This function is in Student1. ")
class Student2(School):
def Func3(self):
print("This function is in Student2.")
# Main Program
Stud_Obj = Student3()
Stud_Obj.Func1()
Stud_Obj.Func2()
Output:
Syntax:
super()
Example:
def Display(self):
print(self.Message)
class Child(Parent):
def __init__(self, Str):
super().__init__(Str)
157
Output:
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.
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.
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:
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)
158
10.4 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.
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.
It is also possible to create a function that can take any object, allowing for polymorphism.
Example:
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
Python allows different classes to have methods with the same name.
Example:
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:
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:
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:
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:
def Show(self):
print(self.Value)
# Main Program
Obj1 = Parent()
Obj2 = Child()
Obj1.Show()
Obj2.Show()
Output:
Exercises:
**********************
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
# 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)
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:
====================================================================
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.
import pandas as pd
import numpy as np
ser = pd.Series()
# simple array
ser = pd.Series(data)
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.
import pandas as pd
df = pd.DataFrame()
print(df)
# list of strings
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.
Output:
Array with Rank 1:
[1 2 3]
Array with Rank 2:
[[1 2 3]
[4 5 6]]
# Defining Array 1
a = np.array([[1, 2],[3, 4]])
# Defining Array 2
b = np.array([[4, 3],[2, 1]])
Output:
Adding 1 to every element:
[[2 3]
[4 5]]
Array sum:
[[5 5]
[5 5]]