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

PythonProgramming book

The document is about a book titled 'Python Programming' published by GCS Publishers India in January 2023, authored by several professors from various educational institutions. It aims to provide a comprehensive understanding of Python programming, covering fundamental concepts and applications in engineering fields. The book includes detailed chapters on topics such as data expressions, control flow, GUI programming, and database programming, making it a valuable resource for practitioners and engineers.

Uploaded by

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

PythonProgramming book

The document is about a book titled 'Python Programming' published by GCS Publishers India in January 2023, authored by several professors from various educational institutions. It aims to provide a comprehensive understanding of Python programming, covering fundamental concepts and applications in engineering fields. The book includes detailed chapters on topics such as data expressions, control flow, GUI programming, and database programming, making it a valuable resource for practitioners and engineers.

Uploaded by

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

See discussions, stats, and author profiles for this publication at: https://www.researchgate.

net/publication/370637742

PYTHON PROGRAMMING GCS PUBLISHERS INDIA

Book · January 2023

CITATIONS READS

0 465

5 authors, including:

Jeyabharathi Jeganmohan Amit Vajpayee


Kalasalingam Academy of Research and Education Parul University
12 PUBLICATIONS 22 CITATIONS 39 PUBLICATIONS 354 CITATIONS

SEE PROFILE SEE PROFILE

M. Tholkapiyan
Chennai Institute Of Technology
33 PUBLICATIONS 563 CITATIONS

SEE PROFILE

All content following this page was uploaded by Amit Vajpayee on 10 May 2023.

The user has requested enhancement of the downloaded file.


PYTHON PROGRAMMING

GCS PUBLISHERS
INDIA
PYTHON PROGRAMMING
Authors

Dr.M.M.Yamuna Devi.,Associate Professor,


Department of Computer Science and Engineering,
Koneru Lakshmaiah Education Foundation,
Vijayawada,Andhra Pradesh -522302,India

Dr.J.Jeyabharathi., ASSOCIATE PROFESSOR,


Department of Computer Science and Engineering,
Kalasalingam Academy of Research and Education,
Anand Nagar, Krishnan koil 626126,Virudhunagar District,
Tamilnadu,India

Dr. Amit Vajpayee.,Associate Professor


Apex Institute of Technology,
Chandigarh University, Mohali, Punjab 140413

Dr. M. Tholkapiyan.,Professor
Department of Civil Engineering
Saveetha School of Engineering,
Saveetha Institute of Medical and Technical Sciences (SIMATS),
Chennai, Tamil Nadu, 602105, India.

Dr. Siva Shankar S.,Associate Professor


Department of Computer Science and Engineering (AI & ML)
KG REDDY COLLEGE OF ENGINEERING &TECHNOLOGY
Moinabad, Hyderabad, Telangana-501504

GCS PUBLISHERS
INDIA
Book Title : Python Programming
Authors : Dr.M.M.Yamuna Devi
Dr.J.Jeyabharathi
Dr. Amit Vajpayee
Dr. M. Tholkapiyan
Dr. Siva Shankar S
Book Subject : Python Programming
Book Category : Authors Volume
Copy Right : @ Authors
First Edition : August , 2022
Book Size : B5
Price : Rs.999/-

Published by
GCS PUBLISHERS INDIA
ISO 9001-2015 CERTIFIED
e-mail : [email protected]

ISBN Supported by International ISBN Agency,


United House, North Road, London, N7 9DP, UK. Tel. + 44 207 503 6418 &
Raja Ram Mohan Roy National Agency for ISBN
Government of India, Ministry of Human Resource Development,
Department of Higher Education, New Delhi – 110066 (India)
ISBN: 978-81-959790-3-5 e-ISBN: 978-81-959790-2-8
PREFACE
This book aims to provide a broad PYTHON PROGRAMMING for the
importance of PYTHON PROGRAMMING is well known in various
engineering fields. The book uses to explain the fundamentals of this
subject.

It provides a logical method of explaining various complicated concepts


and stepwise methods to explain important topics. Each chapter is well
supported with necessary illustrations. All the chapters in the book are
arranged in a proper sequence that permits each topic to build upon earlier
studies.

PYTHON PROGRAMMING an important research area. The techniques


developed in this area so far require to be summarized appropriately. In this
book, the fundamental theories of these techniques are introduced.
Particularly, the functions required in image processing techniques are
introduced.

The brief content of this book is as follows-


CHAPTER 1 INTRODUCTION TO PYTHON
CHAPTER 2 DATA EXPRESSIONS STATEMENTS
CHAPTER 3 CONTROL FLOW, FUNCTIONS CHAPTER 4 STRINGS
CHAPTER 5 LISTS, TUPLES, DICTIONARIES
CHAPTER 6 PYTHON DICTIONARY
CHAPTER 7 FILE, MODULES
CHAPTER 8 FUNCTIONS
CHAPTER 9 FILE SYSTEM
CHAPTER 10 REGULAR EXPRESSIONS, SYMBOLS AND
CHARACTERS
CHAPTER 11 GUI PROGRAMMING
CHAPTER 12 DATABASE PROGRAMMING
REFERENCES
This book is original in style and method and no pains have been
spared to make it as compact, perfect, and reliable as possible. Every
attempt has been made to make the book a unique one.

In particular, this book can be found very useful for practitioners and
engineers who are interested in this area. Hopefully, the chapters presented
in this book have just done that.
ACKNOWLEDGMENTS
Take it from me, writing a book takes time, patience, and motivation in
equal measures. At times the challenges can be overwhelming, and it
becomes very easy to lose focus. However, analytics, patterns, and
uncovering the hidden meaning behind data have always attracted me.
When one considers the possibilities offered by comprehensive analytics
and the inclusion of what may seem to be unrelated databases, the effort
involved seems almost inconsequential.

we also have to acknowledge the many vendors in the Internet of Things


arena who inadvertently helped me along my journey to expose the value
contained in data.

Writing takes a great deal of energy and can quickly consume all of the
hours in a day. With that in mind, I have to thank the numerous editors
whom we have worked with on freelance projects while concurrently
writing this book. Without their understanding and flexibility, we could
never have written this book or any other.

When it comes to providing the ultimate in encouragement and support,


no one can compare with my family time and be still willing to provide me
with whatever we needed to complete this book. We are very thankful to
have such a wonderful and supportive family.
CONTENTS
CHAPTER TITLE PG.NO
CHAPTER 1 INTRODUCTION TO PYTHON 1-30
1.1 INTRODUCTION
1.2 PYTHON
1.3 PYTHON APPLICATIONS
1.5 PYTHON CHARACTERISTICS
1.6 PYTHON LANGUAGE FEATURES
1.7 PYTHON MODULES
1.8 PYTHON OOPS CONCEPTS
1.9 PYTHON CONSTRUCTOR
1.10 PYTHON INHERITANCE
1.11 METHOD OVERRIDING
1.12 DATA ABSTRACTION IN PYTHON
1.13 ABSTRACTION IN PYTHON
CHAPTER 2 DATA EXPRESSIONS STATEMENTS 31-55
2.1 INTRODUCTION
2.2 PYTHON INTERPRETER
2.3 MODES OF PYTHON INTERPRETER
2.4 VALUES AND DATA TYPES
2.5 VARIABLES
2.6 KEYWORDS
2.7 STATEMENTS AND EXPRESSIONS
2.8 INPUT AND OUTPUT
2.9 COMMENTS
2.10 DOCSTRING
2.11 LINES AND INDENTATION
2.12 QUOTATION IN PYTHON
2.13 TUPLE ASSIGNMENT
2.14 OPERATORS
2.16 ARGUMENTS TYPES:

2.17 ILLUSTRATIVE PROGRAMS

CHAPTER 3 CONTROL FLOW, FUNCTIONS 56-76


3.1 BOOLEAN VALUES
3.2 CONDITIONALS
3.3 ITERATION/CONTROL STATEMENTS
3.4 FRUITFUL FUNCTION
CHAPTER 4 STRINGS 77-92
4.1 PYTHON STRING
4.2 STRINGS INDEXING AND SPLITTING
4.3 REASSIGNING STRINGS
4.4 PYTHON STRING FORMATTING
4.5 PYTHON STRING FUNCTIONS
CHAPTER 5 LISTS, TUPLES, DICTIONARIES 93-107
5.1 PYTHON LIST
5.2 PYTHON TUPLE
CHAPTER 6 PYTHON DICTIONARY 108-116
6.1 INTRODUCTION
6.2 ACCESSING THE DICTIONARY VALUES
6.3 BUILT-IN DICTIONARY FUNCTIONS
CHAPTER 7 FILE, MODULES 117-134
7.1 PYTHON PACKAGES
7.2 PYTHON FILE
7.3 PYTHON MODULE
CHAPTER 8 FUNCTIONS 135-171
8.1 PYTHON FUNCTION
8.2 CREATING A FUNCTION
8.3 FUNCTION CALLING
8.4 ARGUMENTS IN FUNCTION
8.5 SCOPE OF VARIABLES
8.6 PYTHON BUILT-IN FUNCTIONS
8.8 PYTHON LAMBDA FUNCTIONS
CHAPTER 9 FILE SYSTEM 172-193
9.1 FILE SYSTEM
9.2 PERSISTENT STORAGE MODULES, RELATED MODULES
9.3 EXCEPTIONS
9.4 EXCEPTIONS AS STRINGS
9.5 ASSERTIONS
9.6 CREATING EXCEPTIONS
9.7 THE SYS MODULE
9.8 MODULES
CHAPTER 10 REGULAR EXPRESSIONS, SYMBOLS AND
CHARACTERS 194-200
10.1 EXPRESSIONS
10.2 MULTITHREADED PROGRAMMING
10.3 GLOBAL INTERPRETER LOCK, THREAD MODULE, THREADING
MODULE, RELATED MODULES
CHAPTER 11 GUI PROGRAMMING 201-206
11.1 INTRODUCTION, TKINTER AND PYTHON PROGRAMMING
11.2 WEB PROGRAMMING
11.3 WEB (HTTP) SERVERS
CHAPTER 12 DATABASE PROGRAMMING 207-219
12.1 INTRODUCTION TO PYTHON DB.
12.2 PYTHON DATABASE APPLICATION PROGRAMMER’S
INTERFACE
12.3 OBJECT RELATIONAL MAPPERS (ORM’S)
REFERENCES
Python Programming

CHAPTER 1
INTRODUCTION TO PYTHON
1.1 INTRODUCTION
Python is a general-purpose interpreted, interactive, object-oriented, high-
level programming language. Guido van Rossum created it during 1985-
1990. Python source code, like Perl, is available under the GNU General
Public License (GPL).
1.1.1 Python History and Versions
Python laid its foundation in the late 1980s.
The implementation of Python was started in December 1989 by Guido
Van Rossum at CWI in the Netherlands.
In February 1991, Guido Van Rossum published the code (labeled version
0.1.0) to alt. sources.
In 1994, Python 1.0 was released with new features like lambda, map,
filter, and reduce.
Python 2.0 added new features such as list comprehensions and garbage
collection systems.
On December 3, 2008, Python 1.0 (also called "Py3K") was released. It was
designed to rectify the fundamental flaw of the language.
ABC programming language is said to be the predecessor of Python
language, which was capable of Exception Handling and interfacing with
the Amoeba Operating System.
The following programming languages influence Python:
ABC language.
1.2 PYTHON
There is a fact behind choosing the name Python. Guido van Rossum was
reading the script of a popular BBC comedy series, "Monty Python's
Flying Circus." It was the late on-air 1970s.
Van Rossum wanted to select a name which unique, sort, and a little bit
mysterious. So he decided to select naming Python after "Monty Python's
Flying Circus" for their newly created programming language.
The comedy series was creative and well random. It talks about everything.
Thus it is slow and unpredictable, which makes it very interesting.
Python is also versatile and widely used in every technical field, such
as Machine Learning, Artificial Intelligence, Web Development,
Mobile Application, Desktop Application, Scientific Calculation, etc.
Python Version List
Python programming language is being updated regularly with new
features and supports. Python versions have had many updates from 1994
to the current release.
1
Python Programming

A list of Python versions with their released date is given below.

Python Version Released Date

Python 1.0 January 1994

Python 1.5 December 31, 1997

Python 1.6 September 5, 2000

Python 2.0 October 16, 2000

Python 2.1 April 17, 2001

Python 2.2 December 21, 2001

Python 2.3 July 29, 2003

Python 2.4 November 30, 2004

Python 2.5 September 19, 2006

Python 2.6 October 1, 2008

Python 2.7 July 3, 2010

Python 3.0 December 3, 2008

Python 3.1 June 27, 2009

Python 3.2 February 20, 2011

Python 3.3 September 29, 2012

Python 3.4 March 16, 2014

Python 3.5 September 13, 2015

Python 3.6 December 23, 2016

Python 3.7 June 27, 2018

2
Python Programming

Python 3.8 October 14, 2019

Tips to Remember While Learning Python


The proper learning method will assist us in learning Python quickly and
becoming competent Python developers.
This part will discuss a few key points when learning Python.
1. Explain why we want to learn.
Before learning Python, you should have a specific target in mind. Python
is a simple but powerful programming language. There are a lot of
libraries, modules, built-in functions, and data structures in it. If the aim
is vague, learning Python would be a tedious and monotonous experience.
You cannot get anything done if you don't have a definite target in mind.
So, first, find out why you want to learn, which could be anything from
learning anything new to developing projects in Python to switching to
Python. The following are some of the most popular environments where
Python is used. Could you choose any of them?
o Data Processing and Analysis
Artificial Intelligence (AI) is a term that refers to a computer program
o Playing games
o Robots/Hardware/Sensors
o Applications for Desktop
Choose one or two areas that concern you and begin your Python journey.
2. Learn the Fundamental Syntax
It is the most significant and fundamental step in learning Python's
syntax. We must first master syntax fundamentals before moving on to
more advanced topics. As we discussed, Python is simple to learn and has
a simple syntax. It does not have a semicolon or bracket. Its syntax is
similar to that of the English language.
As a result, learning its syntax can take very little time. Once we
understand the grammar, we can learn more quickly and work on projects.
1. Make Your Code
The most efficient and reliable way to learn Python is to write code.
Attempt to write code on paper and run it in your head first (Dry Run),
then move on to the method. Writing code on paper will assist us in
quickly becoming familiar with the syntax and storing the definition in our
long-term memory. When writing the code, make an effort to use
appropriate functions and variable names.

3
Python Programming

For Python programming, various editors are available that automatically


highlight syntax issues. As a result, we don't need to pay much attention
to these errors.
4. Continue to practice
Practice is the next important step. It must use Python concepts to
incorporate them into code. Our regular coding practice should be
consistent.
Consistency is essential for success in any endeavor, not just
programming. Writing code regularly can aid in the development of muscle
memory.
We may do a problem-solving exercise involving similar principles or solve
at least two or three Python problems. Although it can seem difficult,
muscle memory plays an important role in programming. It will put us
ahead of those who think Python's reading definition is all needed.
5. Make the necessary notes.
Making notes is a great way to learn Python's concepts and syntax. It will
help you build the consistency and concentration necessary to become a
Python developer. Make short notes with pertinent details and specific
examples of the topic at hand.
Keeping track of your notes will also help you learn more quickly.
According to a review published in Psychological Science,
6. Talk about your ideas with others.
While coding appears to be a solitary task, we can improve our abilities by
communicating with others. We should talk to an expert or friends who are
learning Python about our doubts. This practice will aid in acquiring
additional knowledge, tips and tricks, and the resolution of coding issues.
Python has a fantastic group, which is one of its best features. As a result,
we will benefit from enthusiastic Python users.
7. Carry out small projects
After grasping the fundamental concepts of Python, a novice should
attempt to work on small projects. It will assist you in better
understanding Python and being a more integral part of it. Theoretical
expertise isn't enough to master the Python programming language. It
doesn't matter what these projects are as long as they teach you
something. Start with simple projects like a calculator app, tic-tac-toe
game, alarm clock app, to-do list, student or customer management
system, etc.
If you've mastered a small project, you can quickly move on to your more
interesting domain (Machine Learning, Web Development, etc.).
8. Others to Teach

4
Python Programming

"If you want to learn something, teach it to someone else," goes the adage.
In the case of learning Python, this is also valid. Create blog posts, film
videos, or enroll in classes at a local training center to share your
knowledge with other students. It will assist us in improving our
understanding of Python and uncovering previously unseen gaps in our
knowledge. If you don't want to do all this, enter the online community and
answer questions about Python.
1. Investigate Frameworks and Libraries
Python has a large number of modules and frameworks. After becoming
acquainted with the fundamental concepts of Python, the next move is to
investigate Python libraries. Working with domain-specific projects
necessitates the use of libraries. The following segment provides a brief
overview of the major libraries.
o TensorFlow - TensorFlow is an artificial intelligence library that allows us
to build large-scale AI projects.
o Django - This is an open-source platform for creating web applications.
It's easy to use, adaptable and managed.
o Flask is a web application that is also open source. It's used to make web
applications that aren't too heavy.
o Pandas - Pandas is a Python library for performing scientific
computations.
o Keras - Keras is an open-source library for working with neural
networks.
Python has a plethora of libraries. We've listed a couple of them already.
Ten. Contribute to the open-source community
As we all know, Python is an open-source language that ensures everyone
can use it. We can also contribute to the Python online community to
expand our knowledge. Contributing to open-source projects is the most
effective way to broaden one's horizons. We also get reviews, notes, and
suggestions on the work we've submitted. The feedback will encourage us
to learn the best Python programming practices and assist us in being
good Python developers.
1.3 PYTHON APPLICATIONS
Python is a high-level programming language that is open source and
comes with a range of libraries and frameworks. Python has grown in
popularity due to its ease of use, simple syntax, and user-friendly setting.
The following is an example of Python use.
 Desktop Applications
 Web Applications
 Data Science
5
Python Programming

 Artificial Intelligence
 Machine Learning
 Scientific Computing
 Robotics
 Internet of Things (IoT)
 Gaming
 Mobile Apps
 Data Analysis and Preprocessing.
1.4 IMPORTANCE OF PYTHON
Python is a scripting language that is high-level, interpreted, interactive,
and object-oriented. Python is intended to be a very readable language. It
often uses English keywords instead of punctuation and has fewer
syntactical constructions than other languages.
Python is a must-have skill for students and working professionals who
want to become great software engineers, particularly if they work in the
Web Development field. I'll go through some of the core benefits of learning
Python:
• Python is Interpreted. The interpreter processes Python at runtime.
Before running your software, you do not need to compile it. This is
analogous to the programming languages PERL and PHP.

6
Python Programming

• Python is Interactive. You can sit at a Python prompt and write your
programs by interacting directly with the interpreter.
• Python is Object-Oriented Python supports the Object-Oriented
programming style or methodology, which encapsulates code within
objects.
• Python is a Beginner's Language Python is an excellent language for
beginning programmers since it allows for the development of various
applications, ranging from basic text processing to web browsers and
games.
1.5 PYTHON CHARACTERISTICS
The following are some of the most significant features of Python
programming:
• It supports OOP as well as functional and formal programming
approaches.
• It can be used as a scripting language or compiled into byte code for
large-scale application development.
• It supports dynamic type checking and offers very high-level dynamic
data types.
• It allows for the garbage disposal to be automated.
• C, C++, COM, ActiveX, CORBA, and Java are easily integrated.
Example of a program
Python's version of Hello World.
I'm sending you a small traditional Python Hello World program to get you
excited about Python. You can check it out using the Demo connection.
("Hello, Python!"); print
1.6 PYTHON LANGUAGE FEATURES
Python has a lot of features, some of which are mentioned below –
1. Simple to code:
Python is a programming language with a high degree of abstraction.
Python is a very simple language compared to other programming
languages such as C, C#, Javascript, and Java. Python is a very simple
language; everyone can learn the basics in a few hours or days. It's also a
language that's easy to learn for programmers.
2. Open Source and Free Software:
The Python programming language is freely accessible on the official
website, and you can download it by clicking on the Download Python
keyword below.
Python is available for download.
Since it is open-source, the source code is also available to the general
public. As a result, you can download it, use it, and share it.

7
Python Programming

1. Object-Oriented Programming Language (OOP):


Object-Oriented programming is one of Python's most important features.
Python supports object-oriented language and concepts such as classes,
encapsulation, etc.
4. Support for GUI Programming:
Python modules such as PyQt5, PyQt4, wxPython, and Tk may be used to
build graphical user interfaces.
PyQt5 is the most common Python graphical application framework.
5. Advanced Language:
Python is a programming language with a high degree of abstraction. We
don't need to recall the machine architecture or manage memory while
writing Python programs.
6. Function that can be expanded:
Python is a language that can be extended. We can convert Python code to
C or C++ and then compile it in that language.
7. Python is a portable programming language:
Python is also a portable language. For instance, if we have python code
for Windows and want to run it on other platforms like Linux, Unix, or
Mac, we don't need to modify it; we can run it on any platform.
8. Python is an integrated programming language:
Python is interactive since it can easily be combined with other
programming languages such as c, c++, and others.
1. Language Interpretation:
Python is an Interpreted Language, meaning its code is implemented line
by line. Unlike other languages such as C, C++, Java, and others, Python
code does not need compilation, making debugging easier. Python's source
code is translated into bytecode, an immediate representation of the code.
10 Large Standard Library
Python has a comprehensive standard library that includes many modules
and functions, preventing you from writing your code for anything. Regular
expressions, unit testing, web browsers, and other libraries are available in
Python.

Dynamically Typed Language (DTL):


Python is a language of dynamic typing. The variable type (int, double,
long, etc.) is determined at run time rather than in advance, so we don't
have to define the variable type.
1.7 PYTHON MODULES

8
Python Programming

A file containing a set of functions you want to include in the application is


called a Module.
Create a Module
To create a module, save the code you want in a file with the file extension
.py:
Example
Save this code in a file named mymodule.py
def greeting(name):
print("Hello, " + name)
Use a Module
Now we can use the module we just created by using the import statement:
Example
Import the module named my module, and call the greeting function:
Import my module
my module. greeting("Jonathan")
Note: When using a function from a module, use the syntax:
module_name.function_name. Variables in Module
The module can contain functions, as already described, but also variables
of all types(arrays, dictionaries, objects, etc.):
Naming a Module
You can name the module file whatever you like, but it must have the file
extension .py
Re-naming a Module
You can create an alias when you import a module by using the keyword:
Example
Create an alias for my module called mx:
import mymodule as mx
a = mx.person1["age"]
print(a)

Built-in Modules
There are several built-in modules in Python, which you can import
whenever you like.
Example
Import and use the platform module:
import platform
x = platform.system()
print(x)
Using the dir() Function

9
Python Programming

A module has a built-in function to list all the function names (or variable
names). The dir() function:
Example
List all the defined names belonging to the platform module:
import platform
x = dir(platform)
print(x)
Note: The dir() function can be used on all modules. Also, the ones you
create yourself.
Import from Module
You can import only parts from a module by using the from keyword.
Example
The module named my module has one function and one dictionary:
def greeting(name):
print("Hello, " + name)
person1 = {"name": "John," "age": 36, "country": "Norway"}
Example
Import only the person1 dictionary from the module:
from mymodule import person1
print (person1["age"])
Note: When importing from a keyword, do not use the module name when
referring to
elements in the module. Example: person1["age"], not my
module.person1["age"].
1.8 PYTHON OOPS CONCEPTS
Python, like other general-purpose programming languages, has always
been object-oriented. It enables us to create applications with an Object-
Oriented approach. Classes and objects are simple to create and utilize in
Python.
An object-oriented paradigm is used to create the program using classes
and objects. The object is associated with real-world entities such as a
book, a house, a pencil, etc. The oops concept is concerned with
developing reusable code. It is a common problem for solving problems by
constructing objects.
The following are the major principles of an object-oriented programming
system.
o Class
o Object
o Method
o Inheritance

10
Python Programming

o Polymorphism
o Data Abstraction
o Encapsulation
Class
A collection of objects can be defined as a class. It is a logical entity with
certain characteristics and procedures. For example, an employee class
should include an attribute and method, such as an email id, name, age,
salary, etc.
Syntax
class ClassName:
<statement-1>
.
.
<statement-N>
Object
The object is an entity that has a state and behavior. It may be any real-
world object like a mouse, keyboard, chair, table, pen, etc.
Everything in Python is an object, and almost everything has attributes
and methods. All functions have a built-in attribute __doc__, which returns
the docstring defined in the function source code.
When we define a class, it needs to create an object to allocate the
memory. Consider the following example.
Example:
class car:
def __init__(self,modelname, year):
self.modelname = modelname
self.year = year
def display(self):
print(self.modelname,self.year)

c1 = car("Toyota", 2016)
c1.display()
Output:
Toyota 2016
In the above example, we created the class named car, which has two
attributes model name and year. We have created a c1 object to access the
class attribute. The c1 object will allocate memory for these values. We will
learn more about class and objects in the next tutorial.

11
Python Programming

Method
The method is a function that is associated with an object. In Python, a
method is not unique to class instances. Any object type can have
methods.
Inheritance
Inheritance is the most important aspect of object-oriented programming,
which simulates the real-world concept of inheritance. It specifies that the
child object acquires all the properties and behaviors of the parent object.
By using inheritance, we can create a class that uses another class's
properties and behavior. The new class is known as a derived class or child
class, and the one whose properties are acquired is known as a base class
or parent class.
It provides the re-usability of the code.
Polymorphism
Polymorphism contains two words, "poly" and "morphs." Poly means many,
and morph means shape. By polymorphism, we understand that one task
can be performed differently. For example - you have a class animal, and
all animals speak. But they speak differently. Here, the "speak" behavior is
polymorphic and depends on the animal. So, the abstract "animal" concept
does not actually "speak," but specific animals (like dogs and cats) have a
concrete implementation of the action "speak."
Encapsulation
Encapsulation is also an essential aspect of object-oriented programming.
It is used to restrict access to methods and variables. In encapsulation,
code and data are wrapped together within a single unit from being
modified by accident.
Data Abstraction
Data abstraction and encapsulation are often used as synonyms. Both are
nearly synonyms because data abstraction is achieved through
encapsulation.
Abstraction is used to hide internal details and show only functionalities.
Abstracting something means giving names to things so that the name
captures the core of what a function or a whole program does.
Object-oriented vs. Procedure-oriented Programming languages
The difference between object-oriented and procedure-oriented
programming is given below:

Inde Object-oriented Procedural


x Programming Programming

12
Python Programming

1. Object-oriented Procedural
programming is the programming uses a list
problem-solving of instructions to do
approach where computation step by
computation is done step.
using objects.

2. It makes development In procedural


and maintenance easier. programming, It is not
easy to maintain the
codes when the project
becomes lengthy.

3. It simulates a real-world It doesn't simulate the


entity. So real-world real world. It works on
problems can be easily step-by-step
solved through oops. instructions divided
into small parts called
functions.

4. It provides data hiding. Procedural language


So it is more secure than doesn't provide any
procedural languages. proper way for data
You cannot access binding, making it less
private data from secure.
anywhere.

5. Example of object- Examples of procedural


oriented programming languages are C,
languages is C++, Java, Fortran, Pascal, VB, etc.
.Net, Python, C#, etc.

Python Class and Objects


As we discussed in the last course, a class is a virtual entity that can be
considered an object's blueprint. The class was created when it was
initialized. Let's look at an example to help you understand.
Assume a class is a building prototype. A building has all the data about
the floor, rooms, doors, windows, etc. We can create as many structures as

13
Python Programming

we desire based on these details. As a result, the building may be seen as


a class, and we can create as many objects for this class as we like.
The object, on the other hand, is a class instance. The process of
generating an object is called instantiation.
This course portion will explore how to create Python classes and objects.
We'll also review how to retrieve a class attribute using an object.
Creating classes in Python A class may be created in Python by using the
keyword class, followed by the class name. The syntax for creating a class
is shown below.
Syntax
1. class ClassName:
2. #statement_suite
Each class in Python is connected with a documentation string, which can
be accessed using class-name>. doc__. A class contains a statement suite
that defines fields, constructors, functions, and so forth.
Consider the following example, which contains how to create a class
Employee with two fields: Employee id and name.
The class also contains the function display(), which displays the
Employee's details.
Example
class Employee:
id = 10
name = "Guru"
def display (self):
print(self.id,self.name)
The self-variable is used here to reference the current class object. In the
function definition, it is always the first argument. On the other hand, the
use of self is optional in the function call.
The self-parameter relates to the current instance of the class and allows
access to the class variables. Instead of self, we may use anything, but it
must be the first parameter of any function in the class.
Creating a class instance If we wish to utilize the class attributes in
another class or method, we must first create an instance of the class. A
class can be instantiated by invoking it with the class name.
The syntax for creating a class instance is shown below.
<object-name> = <class-name>(<arguments>)
The following example creates the instance of the class Employee defined
in the above example.
Example
class Employee:

14
Python Programming

id = 10
name = "Guru"
def display (self):
print("ID: %d \nName: %s"%(self.id,self.name))
# Creating an emp instance of the Employee class
emp = Employee()
emp.display()
Output:
ID: 10
Name: Guru
We created the Employee class in the preceding code and provided values
to its two attributes, id and name. We can see that we passed the self as a
parameter to the display function. It alludes to the same class property.
We've created a new instance object named emp. We may access the
class's attributes by utilizing them.
Delete the Object Using the del keyword, we may delete the object's
properties or the object itself. Consider the following example.
Example
class Employee:
id = 10
name = "Guru"

def display(self):
print("ID: %d \nName: %s" % (self.id, self.name))
# Creating an emp instance of the Employee class

emp = Employee()

# Deleting the property of an object


del emp. id
# Deleting the object itself
del emp
emp.display()
It will go through the Attribute error because we have deleted the
object emp.
1.9 PYTHON CONSTRUCTOR
A constructor is a special method (function) used to initialize the class
instance members.
In C++ or Java, the constructor has the same name as its class, but it
treats the constructor differently in Python. It is used to create an object.

15
Python Programming

Constructors can be of two types.


1. Parameterized Constructor
2. Non-parameterized Constructor
When we create an object of this class, the constructor definition is
executed. Constructors also ensure that the object has adequate resources
to complete startup tasks.
Creating the constructor in Python The __init__() method in Python
replicates the class's constructor. When the class is instantiated, this
method is called. It accepts the self-keyword as the first argument, which
provides access to the class's attributes or methods.
Depending on the __init__() definition, we can pass any number of
parameters when creating the class object. It's primarily used to set up the
class's attributes. Every class must have a constructor, even if it only uses
the default constructor.
Consider the example below to initialize the Employee class attributes.
Example
class Employee:
def __init__(self, name, id):
self.id = id
self.name = name

def display(self):
print("ID: %d \nName: %s" % (self.id, self.name))

emp1 = Employee("Guru", 101)


emp2 = Employee("Guru", 102)

# accessing display() method to print employee one information

emp1.display()

# accessing display() method to print employee two information


emp2.display()
Output:
ID: 101
Name: Guru
ID: 102
Name: Guru

16
Python Programming

Counting the number of objects in a class


The constructor is called automatically when we create the object of the
class. Consider the following example.
Example
class Student:
count = 0
def __init__(self):
Student.count = Student.count + 1
s1=Student()
s2=Student()
s3=Student()
print("The number of students:",Student.count)
Output:
The number of students: 3
Python Non-Parameterized Constructor
When we don't wish to alter the value, we use the non-parameterized
constructor or the constructor with simply self as an argument. Consider
the following example.
Example
1. class Student:
# Constructor - non parameterized
def __init__(self):
print("This is non parametrized constructor")
def show(self,name):
print("Hello", name)
student = Student()
student.show("Guru")
Python Parameterized Constructor
The parameterized constructor has multiple parameters along with
the self. Consider the following example.
Example
1. class Student:
# Constructor - parameterized
def __init__(self, name):
print("This is parametrized constructor")
self.name = name
def show(self):
print("Hello", self. name)
student = Student("Guru")
student.show()

17
Python Programming

Output:
This is parametrized constructor
Hello Guru
Python Default Constructor
When we forget to declare or include the constructor in the class, it
becomes the default constructor. It doesn't do anything but initialize the
objects. Consider the following example. Example
class Student:
roll_num = 101
name = "Joseph"

def display(self):
print(self.roll_num,self.name)

st = Student()
st.display()
Output:
101 joseph
More than One Constructor in a Single class
Let's look at another scenario: what happens if we declare the two same
constructors in the class?
Example
class Student:
def __init__(self):
print("The First Constructor")
def __init__(self):
print("The second contructor")

st = Student()
Output:
The Second Constructor
The object is called the second constructor in the above code, whereas
both have the same configuration. The first method is not accessible by
the st object. Internally, the object of the class will always call the last
constructor if the class has multiple constructors.
Note: Constructor overloading is not allowed in Python.
Python built-in class functions
The built-in functions defined in the class are described in the following
table.

18
Python Programming

S Function Description
N

1 getattr(obj,name,def It is used to access the attribute


ault) of the object.

2 setattr(obj, It is used to set a particular


name,value) 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
class Student:
def __init__(self, name, id, age):
self.name = name
self.id = id
self.age = age

# creates the object of the class Student


s = Student("Guru", 101, 22)

# prints the attribute name of the object s


print(getattr(s, 'name'))

# reset the value of attribute age to 23


setattr(s, "age", 23)

# prints the modified value of age


print(getattr(s, 'age'))

# prints true if the student contains the attribute with the name id

print(hasattr(s, 'id'))
# deletes the attribute age
19
Python Programming

delattr(s, 'age')

# this will give an error since the attribute age has been deleted
print(s.age)
Output:
Guru
23
True
AttributeError: 'Student' object has no attribute 'age.'
Built-in class attributes
Along with the other attributes, a Python class also contains some built-in
class attributes which provide information about the class.
The built-in class attributes are given in the below table.

S Attribu Description
N te

1 __dict__ It provides the dictionary containing the


information about the class namespace.

2 __doc__ It contains a string that has the class


documentation

3 __name_ It is used to access the class name.


_

4 __modul It is used to access the module in which


e__ this class is defined.

5 __bases_ It contains a tuple including all base


_ classes.

Example
class Student:
def __init__(self,name,id,age):
self.name = name;
self.id = id;
self.age = age
def display_details(self):
print("Name:%s, ID:%d, age:%d"%(self.name,self.id))
20
Python Programming

s = Student("Guru",101,22)
print(s.__doc__)
print(s.__dict__)
print(s.__module__)
Output:
None
{'name': 'Guru', 'id': 101, 'age': 22}
__main__
1.10 PYTHON INHERITANCE
The object-oriented paradigm places a premium on inheritance. Because
we may utilize an existing class to create a new class rather than creating
it from scratch, inheritance allows us to reuse code in the program.
In inheritance, the child class inherits the parent class's properties and
accesses all of the parent class's data members and functions. A child
class can also implement the parent class's functions. In this lesson
portion, we will go into inheritance in depth.
In Python, a derived class can inherit from a base class by specifying the
base in the brackets following the derived class name. Consider the
following syntax for inheriting a base class into a derived class.

Syntax
class derived-class(base class):
<class-suite>
A class can inherit multiple classes by mentioning them inside the bracket.
Consider the following syntax.
Syntax
class derive-class(<base class 1>, <base class 2>, ..... <base class n>):
<class - suite>
Example 1
class Animal:
def speak(self):
print("Animal Speaking")
#child class Dog inherits the base class Animal

21
Python Programming

class Dog(Animal):
def bark(self):
print("dog barking")
d = Dog()
d.bark()
d.speak()
Output:
dog barking
Animal Speaking

Python Multi-Level inheritance


Multi-level inheritance is possible in Python, as in other object-oriented
languages. When a derived class inherits another derived class, multi-level
inheritance is stored. Python does not restrict the number of levels at

which multi-level inheritance can be preserved.


The syntax of multi-level inheritance is given below.
Syntax
class class1:
<class-suite>
class class2(class1):
<class suite>
class class3(class2):
<class suite>
.
.
Example
class Animal:
def speak(self):
print("Animal Speaking")
#The child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):

22
Python Programming

print("dog barking")
#The child class Dogchild inherits another child class Dog
class DogChild(Dog):
def eat(self):
print("Eating bread...")
d = DogChild()
d.bark()
d.speak()
d.eat()
Output:
dog barking
Animal Speaking
Eating bread.

Python Multiple inheritances


Python allows us to inherit multiple base classes in the child class.

The syntax to perform multiple inheritances is given below.


Syntax
class Base1:
<class-suite>

class Base2:
<class-suite>
.
.
.
class BaseN:
<class-suite>

class Derived(Base1, Base2, ...... BaseN):


<class-suite>

23
Python Programming

Example
class Calculation1:
def Summation(self,a,b):
return a+b;
class Calculation2:
def Multiplication(self,a,b):
return a*b;
class Derived(Calculation1,Calculation2):
def Divide(self,a,b):
return a/b;
d = Derived()
print(d.Summation(10,20))
print(d.Multiplication(10,20))
print(d.Divide(10,20))
Output:
30
200
0.5

The issubclass(sub,sup) method


The issubclass(sub, sup) method checks the relationships between the
specified classes. It returns true if the first class is the subclass of the
second class, and false otherwise.
Consider the following example.
Example
class Calculation1:
def Summation(self,a,b):
return a+b;
class Calculation2:
def Multiplication(self,a,b):
return a*b;
class Derived(Calculation1,Calculation2):
def Divide(self,a,b):
return a/b;
d = Derived()
print(issubclass(Derived,Calculation2))
print(issubclass(Calculation1,Calculation2))
Output:
True
False

24
Python Programming

The isinstance (obj, class) method


The instance() method checks the relationship between the objects and
classes. It returns true if the first parameter, i.e., obj, is the instance of the
second parameter, i.e., class.
Consider the following example.
Example
class Calculation1:
def Summation(self,a,b):
return a+b;
class Calculation2:
def Multiplication(self,a,b):
return a*b;
class Derived(Calculation1,Calculation2):
def Divide(self,a,b):
return a/b;
d = Derived()
print(isinstance(d,Derived))
Output:
True

1.11 METHOD OVERRIDING


We can provide specific implementation of the parent class method in our
child class. The concept is called method overriding when the parent class
method is defined in the child class with some specific implementation. We
may need to override a method where a different definition of a parent
class method is needed in the child class.
Consider the following example to perform method overriding in python.
Example
class Animal:
def speak(self):
print("speaking")
class Dog(Animal):
def speak(self):
print("Barking")
d = Dog()
d.speak()
Output:
Barking

25
Python Programming

Real Life Example of method overriding


class Bank:
def getroi(self):
return 10;
class SBI(Bank):
def getroi(self):
return 7;

class ICICI(Bank):
def getroi(self):
return 8;
b1 = Bank()
b2 = SBI()
b3 = ICICI()
print("Bank Rate of interest:",b1.getroi());
print("SBI Rate of interest:",b2.getroi());
print("ICICI Rate of interest:",b3.getroi());
Output:
Bank Rate of interest: 10
SBI Rate of interest: 7
ICICI Rate of interest: 8
1.12 DATA ABSTRACTION IN PYTHON
Abstraction is an important aspect of object-oriented programming. In
python, we can also perform data hiding by adding the double underscore
(___) as a prefix to the attribute which is to be hidden. After this, the
attribute will not be visible outside the class through the object.
Consider the following example.
Example
1. class Employee:
2. __count = 0;
3. def __init__(self):
4. Employee.__count = Employee.__count+1
5. def display(self):
6. print("The number of employees",Employee.__count)
7. emp = Employee()
8. emp2 = Employee()
9. try:
10. print(emp.__count)
11. finally:
12. emp.display()

26
Python Programming

Output:
The number of employees 2
AttributeError: 'Employee' object has no attribute '__count'
1.13 ABSTRACTION IN PYTHON
Abstraction is used to shield users from the internal functioning of a
function. Users only interact with the function's basic implementation; the
inner workings are concealed. In other words, we all use smartphones and
are quite familiar with their functions, such as camera, voice recorder,
call-dialing, and so on, but we don't know how these operations are
happening in the background. Consider another example: when we use the
Tremont to boost the volume. We're not sure how hitting a key raises the
volume of the television. We only know how to boost the volume by
pressing the "+" button.
That is the precise abstraction that is used in the object-oriented concept.
What Is the Importance of Abstraction?
Python uses Abstraction to conceal unnecessary data/classes and
minimize complexity. It also improves application efficiency. We'll learn
how to achieve abstraction using the Python program.
Abstraction classes in Python Abstract classes and interfaces can be used
to accomplish abstraction in Python.
An abstract class is a class that consists of one or more abstract methods.
The implementation of abstract methods is not included. Subclasses can
inherit abstract classes, and abstract methods can be defined in
subclasses. Abstraction classes are intended to serve as the template for
the other class. When creating major functions, an abstract class might be
beneficial. An abstract class can also offer a common interface for diverse
component implementations. Python has the ABC module, which allows
you to utilize abstraction in your Python program. Let's have a look at the
syntax below.
Syntax
from ABC import ABC
class ClassName(ABC):
We import the ABC class from the ABC module.
Abstract Base Classes
An abstract base class is the interface's common application program for a
collection of subclasses. It can be used by a third party to offer
implementations, such as via plugins. It is particularly useful when
working with a big code base when it is difficult to remember all classes.
Unlike other high-level languages, working Abstract Classes, Python does
not supply the abstract class itself. We must import the ABC module,

27
Python Programming

which is the foundation for creating Abstract Base classes (ABC). The ABC
operates by abstracting methods from the underlying class. It registers
concrete classes as the abstract base's implementation. We use the
@abstractmethod decorator to define an abstract method, or if we don't
define it, it becomes an abstract method by default. Let's have a look at an
example.
Example -
# Python program demonstrate
# abstract base class work
from ABC import ABC, abstract method
class Car(ABC):
def mileage(self):
pass
class Tesla(Car):
def mileage(self):
print("The mileage is 30kmph")
class Suzuki(Car):
def mileage(self):
print("The mileage is 25kmph ")
class Duster(Car):
def mileage(self):
print("The mileage is 24kmph ")
class Renault(Car):
def mileage(self):
print("The mileage is 27kmph ")
# Driver code
t= Tesla ()
t.mileage()
r = Renault()
r.mileage()
s = Suzuki()
s.mileage()
d = Duster()
d.mileage()
Output:
The mileage is 30kmph
The mileage is 27kmph
The mileage is 25kmph
The mileage is 24kmph
Explanation -

28
Python Programming

We have imported the ABC module to create the abstract base class in the
above code. We created the Car class that inherited the ABC class and
defined an abstract method named mileage(). We then inherited the base
class from the three subclasses and implemented the abstract method
differently. We created the objects to call the abstract method.
Let's understand another example.
Let's understand another example.
Example -
# Python program to define
# abstract class
from ABC import ABC
class Polygon(ABC):
# abstract method
def sides(self):
pass
class Triangle(Polygon):
def sides(self):
print("Triangle has 3 sides")
class Pentagon(Polygon):
def sides(self):
print("Pentagon has 5 sides")
class Hexagon(Polygon):
def sides(self):
print("Hexagon has 6 sides")
class square(Polygon):
def sides(self):
print("I have 4 sides")
# Driver code
t = Triangle()
t.sides()
s = square()
s.sides()
p = Pentagon()
p.sides()
k = Hexagon()
K.sides()
Output:
Triangle has 3 sides
The Square has 4 sides
Pentagon has 5 sides

29
Python Programming

Hexagon has 6 sides


Explanation -
We defined the preceding code's abstract base class, Polygon, and abstract
method. All subclasses inherit this basic class. In each subclass, we
implemented the abstract method. We created the subclasses object and
called the sides() method. The subclasses' secret implementations of the
sides() method come into play. The abstract method sides() defined in the
abstract class are never called.
Points to Know The following are some things to remember regarding the
abstract base class in Python.
o An Abstract class can have both traditional and abstract methods.
O We cannot create objects for the Abstract class since it cannot be
instantiated.
Abstraction is required to conceal the fundamental functionality from
consumers. We have covered all of the fundamental principles of
Abstraction in Python.

30
Python Programming

CHAPTER 2
DATA EXPRESSIONS STATEMENTS
2.1 INTRODUCTION
Python is a general-purpose interpreted, interactive, object-oriented,
high-level programming language.
Python was named after the film "Monty Python's Flying Circus." Python
was first introduced in the year 2000.
Python is interpreted: The interpreter processes Python at runtime. You do
not need to compile your program before executing it.
Python is Interactive: You may sit at a Python prompt and interact directly
with the interpreter to develop your programs.
Python is Object-Oriented: Python supports the Object-Oriented
programming paradigm, which wraps code into objects.
Python is a Beginner's Language: Python is an excellent language for
beginning programmers and allows for creating a wide range of
applications.
PYTHON FEATURES:
Simple to learn: Python is well-defined and understandable. The program's
structure is quite basic. It uses only a few terms.
Simple to maintain: Python's source code is fairly simple to maintain.
Portability: Python can run on a broad range of hardware devices and has
the same interface across all platforms.
Interpreted: The interpreter processes Python at runtime. As a result, there
is no need to compile a program before executing it. You may just run the
program.
Extensible: Python may be embedded in C, C++, Java scripts, ActiveX, and
other programming languages.
Free and Open Source: Anyone can freely share, view the source code, and
change it.
High-Level Language: When developing programs, programmers focus on
solving the present problem; there is no need to think about low-level
features.
Scalable: Python has a fine structure and support for big programs than
shell programming.
Applications
BitTorrent file sharing
Google search engine, YouTube
Intel, Cisco, HP, and IBM
i–Robot
NASA
31
Python Programming

Facebook, Dropbox
2.2 PYTHON INTERPRETER:
InterpreterTo executes a program in a high-level language by
translating it one line at a time, you need an interpreter.

Compiler: A program that translates a program written in a high-level


language into a low-level language in preparation for subsequent

execution.
FIG 2.1 DIFFERENCE BETWEEN COMPILER AND INTERPRETER
2.3 MODES OF PYTHON INTERPRETER:
Python interpreter is a program that reads and executes Python
code. It uses two execution modes.
1. Interactive mode
2. Script mode
1. Interactive mode:
As the name indicates, Interactive Mode allows us to interact with the
operating system.
When we type a Python statement, the interpreter instantly displays the
result(s).
Advantages:
Python in interactive mode is adequate for learning, experimenting, and
exploring.
Working in interactive mode is useful for novices and testing tiny portions
of code.
Drawback:
We can't save the statements and must retype them to run them again.
You type Python programs in interactive mode, and the interpreter
displays the results
>>> 1+1
2

32
Python Programming

The chevron, >>>, uses that the interpreter is ready for you to input code.
When you type 1 + 1, the interpreter responds with 2.
>>> print ('Hello, World!')
Hello, World!
This is an example of a print statement. It displays the result on the
screen. In this example, the result is the words.

2. Script mode:
In script mode, we type a Python program into a file and then use the
interpreter to execute the file's contents.
Scripts can be stored on a disk for later use. Python programs contain the
extension.py, which means that the filename finishes with.py.
Save the code as filename.py and run the interpreter in script mode to run
the script.

Integrated Development Learning Environment (IDLE):


It is a graphical user interface built entirely in Python.
It comes with the Python language's default implementation and an
optional element of the Python package.
Features of IDLE:
A multi-window text editor with syntax highlighting.
Auto-completion with clever indentation.

33
Python Programming

Python shell to display output with syntax highlighting.


2.4 VALUES AND DATA TYPES
Value:
The value can be any letter, number, or string.
E.g., Values are 2, 42.0, and 'Hello, World!'. (These values belong
to different datatypes.)
Data type:
Every value in Python has a data type.
It is a set of values and the operations that may be performed on those
values.
Python has four standard data types:

FIG 2.2 PYTHON DATA TYPES

Numbers:
The Number data type holds Numerical Values.
This data type is immutable [values/items cannot be changed].
Python supports integers, floating point numbers, and complex numbers.
They are defined as,

Sequence:
A sequence is an ordered collection of items indexed by positive numbers.

34
Python Programming

It combines mutable (values that may be changed) and immutable (values


that cannot be changed) data types.
In Python, there are three types of sequence data types:
1. Strings
2. Lists
3. Tuples
1. Strings
In Python, a String is a series or sequence of characters, including letters,
numbers, and special characters.
Quotation marks denote strings:
· single quotes (' ') Eg, 'This a string in single quotes
· double quotes (" ") Eg, "'This a string in double-quotes."
· triple quotes(""" """) Eg, This is a paragraph. It is made up of
multiple lines and sentences."""
A subscript is used to access individual characters in a string (index).
Characters can be accessed using indexing and slicing operations.
Strings are immutable, meaning the string's contents cannot be changed
after it is created.
Indexing:

· Positive indexing helps in accessing the string from the


beginning
· Negative subscript helps in accessing the string from the end.
· Subscript 0 or –ve n(where n is the length of the string)
displays the first element.
Example: A[0] or A[-5] will display "H"
· Subscript 1 or –ve (n-1) displays the second element.
Example: A[1] or A[-4] will display "E"

Operations on string:
i. Indexing
ii. Slicing
iii. Concatenation
iv. Repetitions
v. Member ship

35
Python Programming

FIG 2.3 STRING


2. Lists
A list is an ordered sequence of items. The values in the list are
referred to as elements/items.
It can be written as a list of comma-separated items (values) enclosed
by square brackets[ ]
The items in the lists can be of various data kinds.
Operations on the list:
Indexing
Slicing
Concatenation
Repetitions
Update, Insertion, Deletion

36
Python Programming

FIG 2.4 LIST


3. Tuple:
A tuple is similar to a list, except that parentheses surround the set of
elements rather than square brackets.
A tuple is an immutable list. In other words, once a tuple has been
created, it cannot be added or removed.
The benefit of Tuple:
Tuples are faster than lists.
A tuple can be used if the user wants to protect the data from accidental
changes.
Tuples can be used as keys in dictionaries, while lists can't.
Basic Operations:

37
Python Programming

FIG 2.5 TUPLE


Altering the tuple data type leads to an error. The following error occurs
when a user tries to do.
>>> t[0]="a"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
Type Error: 'tuple' object does not support item assignment
Mapping
-This data type is unordered and mutable.
-Dictionaries fall under Mappings.
Dictionaries:
Lists are ordered sets of objects, whereas dictionaries are unordered
sets.
Dictionary is created by using curly brackets. i,e. {}
Dictionaries are accessed via keys and not via their position.
A dictionary is an associative array (also known as hashes). Any
dictionary key is associated (or mapped) to a value.
The values of a dictionary can be any Python data type. So dictionaries
are

Unordered key-value-pairs(The association of a key and a value is called


a key-value pair )
Dictionaries don't support the sequence operation of the sequence data
types like strings, tuples, and lists.

38
Python Programming

If you try to access a key that doesn't exist, you will get an error message:
>>> words = {"house" :"Haus", "cat":"Katze"}
>>> words["car"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'car'

2.5 VARIABLES:
- A variable allows us to store a value by assigning it to a name, which
can be used later.
- Named memory locations to store values.
- Programmers generally choose names for their variables that are
meaningful.
- It can be of any length. No space is allowed.
- We don't need to declare a variable before using it. In Python, we assign
a value to a variable that will exist.
Assigning value to a variable:

The value should be given on the right side of the assignment operator(=)
and the variable on the left side.
>>>counter =45
print(counter)
Assigning a single value to several variables simultaneously:
>>> a=b=c=100
Assigning multiple values to multiple variables:
>>> a,b,c=2,4,"ram"
2.6 KEYWORDS:
Keywords are the reserved words in Python.

39
Python Programming

We cannot use a keyword as the variable name, function name, or


another identifier.
They are used to define the syntax and structure of the Python language.
Keywords are case-sensitive.

IDENTIFIERS:
Python, an identifier, is the name assigned to things such as classes,
functions, variables, and so on.
Identifiers can be a combination of letters in lowercase (a to z) or
uppercase (A to Z) or digits (0 to 9), or underscore (_).
All are good examples.
An identifier cannot start with a digit.
Keywords cannot be used as identifiers.
Cannot use special symbols like !, @, #, $, % etc., in our identifier.
The identifier can be of any length.
Example:
Names like myClass, var_1, and this_is_a_long_variable

2.7 STATEMENTS AND EXPRESSIONS:


Statements:
-Instructions that a Python interpreter can execute are called statements.
-A statement is a coding unit like creating a variable or displaying a value.
>>> n = 17
>>> print(n)
Here, The first line is an assignment statement that gives a value to n.
The second line is a print statement that displays the value of n.

40
Python Programming

Expressions:
-An expression is a combination of values, variables, and operators.
-A value all by itself is considered an expression and variable.
So the following are all legal expressions:
>>> 42
42
>>> a=2
>>> a+3+2
7
>>> z=("hi"+"friend")
>>> print(z)
Hi friend
2.8 INPUT AND OUTPUT

INPUT: Input is data entered by the user (end-user) in the program.


In python, the input () function is available for input.
Syntax for input() is:
variable = input ("data")
Example:
>>> x=input("enter the name:") enter the name: George
>>>y=int(input("enter the number"))
enter the number 3
#python accepts a string as the default data type. Conversion is required
for type.

OUTPUT: Output can be displayed to the user using a Print statement.


Syntax:
print (expression/constant/variable)
Example:
print ("Hello")
Hello

2.9 COMMENTS:
A hash sign (#) is the beginning of a comment.
The interpreter ignores anything written after # in a line.
Eg:percentage = (minute * 100) / 60 # calculating percentage of an
hour
Python does not have a multiple-line commenting feature. You have
to
comment on each line individually as follows :

41
Python Programming

Example:
# This is a comment.
# This is a comment, too.
# I said that already.
2.10 DOCSTRING:
A string appears as the initial statement in defining a module,
function, class, or method. In the docstring, we must describe what a
function/class performs.
Triple quotes are used while writing docstrings.
Syntax:
functionname__doc.__
Example:
def double(num):
"Function to double the value."
return 2*num
>>> print(double.__doc__) Function to double the value
2.11 LINES AND INDENTATION:
- Most programming languages like C, C++, and Java use braces { } to
define a code block. But python uses indentation.
- A line indentation denotes blocks of code.
- It is a space for the block of codes for class and function definitions or
flow control.
Example:
a=3
b=1
If a>b:
print("a is greater")
Else:
print("b is greater")
2.12 QUOTATION IN PYTHON:
Python accepts single ('), double ("), and triple (''' or "") quotes to denote
string literals.
Anything that is represented using quotations is considered a string.
single quotes (' ') Eg, 'This a string in single quotes
double quotes (" ") Eg, "'This a string in double-quotes."
triple quotes(""" """) Eg, This is a paragraph. It is made up of multiple
lines and sentences."""
2.13 TUPLE ASSIGNMENT
An assignment to all elements in a tuple using a single assignment
statement.

42
Python Programming

Python has a very powerful tuple assignment feature that allows a tuple
of variables on the left of an assignment to be assigned values from a tuple
on the right.
The left side is a tuple of variables; the right is a tuple of values.
Each value is assigned to its respective variable.
All the expressions on the right side are evaluated before the
assignments. This feature makes tuple assignments quite versatile.
Naturally, the number of variables on the left and the number of values
on the right have to be the same.
>>> (a, b, c, d) = (1, 2, 3)
ValueError: need more than 3 values to unpack
Example:
-It is useful to swap the values of two variables. With conventional
assignment statements, we have to use a temporary variable. For
example, to swap a and b:
Swap two numbers
a=2;b=3
print(a,b)
temp = a
a=b
b = temp
print(a,b)
Output:
(2, 3)
(3, 2)
>>>
-Tuple assignment solves this problem neatly:
(a, b) = (b, a)

-One way to think of tuple assignment is as tuple packing/unpacking.


In tuple packing, the values on the left are ‘packed’ together in a tuple:
>>> b = ("George", 25, "20000") # tuple packing
-In tuple unpacking, the values in a tuple on the right are
‘unpacked’ into the variables/names on the right:
>>> b = ("George", 25, "20000") # tuple packing
>>> (name, age, salary) = b # tuple unpacking
>>> name
'George'
>>> age
25

43
Python Programming

>>> salary
'20000'
-The right side can be any sequence (string, list, tuple)
Example:
-To split an email address into a user name and a domain
>>> mailid='[email protected]'
>>> name,domain=mailid.split('@')
>>> print name
god
print (domain)
abc.org
2.14 OPERATORS:

Operators are the constructs that can manipulate the value of operands.
Consider the expression 4 + 5 = 1. Here, 4 and 5 are called operands,
and + is called an operator

Types of Operators:
-Python language supports the following types of operators
· Arithmetic Operators
· Comparison (Relational) Operators
· Assignment Operators
· Logical Operators
· Bitwise Operators
· Membership Operators
· Identity Operators

Arithmetic operators:

They perform mathematical operations like addition, subtraction,


multiplication, etc. Assume a=10 and b=5

44
Python Programming

FIG 2.6 ARITHMETIC OPERATORS:

Examples
a=10
b=5
print("a+b=",a+b)
print("a-b=",a-b)
print("a*b=",a*b)
print("a/b=",a/b)
print("a%b=",a%b)
print("a//b=",a//b)
print("a**b=",a**b)

Output:
a+b= 15
a-b= 5
a*b= 50
a/b= 2.0
a%b= 0
a//b= 2
a**b= 100000

Comparison (Relational) Operators:


· Comparison operators are used to comparing values.
· It either returns True or False according to the condition. Assume a=10
and b=5

45
Python Programming

FIG 2.7 COMPARISON (RELATIONAL) OPERATORS:


Example
a=10
b=5
print("a>b=>",a>b)
print("a>b=>",a<b)
print("a==b=>",a==b)
print("a!=b=>",a!=b)
print("a>=b=>",a<=b)
print("a>=b=>",a>=b)

Output:
a>b=> True
a>b=> False
a==b=> False
a!=b=> True
a>=b=> False
a>=b=> True

Assignment Operators:

-Assignment operators are used in Python to assign values to variables.

46
Python Programming

FIG 2.8 ASSIGNMENT OPERATORS:

Example
a = 21
b = 10
c=0
c=a+b
print("Line 1 - Value of c is ", c)
c += a
print("Line 2 - Value of c is ", c)
c *= a
print("Line 3 - Value of c is ", c)
c /= a
print("Line 4 - Value of c is ", c)
c= 2 c %= a
print("Line 5 - Value of c is ", c) c **= a

47
Python Programming

print("Line 6 - Value of c is ", c) c //= a


print("Line 7 - Value of c is ", c)

Output
Line 1 - Value of c is 31
Line 2 - Value of c is 52
Line 3 - Value of c is 1092
Line 4 - Value of c is 52.0
Line 5 - Value of c is 2
Line 6 - Value of c is 2097152
Line 7 - Value of c is 99864

Logical Operators:

-Logical operators are the and, or, not operators.

FIG 2.9 LOGICAL OPERATORS:

Example
a = True
b = False
print(a and b is, a and b)
print(a or b is',a or b)
print('not a is',not a)

Output
x and y are False
x or y is True
not x is False

Bitwise Operators:

A bitwise operation operates on one or more bit patterns at the level of


individual Bits
Example:
Let x = 10 (0000 1010 in binary) and
48
Python Programming

y = 4 (0000 0100 in binary)

FIG 2.10 BITWISE OPERATORS:


Example
a = 60 # 60 = 0011 1100
b = 13 # 13 = 0000 1101
c=0
c = a & b; # 12 = 0000 1100
print "Line 1 - Value of c is ", c
c = a | b; # 61 = 0011 1101
print "Line 2 - Value of c is ", c
c = a ^ b; # 49 = 0011 0001
print "Line 3 - Value of c is ", c
c = ~a; # -61 = 1100 0011
print "Line 4 - Value of c is ", c
c = a << 2; # 240 = 1111 0000
print "Line 5 - Value of c is ", c
c = a >> 2; # 15 = 0000 1111
print "Line 6 - Value of c is ", c

Output
Line 1 - Value of c is 12
Line 2 - Value of c is 61
Line 3 - Value of c is 49
Line 4 - Value of c is -61
Line 5 - Value of c is 240
Line 6 - Value of c is 15

Membership Operators:

Evaluate whether to find a value or a variable in the specified sequence of


string, list, tuple, or dictionary.

49
Python Programming

Let, x=[5,3,6,4,1]. In and not-in operators check the particular item in a


list.

FIG 2.11 MEMBERSHIP OPERATORS:


Example:
x=[5,3,6,4,1]
>>> 5 in x
True
>>> 5 not in x
False

Identity Operators

They are used to check if two values (or variables) are located on the same
part of the memory.

FIG 2.12 IDENTITY OPERATORS

Example
x=5
y=5
x2 = 'Hello'
y2 = 'Hello'
print(x1 is not y1)
print(x2 is y2)

Output
False
True
2.15 OPERATOR PRECEDENCE:
When an expression contains more than one operator, the order of
evaluation depends on the order of operations.

50
Python Programming

FIG 2.13 OPERATOR PRECEDENCE


-For mathematical operators, Python follows mathematical convention.

-The acronym PEMDAS (Parentheses, Exponentiation, Multiplication,


Division, Addition, Subtraction) is a useful way to remember the rules:

Parentheses have the highest precedence and can be used to force an


expression to evaluate in the order you want. Since expressions in
parentheses are evaluated first, 2 * (3-1)is 4, and (1+1)**(5-2) is 8.

You can also use parentheses to make an expression easier to read, as in


(minute * 100) / 60, even if it doesn’t change the result.

Exponentiation has the next highest precedence, so 1 + 2**3 is 9, not 27,


and 2 *3**2 is 18, not 36.

Multiplication and Division have higher precedence than Addition and


Subtraction. So 2*3-1 is 5, not 4, and 6+4/2 is 8, not 5.

51
Python Programming

Operators with the same precedence are evaluated from left to right
(except exponentiation).
Example:
a=9-12/3+3*2-1
a=?
a=9-4+3*2-1
a=9-4+6-1
a=5+6-1
a=11-1
a=10

A=2*3+4%5-3/2+6
A=6+4%5-3/2+6
A=6+4-3/2+6
A=6+4-1+6
A=10-1+6
A=9+6
A=15

find m=?
m=-43||8&&0||-2
m=-43||0||-2
m=1||-2
m=1

a=2,b=12,c=1
d=a<b>c
d=2<12>1
d=1>1
d=0
a=2,b=12,c=1
d=a<b>c-1
d=2<12>1-1
d=2<12>0
d=1>0
d=1
a=2*3+4%5-3//2+6
a=6+4-1+6
a=10-1+6
a=15

52
Python Programming

2.16 ARGUMENTS TYPES:


1. Required Arguments
2. Keyword Arguments
3. Default Arguments
4. Variable length Arguments
1. Required Arguments:
The number of arguments in the function call should match exactly with
the function definition.
def my_details( name, age ):
print("Name: ", name)
print("Age ", age)
return
my_details("George",56)
Output:
Name: George
Age 56

2. Keyword Arguments:
Python interpreters can use the keywords provided to match the values
with parameters, even if they are arranged out of order.
def my_details( name, age ):
print("Name: ", name)
print("Age ", age)
return
my_details(age=56,name="george")
Output:
Name: george
Age 56

3. Default Arguments:
Assumes a default value if a value is not provided in the function call for
that argument.
def my_details( name, age=40 ):
print("Name: ", name)
print("Age ", age)
return
my_details(name="george")
Output:
Name: george
Age 40

53
Python Programming

4. Variable length Arguments


Variable length arguments are used if we want to specify more arguments
than specified while defining the function. The * symbol denotes it before
the parameter.
def my_details(*name ):
print(*name)
my_details("rajan", "rahul", "micheal", " arjun")
Output:
rajan rahul micheal arjun
2.17 ILLUSTRATIVE PROGRAMS
Program for SWAPPING(Exchanging )of values
a = int(input("Enter a value "))
b = int(input("Enter b value "))
c=a
a=b
b=c
print("a=",a,"b=",b,)

Output
Enter a value of 5
Enter b value 8
a=8
b=5
Program to find the distance between two points
import math
x1=int(input("enter x1"))
y1=int(input("enter y1"))
x2=int(input("enter x2"))
y2=int(input("enter y2"))
distance =math.sqrt((x2-x1)**2)+((y2-y1)**2)
print(distance)
Output
enter x1 7
enter y1 6
enter x2 5
enter y2 7
2.5

Program to circulate n numbers


a=list(input("enter the list"))

54
Python Programming

print(a)
for i in range(1,len(a),1):
print(a[i:]+a[:i])
Output:
enter the list '1234'
['1', '2', '3', '4']
['2', '3', '4', '1']
['3', '4', '1', '2']
['4', '1', '2', '3']

55
Python Programming

CHAPTER – 3
CONTROL FLOW, FUNCTIONS
3.1 BOOLEAN VALUES:
Boolean:
Boolean data types have two values. They are 0 and 1.
0 represents False
1 represents True
True and False are keywords.
Example:
>>> 3==5
False
>>> 6==6
True
>>> True+True
2
>>> False+True
1
>>> False*True
0
3.2 CONDITIONALS
Conditional if
Alternative if… else
Chained if…elif…else
Nested if….else
Conditional (if):
conditional (if) is used to test a condition; if the condition is true, the
statements inside it will be executed.
Syntax:
if(condition 1):
Statement 1

Flowchart:

56
Python Programming

Example:
1. Program to provide flat rs 500 if the purchase exceeds 2000.
2. Program to provide bonus marks if the category is sports.
Program to provide flat rs 500 if the purchase amount exceeds 2000.
purchase=eval(input("enter your purchase amount"))
if(purchase>=2000):
purchase=purchase-500
print("amount to pay",purchase)

output
enter your purchase
amount
2500
amount to pay
2000
Program to provide bonus marks if the category is sports
m=eval(input("enter ur mark out of 100"))
c=input("enter ur category G/S")
if(c=="S"):
m=m+5
print("mark is",m)

output
enter your mark out of 100
85
enter your category G/S
S
mark is 90
alternative (if-else)
The condition must be true or false in the alternative. This else statement
can be used in conjunction with an if statement. When the condition is
57
Python Programming

false, the else statement performs a code block. If the condition is true, the
statements within the if are executed; otherwise, the else part is executed.
Because they are branches in the execution flow, the alternatives are
referred to as branches.
Syntax:

Flowchart:

Examples:
1. odd or even number
2. positive or negative number
3. leap year or not
4. greatest of two numbers
5. eligibility for voting
Odd or even number
n=eval(input("enter a number"))
if(n%2==0):

58
Python Programming

print("even number")
else:
print("odd number")

Output
enter a number4
even number
a positive or negative number
n=eval(input("enter a number"))
if(n>=0):
print("positive number")
else:
print("negative number")

Output
enter a number8
positive number

leap year or not


y=eval(input("enter a yaer"))
if(y%4==0):
print("leap year")
else:
print("not leap year")

Output
enter a yaer2000
leap year
greatest of two numbers
a=eval(input("enter a value:"))
b=eval(input("enter b value:"))
if(a>b):
print("greatest:",a)
else:
print("greatest:",b)

Output
enter a value:4
enter b value:7
greatest: 7

59
Python Programming

eligibility for voting


age=eval(input("enter ur age:"))
if(age>=18):
print("you are eligible for vote")
else:
print("you are eligible for vote")

Output
enter your age:78
you are eligible to vote
Chained conditionals(if-elif-else)
· The elif is short for else if.
· This is used to check more than one condition.
· If the condition1 is False, it checks condition2 of the elif block.
If all the conditions are False, then the other part is executed.
· Among the several if...elif...else parts, only one is executed
according to the condition.
• The if block can have only one else block. But it can have multiple elif
blocks.
• The way to express a computation like that is a chained conditional.
Syntax:

Flowchart:

60
Python Programming

Example:
1. student mark system
2. traffic light system
3. compare two numbers
4. roots of quadratic equation

student mark system


mark=eval(input("enter ur mark:"))
if(mark>=90):
print("grade:S")
elif(mark>=80):
print("grade:A")
elif(mark>=70):
print("grade:B")
elif(mark>=50):
print("grade:C")
else:
print("fail")

Output
enter your mark:78
grade: B

traffic light system


colour=input("enter colour of light:")
if(colour=="green"):
print("GO")
elif(colour=="yellow"):
print("GET READY")
else:
print("STOP")

Output
enter the color of light: green
GO

compare two numbers


x=eval(input("enter x value:"))
y=eval(input("enter y value:"))

61
Python Programming

if(x == y):
print("x and y are equal")
elif(x < y):
print("x is less than y")
else:
print("x is greater than y")

Output
enter x value:5
enter y value:7
x is less than y

Roots of quadratic equation


a=eval(input("enter a value:"))
b=eval(input("enter b value:"))
c=eval(input("enter c value:"))
d=(b*b-4*a*c)
if(d==0):
print("same and real roots")
elif(d>0):
print("diffrent real roots")
else:
print("imaginagry roots")

output
enter a value:1
enter b value:0
enter c value:0
same and real roots

Nested conditionals

One conditional can also be nested within another. A variety of conditions


can be nested within one another if the condition is true and another if
condition one is checked. If both conditions are met, statement 1 is
executed; otherwise, statement 2 is executed. Statement 3 is executed if
the condition is false.
Syntax:

62
Python Programming

Flowchart:

Example:
1. greatest of three numbers
2. positive, negative, or zero

greatest of three numbers


a=eval(input("enter the value of a"))
b=eval(input("enter the value of b"))
c=eval(input("enter the value of c"))
if(a>b):
if(a>c):
print("the greatest no is",a)
else:
print("the greatest no is",c)
else:
if(b>c):
print("the greatest no is",b)
63
Python Programming

else:
print("the greatest no is",c)

output
enter the value of a 9
enter the value of a 1
enter the value of an 8
the greatest no is 9

positive, negative, or zero


n=eval(input("enter the value of n:"))
if(n==0):
print("the number is zero")
else:
if(n>0):
print("the number is positive")
else:
print("the number is negative")

output
enter the value of n:-9
the number is negative
3.3 ITERATION/CONTROL STATEMENTS:
· state
· while
· for
· break
· continue
· pass
State:
The transition from one process to another process under specified
conditions within a time is called a state.
While loop:
• While loop statement in Python is used to repeatedly executes a set of
statements as long as a given condition is true.
• In a while loop, the test expression is tested first. Only if the test
expression is True is the loop's body entered. The test expression is tested
again after one cycle. This step is repeated until the test expression
returns False.
• In Python, indentation is used to determine the body of the while loop.

64
Python Programming

• The statements within the while beginning with indentation and finish
with the first unindented line

.
Flowchart

Examples:
1. program to find the sum of n numbers:
2. program to find the factorial of a number
3. program to find the sum of digits of a number:
4. Program to Reverse the given number:
5. Program to find a number is Armstrong number or not
6. Program to check if the number is palindrome or not
Sum of n numbers:
n=eval(input("enter n"))
i=1
sum=0
while(i<=n):
sum=sum+i
i=i+1
print(sum)

output
enter n
10

65
Python Programming

55
Factorial of numbers:
For loop:
For in range:
• The while loop statement in Python is used to execute a collection of
statements continuously as long as a particular condition is true.
• The test expression is tested first in a while loop. The loop's body is
entered only if the test expression is True. After one cycle, the test
expression is tested again. This procedure is continued until the test
expression yields False.
• Python uses indentation to determine the body of the while loop.
• The while statements begin with indentation and end with the first
unindented line.
Syntax

Flowchart:

For in sequence
Python's for loop is used to iterate through a sequence (list, tuple, string).
The process of iterating across a sequence is known as traversal. The loop
is repeated until we reach the last element in the sequence.
Indentation separates the for loop's body from the remainder of the code.

66
Python Programming

The sequence can be a list, strings, or tuples

Examples:
1. print nos divisible by 5, not by 10:
2. Program to print the Fibonacci series.
3. Program to find factors of a given number
4. check whether the given number is the perfect number or not
5. check whether the no is prime or not
6. Print first n prime numbers
7. Program to print prime numbers in the range
Loop Control Structures
BREAK
Break statements can be used to change the flow of a loop.

It ends the current loop and performs the last statement outside the loop.

If the loop contains an otherwise statement, it will be ended, and the loop will be exited fully. Syntax:
Break

Flowchart

67
Python Programming

example
for i in "welcome":
if(i=="c"):
break
print(i)
Output
w
e
l
CONTINUE
It terminates the current iteration and transfers the control to the next
iteration in the loop.
Syntax:
Continue

68
Python Programming

Flowchart

Example:
for i in "welcome":
if(i=="c"):
continue
print(i)
Output
w
e
l
o
m
e

PASS
It is used when a statement is required syntactically, but you don’t
want any code to execute.
It is a null statement; nothing happens when it is executed.
Syntax:
pass
break
Example
for i in "welcome":
if (i == "c"):

69
Python Programming

pass
print(i)
Output
w
e
l
c
o
m
e

What is the difference between break and continue

else statement in loops:


else in for loop:
If the else statement is used in the loop, the else statement is executed
when the loop has reached the limit.
The statements inside for loop and statements inside the else will also
execute.
example
for i in range(1,6):
print(i)
else:
print("the number greater than 6")
output
1
2
3

70
Python Programming

4
5 the number greater than 6
else in while loop:
If a statement is used within the while loop, the else part will be
executed when the condition becomes false.
The statements inside for loop and statements inside the else will also
execute.
Program
i=1
while(i<=5):
print(i)
i=i+1
else:
print("the number greater than 5")
output
1
2
3
4
5
A number greater than 5
3.4 FRUITFUL FUNCTION

Fruitful function
Void function
Return values
Parameters
Local and global scope
Function composition
Recursion

Fruitful function:

A function that returns a value is called a fruitful function.


Example:
Root=sqrt(25)

Example:
def add():
a=10

71
Python Programming

b=20
c=a+b
return c
c=add()
print(c)

Void Function

A function that performs an action but doesn’t return any value.


Example:
print("Hello")
Example:
def add():
a=10
b=20
c=a+b
print(c)
add()

Return values:

Return keywords are used to return the values from the function.

Example:
return a – return 1 variable
return a,b– return 2 variables
return a,b,c– return 3 variables
return a+b– return expression
return 8– return value

PARAMETERS / ARGUMENTS:

Parameters are variables that are utilized in the function definition.


Functions take parameters as inputs. The parameter receives the function
call's input.
It is possible to define more than one parameter in the function definition.
Types of parameters/Arguments:
1. Required/Positional parameters
2. Keyword parameters
3. Default parameters

72
Python Programming

4. Variable-length parameters

Required/ Positional Parameter:


The number of parameters in the function definition should match exactly
with several arguments in the function call.
Example
def student( name, roll ):
print(name,roll)
student(" George ",98)
Output:
George 98
Keyword parameter:
When we call a function with some values, they get assigned to the
parameter according to their position. When we call functions in the
keyword parameter, the order of the arguments can be changed.
Example
def student(name,roll,mark):
print(name,roll,mark)
student(90,102, " bala")
Output:
90 102 bala
Default parameter:

Python allows function parameters to have default values; if the function is


called without the argument, the argument gets its default value in the
function definition.
Example
def student( name, age=17):
print (name, age)
student( " Kumar "):
student( " Ajay "):
Output:
Kumar 17
Ajay 17

Variable length parameter

- Sometimes, we do not know in advance the number of arguments


that will be passed into a function.

73
Python Programming

- Python allows us to handle this situation through function calls with


several arguments.

- In the function definition, we use an asterisk (*) before the parameter


name to denote this variable length of the parameter.

Example
def student( name,*mark):
print(name,mark)
student (" bala ",102,90)

Output:
bala ( 102 ,90)

Local and Global Scope


Global Scope
- The scope of a variable refers to the places you can see or access a
variable.
- A variable with global scope can be used anywhere in the program.
- It can be created by defining a variable outside the function.

Local Scope, A variable with a local scope can be used only within the
function.

74
Python Programming

Function Composition:

- Function Composition is the ability to call one function from within


another function
- It is a way of combining functions such that the result of each
function is passed as the argument of the next function.
- In other words, the output of one function is given as the input of
another function is known as function composition.

Example:
math.sqrt(math.log(10))
def add(a,b):
c=a+b
return c
def mul(c,d):
e=c*d
return e
c=add(10,20)
e=mul(c,30)
print(e)

Output:
900
Recursion

A function calls itself until it reaches the base value - the stop point of the
function call. Example: factorial of a given number using recursion

Factorial of n
def fact(n):
if(n==1):
return 1
else:
return n*fact(n-1)
n=eval(input("enter no. to find fact:"))
fact=fact(n)
print("Fact is",fact)

Output
enter no. to find fact:5

75
Python Programming

Fact is 120

Explanation

Examples:
1. the sum of n numbers using recursion
2. exponential of a number using recursion

Sum of n numbers
def sum(n):
if(n==1):
return 1
else:
return n+sum(n-1)
n=eval(input("enter no. To find sum:"))
sum=sum(n)
print("Fact is",sum)

Output
enter no. to find sum:10
Fact is 55

76
Python Programming

CHAPTER 4
STRINGS
4.1 PYTHON STRING
So far, we've covered integers as the most common data types in Python.
This course portion will cover Python's most common data type: strings.
A Python string is a collection of characters enclosed by single, double, or
triple quotes. The computer does not understand the characters; instead,
it saves the modified character as a combination of 0's and 1's internally.
Each character is encoded in either ASCII or Unicode. As a result, Python
strings may alternatively be referred to as a collection of Unicode
characters.
Strings may be created in Python by surrounding the character or
sequence of characters in quotes. To create the string, Python allows us to
use single quotes, double quotes, or triple quotes.
Consider the following Python string-creation example.
Syntax:
str = "Hi Python !"
Here, if we check the type of the variable str using a Python script
print(type(str)), then it will print a string (str).
In Python, strings are treated as a sequence of characters, which means
that Python doesn't support the character data type; instead, a single
character written as 'p' is treated as a string of length 1.
Creating String in Python
We can create a string by enclosing the characters in single quotes or
double- quotes. Python also provides triple quotes to represent the string,
but it is generally used for multiline strings or docstrings.
#Using single quotes
str1='Hello Python'
print(str1)
#Using double quotes
str2 = "Hello Python"
print(str2)

#Using triple quotes


str3 = '''''Triple quotes are generally used for
represent the multiline or
docstring'''
print(str3)
Output:
Hello Python
77
Python Programming

Hello Python
Triple quotes are generally used for
represent the multiline or
docstring
4.2 STRINGS INDEXING AND SPLITTING
Like other languages, the indexing of the Python strings starts from 0. For
example, The string "HELLO" is indexed as given in the below figure.

Consider the following example:


str = "HELLO"
print(str[0])
print(str[1])
print(str[2])
print(str[3])
print(str[4])
# It returns the IndexError because the 6th index doesn't exist
print(str[6])
Output:
H
E
L
L
O
IndexError: string index out of range
As shown in Python, the slice operator [] is used to access the individual
characters of the string. However, we can use the : (colon) operator in
Python to access the substring from the given string. Consider the
following example.

78
Python Programming

Here, we must notice that the upper range given in the slice operator is
always exclusive, i.e., if str = 'HELLO' is given, then str[1:3] will always
include str[1] = 'E,' str[2] = 'L' and nothing else.
Consider the following example:
# Given String
str = "ITKINGS"
# Start Oth index to end
print(str[0:])
# Starts 1th index to 4th index
print(str[1:5])
# Starts 2nd index to 3rd index
print(str[2:4])
# Starts 0th to 2nd index
print(str[:3])
#Starts 4th to 6th index
print(str[4:7])
Output:
ITKINGS
AVAT
VA
JAVA
TOP
We can do the negative slicing in the string; it starts from the rightmost
character, which is indicated as -1. The second rightmost index indicates -
2, and so on. Consider the following image.

79
Python Programming

Consider the following example


str = 'ITKINGS'
print(str[-1])
print(str[-3])
print(str[-2:])
print(str[-4:-1])
print(str[-7:-2])
# Reversing the given string
print(str[::-1])
print(str[-12])
Output:
T
I
NT
OIN
APOI
TNIOPTAVAJ
IndexError: string index out of range
4.3 REASSIGNING STRINGS
Updating the string content is as simple as assigning it to a new string.
The string object does not enable item assignment, which means that a
string may only be replaced with a new string since its content cannot be
altered partially. In Python, strings are immutable.
Consider the following example.
Example 1
str = "HELLO"
str[0] = "h"
print(str)
Output:
Traceback (most recent call last):
80
Python Programming

File "12.py", line 2, in <module>


str[0] = "h";
TypeError: 'str' object does not support item assignment
However, in example 1, the string str can be assigned completely to new
content as specified in the following example.
Example 2
str = "HELLO"
print(str)
str = "hello"
print(str)
Output:
HELLO
hello
Deleting the String
Strings, as we all know, are immutable. The characters in the string
cannot be deleted or removed. However, we may use the del keyword to
remove the entire string.
str = "ITKINGS"
del str[1]
Output:
TypeError: 'str' object doesn't support item deletion
Now we are deleting the entire string.
str1 = "ITKINGS"
del str1
print(str1)
Output:
NameError: name 'str1' is not defined
String Operators

Operat Description
or

+ It is known as the concatenation operator used to


join the strings given on either side of the
operator.

* It is known as the repetition operator. It


concatenates multiple copies of the same string.

81
Python Programming

[] It is known as the slice operator. It is used to


access the sub-strings of a particular string.

[:] It is known as the range slice operator. It is used


to access the characters from the specified range.

in It is known as a membership operator. It returns


if a particular sub-string is present in the
specified string.

not in It is also a membership operator and does the


exact reverse of in. It returns true if a particular
substring is not present in the specified string.

r/R It is used to specify the raw string. Raw strings


are used when we need to print the actual
meaning of escape characters, such as
"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 uses 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.

Example
Consider the following example to understand the real use of Python
operators.
str = "Hello"
str1 = " world"
print(str*3) # prints HelloHelloHello
print(str+str1)# prints Hello world
print(str[4]) # prints o
print(str[2:4]); # prints ll
print('w' in str) # prints false as w is not present in str
print('wo' not in str1) # prints false as who is present in str1.
print(r'C://python37') # prints C://python37 as it is written
print("The string str : %s"%(str)) # prints The string str : Hello

82
Python Programming

Output:
HelloHelloHello
Hello world
o
ll
False
False
C://python37
The string str: Hello
4.4 PYTHON STRING FORMATTING
Escape Sequence
Assume we need to write the text like this - They said, "Hello, what's going
on?" The provided statement may be written in single or double quotes,
but it will produce the SyntaxError since it contains both single and
double quotes.
Example
Consider the following example to understand the real use of Python
operators.
1. Str = "They said, "Hello, what's going on? "
2. print(str)
Output:
SyntaxError: invalid syntax
We can use triple quotes to accomplish this problem, but Python provides
the escape sequence.
The backslash(/) symbol denotes the escape sequence. A special character
can follow the backslash, and it is interpreted differently. The single quotes
inside the string must be escaped. We can apply the same as in the double
quotes.
Example -
# using triple quotes
print('''''They said, "What's there?"''')

# escaping single quotes


print('They said, "What\'s going on?"')

# escaping double quotes


print("They said, \"What's going on?\"")
Output:
They said, "What's there?"
They said, "What's going on?"

83
Python Programming

They said, "What's going on?"


The list of escape sequences is given below:

S Escape Descripti Example


r. Sequen on
ce

1. \newline It ignores print("Python1 \


the new Python2 \
line. Python3")
Output:
Python1 Python2 Python3

2. \\ Backslash print("\\")
Output:
\

3. \' Single print('\'')


Quotes Output:
'

4. \\'' Double print("\"")


Quotes Output:
"

5. \a ASCII Bell print("\a")

6. \b ASCII print("Hello \b World")


Backspace( Output:
BS) Hello World

7. \f ASCII print("Hello \f World!")


Formfeed Hello World!

8. \n ASCII print("Hello \n World!")


Linefeed Output:
Hello
World!

84
Python Programming

1. \r ASCII print("Hello \r World!")


Carriage Output:
Return(CR) World!

10. \t ASCII print("Hello \t World!")


Horizontal Output:
Tab Hello World!

11. \v ASCII print("Hello \World!")


Vertical Output:
Tab Hello
World!

12. \ooo A character print("\110\145\154\154\


with an 157")
octal value Output:
Hello

13 \xHH The print("\x48\x65\x6c\x6c\x


character 6f")
with a hex Output:
value. Hello

Here is a simple example of an escape sequence.


print("C:\\Users\\GURU SHARMA\\Python32\\Lib")
print("This is the \n multiline quotes")
print("This is \x48\x45\x58 representation")
Output:
C:\Users\GURU SHARMA\Python32\Lib
This is the
multiline quotes
This is HEX representation
We can ignore the escape sequence from the given string by using the raw
string. We can write r or R in front of the string. Consider the following
example.
print(r"C:\\Users\\GURU SHARMA\\Python32")
Output:
C:\\Users\\GURU SHARMA\\Python32

85
Python Programming

The format() method


The format() method is the most flexible and useful for formatting strings.
The curly braces {} are used as the placeholder in the string and replaced
by the format() method argument. Let's have a look at the given an
example:
# Using Curly braces
print("{} and {} both are the best friend".format("Guru","Abhishek"))

#Positional Argument
print("{1} and {0} best players ".format("Virat","Rohit"))

#Keyword Argument
print("{a},{b},{c}".format(a = "James", b = "Peter", c = "Ricky"))
Output:
Guru and Abhishek are both the best friend
Rohit and Virat are the best players
James, Peter, Ricky
Python String Formatting Using % Operator
Python supports the format specifiers found in C's print statement. In
Python, format specifiers are processed in the same manner as in C.
Python, on the other hand, has an extra operator percent that serves as a
bridge between format specifiers and their values. In other words, it
connects the format specifiers to the values.
Consider the following scenario.
Integer = 10;
Float = 1.290
String = "Guru"
print("Hi I am Integer ... My value is %d\nHi I am float ... My value is %f\n
Hi I am string ... My value is %s"%(Integer,Float,String))
Output:
Hi, I am Integer ... My value is 10
Hi, I am float ... My value is 1.290000
Hi, I am string ... My value is Guru
4.5 PYTHON STRING FUNCTIONS
Python provides various in-built functions that are used for string
handling. Many String fun

Method Description

86
Python Programming

capitalize() It capitalizes on the first


character of the String. This
function is deprecated in
python3

casefold() It returns a version of s suitable


for case-less comparisons.

center(width ,fillchar) It returns a space-padded


string with the original string
centered with an equal number
of left and right spaces.

count(string,begin,end) It counts the number of


occurrences of a substring in a
String between the beginning
and end index.

decode(encoding = 'UTF8', Decodes the string using a


errors = 'strict') codec registered for encoding.

encode() Encode S using the codec


registered for encoding. The
default encoding is 'utf-8'.

endswith(suffix It returns a Boolean value if the


,begin=0,end=len(string)) string terminates with a given
suffix between the beginning
and the end.

expandtabs(tabsize = 8) It defines tabs in the string to


multiple spaces. The default
space value is 8.

find(substring ,beginIndex, It returns the index value of the


endIndex) string where the substring is
found between begin index and
the end index.

87
Python Programming

format(value) It returns a formatted version of


S using the passed value.

index(subsring, It throws an exception if the


beginIndex, endIndex) string is not found. It works the
same as the find() method.

isalnum() It returns true if the characters


in the string are alphanumeric,
i.e., alphabets or numbers, and
there is at least 1 character.
Otherwise, it returns false.

isalpha() It returns true if all the


characters are alphabetical and
there is at least one character;
otherwise False.

isdecimal() It returns true if all the


characters of the string are
decimals.

isdigit() It returns true if all the


characters are digits and there
is at least one character;
otherwise False.

isidentifier() It returns true if the string is


the valid identifier.

islower() It returns true if the characters


of a string are in lower case;
otherwise false.

isnumeric() It returns true if the string


contains only numeric
characters.

88
Python Programming

isprintable() It returns true if all the


characters of s are printable or
s is empty; false otherwise.

isupper() It returns false if characters of


a string are in Upper case;
otherwise, False.

isspace() It returns true if the characters


of a string are white-space;
otherwise false.

istitle() It returns true if the string is


titled properly and false
otherwise. A title string is one
in which the first character is
upper-case, whereas the other
characters are lower-case.

isupper() It returns true if all the


characters of the string(if exists)
are true; otherwise, it returns
false.

join(seq) It merges the strings


representation of the given
sequence.

Len(string) It returns the length of a string.

ljust(width[,fillchar]) It returns the space-padded


strings with the original string
left justified to the given width.

lower() It converts all the characters of


a string to Lower case.

89
Python Programming

lstrip() It removes all leading


whitespaces of a string and can
also remove a particular
character from leading.

partition() It searches for the separator


sep in S and returns the part
before it, the separator itself,
and the part after it. If the
separator is not found, return S
and two empty strings.

maketrans() It returns a translation table to


be used in the translate
function.

replace(old,new[,count]) It replaces the old sequence of


characters with the new
sequence. The max characters
are replaced if the max is given.

rfind(str,beg=0,end=len(str) It is similar to finding but


) traverses the string in the
backward direction.

rindex(str,beg=0,end=len(st It is the same as the index but


r)) traverses the string backward.

rjust(width,[,fillchar]) Returns a space-padded string


having the original string right
justified to the number of
characters specified.

rstrip() It removes all trailing


whitespace of a string and can
also remove a particular
character from the trailing.

90
Python Programming

rsplit(sep=None, maxsplit = It is the same as split(), but it


-1) processes the string from the
backward direction. It returns
the list of words in the string. If
Separator is not specified, then
the string splits according to
the white space.

split(str,num=string.count( Splits the string according to


str)) the delimiter str. The string
splits according to the space if
the delimiter is not provided. It
returns the list of substring
concatenated with the
delimiter.

splitlines(num=string.coun It returns the list of strings at


t('\n')) each line with the new line
removed.

startswith(str,beg=0,end=le It returns a Boolean value if the


n(str)) string starts with a given str
between the beginning and the
end.

strip([chars]) It performs strip() and strip() on


the string.

swap case() It inverts the case of all


characters in a string.

title() It is used to convert the string


into the title case, i.e., The
string Meerut will be converted
to Meerut.

91
Python Programming

translate(table,deletechars It translates the string


= '') according to the translation
table passed in the function.

upper() It converts all the characters of


a string to Upper Case.

zfill(width) Returns original string left


padded with zeros to a total of
width characters; intended for
numbers, fill() retains any sign
given (less one zero).

rpartition()

92
Python Programming

CHAPTER 5
LISTS, TUPLES
5.1 PYTHON LIST
In Python, a list is used to store the sequence of various types of data.
Python lists are changeable, meaning they can change their elements after
they are created. However, Python has six data types that may store
sequences, but the list is the most popular and trustworthy.
A list is a collection of values or items of various types. The items in the list
are separated by commas (,) and contained by square brackets [].
A list can be defined below
L1 = ["Guru," 102, "USA"]
L2 = [1, 2, 3, 4, 5, 6]
if we try to print the type of L1, L2, and L3 using the type() function, it will
become a list.
print(type(L1))
print(type(L2))
Output:
<class 'list'>
<class 'list'>
Characteristics of Lists
The list has the following characteristics:
o The lists are ordered.
o The element of the list can access by index.
o The lists are the mutable type.
o The lists are mutable types.
o A list can store the number of various elements.
Let's check the first statement that lists are ordered.
a = [1,2, "Peter",4.50, "Ricky",5,6]
b = [1,2,5,"Peter",4.50,"Ricky",6]
a ==b
Output:
False
Both lists included identical elements, but the second list shifted the index
position of the fifth element, which violated the order of the lists. When the
two lists are compared, the result is false.
Lists maintain the order of the elements for the duration of their element.
That is why it is an ordered collection of objects.
a = [1, 2, "Peter", 4.50,"Ricky",5, 6]
b = [1, 2,"Peter", 4.50,"Ricky",5, 6]
a == b

93
Python Programming

Output:
True
Let's have a look at the list example in detail.
emp = ["Guru," 102, "USA"]
Dep1 = ["CS",10]
Dep2 = ["IT",11]
HOD_CS = [10," Mr. Holding"]
HOD_IT = [11, "Mr. Bewon"]
print("printing employee data...")
print("Name : %s, ID: %d, Country: %s"%(emp[0],emp[1],emp[2]))
print("printing departments...")
print("Department 1:\nName: %s, ID: %d\nDepartment 2:\nName: %s, ID
: %s"%(Dep1[0],Dep2[1],Dep2[0],Dep2[1]))
print("HOD Details ....")
print("CS HOD Name: %s, Id: %d"%(HOD_CS[1],HOD_CS[0]))
print("IT HOD Name: %s, Id: %d"%(HOD_IT[1],HOD_IT[0]))
print(type(emp),type(Dep1),type(Dep2),type(HOD_CS),type(HOD_IT))
Output:
Printing employee data...
Name: Guru, ID: 102, Country: USA
printing departments...
Department 1:
Name: CS, ID: 11
Department 2:
Name: IT, ID: 11
HOD Details...
CS HOD Name: Mr. Holding, Id: 10
IT HOD Name: Mr. Bewon, Id: 11
<class 'list'> <class 'list'> <class 'list'> <class 'list'> <class 'list'>
We created employee and department lists in the preceding example and
printed the related information. Understand the above code to have a
better understanding of the list idea.
List indexing and splitting
Indexing is processed in the same way that strings are. The slice operator
[] can access the list's elements.
The index starts from 0 to length - 1. The 0th index stores the initial
element of the list, the 1st index stores the second element of the list, and
so on.

94
Python Programming

We can get the sub-list of the list using the following syntax.
1. list_varible(start:stop:step)
o The start denotes the starting index position of the list.
o The stop denotes the last index position of the list.
o The step is used to skip the nth element within a start: stop
Consider the following example:
list = [1,2,3,4,5,6,7]
print(list[0])
print(list[1])
print(list[2])
print(list[3])
# Slicing the elements
print(list[0:6])
# By default, the index value is 0,
so it starts from the 0th element and goes for index -1.
print(list[:])
print(list[2:5])
print(list[1:6:2])
Output:
1
2
3
4
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 7]
[3, 4, 5]
[2, 4, 6]

95
Python Programming

Unlike other languages, Python also provides the flexibility to use negative
indexing. The negative indices are counted from the right. The list's last
element (rightmost) has the index -1; its adjacent left element is present at
the index -2, and so on, until the left-most elements are encountered.

Let's look at the following example: We will use negative indexing to access
the list elements.
list = [1,2,3,4,5]
print(list[-1])
print(list[-3:])
print(list[:-1])
print(list[-3:-1])
Output:
5
[3, 4, 5]
[1, 2, 3, 4]
[3, 4]
As previously mentioned, we may obtain an element by utilizing negative
indexing. The first print statement in the above code returned the list's
rightmost element. The second print statement returned the sub-list, and
so on.
Updating list values
List values may be changed using the slice and assignment operators.
Lists are the most versatile data structures in Python because they are
mutable.
Python additionally has to append() and insert() methods for adding values
to a list.
Consider the following example to update the list's values.
list = [1, 2, 3, 4, 5, 6]
print(list)
# It will assign value to value to the second index
list[2] = 10
print(list)
# Adding multiple-element
list[1:3] = [89, 78]
print(list)
# It will add value at the end of the list
96
Python Programming

list[-1] = 25
print(list)
Output:
[1, 2, 3, 4, 5, 6]
[1, 2, 10, 4, 5, 6]
[1, 89, 78, 4, 5, 6]
[1, 89, 78, 4, 5, 25]
The list elements can also be deleted by using the del keyword. Python
also provides us with the remove() method if we do not know which
element will be deleted from the list.
Consider the following example to delete the list elements.
list = [1, 2, 3, 4, 5, 6]
print(list)
# It will assign value to the value second index
list[2] = 10
print(list)
# Adding multiple elements
list[1:3] = [89, 78]
print(list)
# It will add value at the end of the list
list[-1] = 25
print(list)
Output:
[1, 2, 3, 4, 5, 6]
[1, 2, 10, 4, 5, 6]
[1, 89, 78, 4, 5, 6]
[1, 89, 78, 4, 5, 25]
Python List Operations
The concatenation (+) and repetition (*) operators function as they did with
strings.
Let's examine how the list responds to different operators.
Consider a Lists l1 = [1, 2, 3, 4] and l2 = [5, 6, 7, 8] to operate.

Operator Description Exampl


e

Repetition The repetition operator enables L1*2 = [1,


the list elements to be repeated 2, 3, 4, 1,
multiple times. 2, 3, 4]

97
Python Programming

Concatenatio It concatenates the list l1+l2 =


n mentioned on either side of the [1, 2, 3,
operator. 4, 5, 6, 7,
8]

Membership It returns true if a particular item print(2 in


exists in a separate list; l1) prints
otherwise false. True.

Iteration The for loop is used to iterate for i in


over the list elements. l1:
print(i)
Output
1
2
3
4

Length It is used to get the length of the len(l1) =


list 4

Iterating a List
A list can be iterated by using a for-in loop. A simple list containing four
strings can be iterated as follows.
list=["Guru","Guru","James","Jonathan"]
for j in the list:
# The i variable will iterate over the List elements and
contain each element in each iteration.
print(i)
Output:
Guru
Guru
James
Jonathan
Adding elements to the list
The append() function in Python adds an element to a list. The append()
function, on the other hand, can only add value to the list's end.
Consider the following example: we take the list of items from the user and
print them on the console.
#Declaring the empty list
98
Python Programming

l=[]
The user will enter #Number of elements
n = int(input("Enter the number of elements in the list:"))
# for loop to take the input
for i in range(0,n):
# The input is taken from the user and added to the list as the item
l.append(input("Enter the item:"))
print("printing the list items..")
# traversal loop to print the list items
for i in l:
print(i, end = " ")
Output:
Enter the number of elements in the list:5
Enter the item:25
Enter the item:46
Enter the item:12
Enter the item:75
Enter the item:42
printing the list of items
25 46 12 75 42
Removing elements from the list
The remove() function in Python removes an element from a list. To
understand this concept, consider the following example.
Example -
list = [0,1,2,3,4]
print("printing original list: ")
for i in list:
print(i,end=" ")
list.remove(2)
print("\nprinting the list after the removal of the first element...")
for i in list:
print(i,end=" ")
Output:
Printing original list:
01234
printing the list after the removal of the first element...
0134
Python List Built-in functions
Python provides the following built-in functions, which can be used with
lists.

99
Python Programming

S Functio Description Example


N n

1 CMP(list1 It compares This method is not used


, list2) the elements in Python 3 and the
of both lists. above versions.

2 len(list) It is used to L1 = [1,2,3,4,5,6,7,8]


calculate the print(line(L1))
length of the 8
list.

3 max(list) It returns the L1 = [12,34,26,48,72]


maximum print(max(L1))
element of the 72
list.

4 min(list) It returns the L1 = [12,34,26,48,72]


minimum print(min(L1))
element of the 12
list.

5 list(seq) It converts any str = "Gurus on"


sequence to s = list(str)
the list. print(type(s))
<class list>

Let's have a look at the few list examples.


Example: 1- Write the program to remove the duplicate element of the list.
list1=[1,2,2,3,55,98,65,65,13,29]
# Declare an empty list that will store unique values
list2=[]
for i in list1:
if i not in list2:
list2.append(i)
print (list2)
Output:
[1, 2, 3, 55, 98, 65, 13, 29]
Example 2- Write a program to find the sum of the element in the list.
100
Python Programming

list1 = [3,4,5,9,10,12,24]
sum = 0
for i in list1:
sum = sum+i
print("The sum is:",sum)
Output:
The sum is: 67
Example: 3- Write the program to find lists of at least one common
element.
list1 = [1,2,3,4,5,6]
list2 = [7,8,9,2,10]
for x in list1:
for y in list2:
if x == y:
print("The common element is:",x)
Output:
The common element is: 2
5.2 PYTHON TUPLE
Python Tuple is a data structure used to store a sequence of immutable
Python objects. The tuple is similar to lists in that the value of the items
stored in the list may be changed, but the tuple is immutable, and the
value of the items stored in the tuple cannot be changed.
Creating a tuple
A tuple is a collection of comma-separated (,) values written using tiny ()
brackets. The parenthesis is optional, although they are excellent practice.
A tuple is defined as follows.
T1 = (101,"Peter",22)
T2 = ("Apple","Banana","Orange")
T3 = 10,20,30,40,50
print(type(T1))
print(type(T2))
print(type(T3))
Output:
<class 'tuple'>
<class 'tuple'>
<class 'tuple'>
An empty tuple can be created as follows.
T4 = ()
Creating a tuple with a single element is slightly different. We need to put
a comma after the element to declare the tuple.

101
Python Programming

tup1 = ("JavaTpoint")
print(type(tup1))
#Creating a tuple with a single element
tup2 = ("JavaTpoint,")
print(type(tup2))
Output:
<class 'str'>
<class 'tuple'>
A tuple is indexed in the same way as the lists. The items in the tuple can
be accessed using their specific index value.
Consider the following example of a tuple:
Example - 1
tuple1=(10,20,30,40,50,60)
print(tuple1)
count=0
for i in tuple1:
print("tuple1[%d] = %d"%(count, i))
count = count+1
Output:
(10, 20, 30, 40, 50, 60)
tuple1[0] = 10
tuple1[1] = 20
tuple1[2] = 30
tuple1[3] = 40
tuple1[4] = 50
tuple1[5] = 60
Example - 2
tuple1 = tuple(input("Enter the tuple elements ..."))
print(tuple1)
count = 0
for i in tuple1:
print("tuple1[%d] = %s"%(count, i))
count = count+1
Output:
Enter the tuple elements ...123456
('1', '2', '3', '4', '5', '6')
tuple1[0] = 1
tuple1[1] = 2
tuple1[2] = 3
tuple1[3] = 4

102
Python Programming

tuple1[4] = 5
tuple1[5] = 6
A tuple is indexed similarly to a list. The tuple's items can be accessed by
using their unique index value.
In this portion of the lesson, we will look at all of these characteristics of
the tuple.
Tuple indexing and slicing
Tuple indexing and slicing are comparable to lists. The indexing in the
tuple starts at 0 and continues to length(tuple) - 1.
The index [] operator may access the items in the tuple. We may also use
the colon operator in Python to retrieve multiple items in a tuple.
Consider the picture below to understand indexing and slicing better.

Consider the following example:


tup = (1,2,3,4,5,6,7)
print(tup[0])
print(tup[1])
print(tup[2])
# It will give the IndexError
print(tup[8])
Output:
1
2
3
tuple index out of range
In the above code, the tuple has 7 elements which denote 0 to 6. We tried
to access an element outside the tuple that raised an IndexError.
tuple = (1,2,3,4,5,6,7)
103
Python Programming

#element 1 to end
print(tuple[1:])
#element 0 to 3 element
print(tuple[:4])
#element 1 to 4 element
print(tuple[1:5])
# element 0 to 6 and take step 2
print(tuple[0:6:2])
Output:
(2, 3, 4, 5, 6, 7)
(1, 2, 3, 4)
(1, 2, 3, 4)
(1, 3, 5)
Negative Indexing
Negative indexing can also be used to reach the tuple element. The index of
-1 signifies the rightmost element, -2 is the second last item, and so on.
The items are traversed from left to right using negative indexing. Consider
the following scenario:
tuple1 = (1, 2, 3, 4, 5)
print(tuple1[-1])
print(tuple1[-4])
print(tuple1[-3:-1])
print(tuple1[:-1])
print(tuple1[-2:])
Output:
5
2
(3, 4)
(1, 2, 3, 4)
(4, 5)
Deleting Tuple
Tuple items, unlike lists, cannot be removed with the del keyword since
tuples are immutable. We may use the del keyword with the tuple name to
remove a whole tuple.
Consider the following example.
tuple1 = (1, 2, 3, 4, 5, 6)
print(tuple1)
del tuple1[0]
print(tuple1)
del tuple1

104
Python Programming

print(tuple1)
Output:
(1, 2, 3, 4, 5, 6)
Traceback (most recent call last):
File "tuple.py", line 4, in <module>
print(tuple1)
NameError: name 'tuple1' is not defined
Basic Tuple operations
Concatenation (+), repetition (*), and membership (in) work in the same
way as they do with lists. For further information, see the table below.
Let's say Tuple t = (1, 2, 3, 4, 5) and Tuple t1 = (6, 7, 8, 9) are declared.

Operator Description Example

Repetition The repetition operator T1*2 = (1, 2, 3,


enables the tuple elements 4, 5, 1, 2, 3, 4,
to be repeated multiple 5)
times.

Concatenat It concatenates the tuple T1+T2 = (1, 2,


ion mentioned on either side of 3, 4, 5, 6, 7, 8,
the operator. 9)

Membershi It returns true if a particular print (2 in T1)


p item exists in the tuple; prints True.
otherwise, false

Iteration The for loop is used to for i in T1:


iterate over the tuple print(i)
elements. Output
1
2
3
4
5

Length It is used to get the length of len(T1) = 5


the tuple.

105
Python Programming

Python Tuple inbuilt functions

S Functi Description
N on

1 CMP(tupl It compares two tuples and returns true if


e1, tuple1 is greater than tuple2; otherwise
tuple2) false.

2 len(tuple) It calculates the length of the tuple.

3 max(tupl It returns the maximum element of the


e) tuple

4 min(tuple It returns the minimum element of the


) tuple.

5 tuple(seq It converts the specified sequence to the


) tuple.

Where do you use tuples?


Using a tuple instead of a list is used in the following scenario.
1. Using a tuple instead of a list gives us a clear idea that tuple data is
constant and must not be changed.
2. Tuple can simulate a dictionary without keys. Consider the following
nested structure, which can be used as a dictionary.
1. [(101, "Guru", 22), (102, "Mike", 28), (103, "Dustin", 30)]
List vs. Tuple

S List Tuple
N

1 The literal syntax of the The literal syntax of the


list is shown by the []. tuple is shown by the ().

2 The List is mutable. The tuple is immutable.

106
Python Programming

3 The List has a variable The tuple has a fixed length.


length.

4 The list provides more The tuple provides less


functionality than a functionality than the list.
tuple.

5 The list is used in the The tuple is used when we


scenario where we need need to store the read-only
to store the simple collections, i.e., the value of
collections with no the items cannot be
constraints where the changed. It can be used as
value of the items can the key inside the
be changed. dictionary.

6 The lists are less The tuples are more memory


memory efficient than a efficient because of their
tuple. immutability.

107
Python Programming

CHAPTER 6
PYTHON DICTIONARY
6.1 INTRODUCTION
Python Dictionary is used to store data in key-value pair format. In
Python, the dictionary is a data type that may imitate a real-world data
arrangement in which a specific value exists for a given key. It refers to the
changeable data structure. The dictionary is divided into two parts: keys
and values.
O Keys must consist of a single element.
O Values can be of any type, including list, tuple, integer, etc.
In other words, a dictionary is a collection of key-value pairs, with the
value being any Python object. On the other hand, the keys are immutable
Python objects, such as Numbers, strings, or tuples.
Creating the dictionary
The dictionary may be created by enclosing several key-value pairs in curly
brackets, separating each key from its value by a colon (:). The following
syntax is used to define the dictionary.
Syntax:
Dict = {"Name": "Tom", "Age": 22}
The above dictionary Dict, The keys Name and Age are the string that is an
immutable object.
Let's see an example of creating a dictionary and print its content.
Employee = {"Name": "Guru", "Age": 29, "salary":25000,"Company":"GOOGL
E"}
print(type(Employee))
print("printing Employee data .... ")
print(Employee)
Output
<class 'dict'>
Printing Employee data...
{'Name': 'Guru', 'Age': 29, 'salary': 25000, 'Company': 'GOOGLE'}
Python provides the built-in function dict() method, which is also used to
create a dictionary. The empty curly braces {} are used to create an empty
dictionary.
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)

# Creating a Dictionary

108
Python Programming

# with dict() method


Dict = dict({1: 'Java', 2: 'T', 3:'Point'})
print("\nCreate Dictionary by using dict(): ")
print(Dict)

# Creating a Dictionary
# with each item as a Pair
Dict = dict([(1, 'Guru'), (2, 'Sharma')])
print("\nDictionary with each item as a pair: ")
print(Dict)
Output:
Empty Dictionary:
{}
Create Dictionary by using direct():
{1: 'Java', 2: 'T', 3: 'Point'}
Dictionary with each item as a pair:
{1: 'Guru,' 2: 'Sharma'}
6.2 ACCESSING THE DICTIONARY VALUES
We've discussed using indexing to access data in a list and a tuple.
However, because keys are unique in the dictionary, the values may be
accessed in the dictionary by using the keys.
The dictionary values can be accessed in the following way.
Employee = {"Name": "Guru", "Age": 29, "salary":25000,"Company":"GOOGL
E"}
print(type(Employee))
print("printing Employee data .... ")
print("Name : %s" %Employee["Name"])
print("Age : %d" %Employee["Age"])
print("Salary : %d" %Employee["Salary"])
print("Company : %s" %Employee["Company"])
Output:
<class 'dict'>
printing Employee data...
Name: Guru
Age: 29
Salary: 25000
Company: GOOGLE
Python provides an alternative to the get() method to retrieve the dictionary
values. It would provide the same result as indexing.
Inserting dictionary values

109
Python Programming

The dictionary is a mutable data type whose values may be updated using
the appropriate keys. The value can be updated with the key Dict[key] =
value. The update() method is also used to update an existing value.
Nota bene: The value is updated if the key-value pair is already in the
dictionary. Otherwise, the dictionary will be updated with the new keys.
Let's update an example of updating the dictionary values.
Example - 1:
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)

# Adding elements to the dictionary one at a time


Dict[0] = 'Peter'
Dict[2] = 'Joseph'
Dict[3] = 'Ricky'
print("\nDictionary after adding 3 elements: ")
print(Dict)

# Adding a set of values


# with a single Key
# The Emp_ages doesn't exist in the dictionary
Dict['Emp_ages'] = 20, 33, 24
print("\nDictionary after adding 3 elements: ")
print(Dict)

# Updating existing Key's Value


Dict[3] = 'JavaTpoint.'
print("\nUpdated key value: ")
print(Dict)
Output:
Empty Dictionary:
{}
Dictionary after adding 3 elements:
{0: 'Peter', 2: 'Joseph', 3: 'Ricky'}
Dictionary after adding 3 elements:
{0: 'Peter', 2: 'Joseph', 3: 'Ricky', 'Emp_ages': (20, 33, 24)}
Updated key value:
{0: 'Peter', 2: 'Joseph', 3: 'JavaTpoint', 'Emp_ages': (20, 33, 24)}
Example - 2:

110
Python Programming

Employee = {"Name": "Guru", "Age": 29, "salary":25000,"Company":"GOOGL


E"}
print(type(Employee))
print("printing Employee data .... ")
print(Employee)
print("Enter the details of the new employee....");
Employee["Name"] = input("Name: ");
Employee["Age"] = int(input("Age: "));
Employee["salary"] = int(input("Salary: "));
Employee["Company"] = input("Company:");
print("printing the new data");
print(Employee)
Output:
Empty Dictionary:
{}
Dictionary after adding 3 elements:
{0: 'Peter', 2: 'Joseph', 3: 'Ricky'}
Dictionary after adding 3 elements:
{0: 'Peter', 2: 'Joseph', 3: 'Ricky', 'Emp_ages': (20, 33, 24)}
Updated key value:
{0: 'Peter', 2: 'Joseph', 3: 'JavaTpoint', 'Emp_ages': (20, 33, 24)}
Deleting elements using the del keyword
The dictionary items can be deleted using the del keyword as given below.
Employee = {"Name": "Guru", "Age": 29, "salary":25000,"Company":"GOOGL
E"}
print(type(Employee))
print("printing Employee data .... ")
print(Employee)
print("Deleting some of the employee data")
del Employee["Name"]
del Employee["Company"]
print("printing the modified information ")
print(Employee)
print("Deleting the dictionary: Employee");
del Employee
print("Lets try to print it again ");
print(Employee)
Output:
<class 'dict'>
printing Employee data...

111
Python Programming

{'Name': 'Guru', 'Age': 29, 'salary': 25000, 'Company': 'GOOGLE'}


Deleting some of the employee data
printing the modified information
{'Age': 29, 'salary': 25000}
Deleting the dictionary: Employee
Let's try to print it again
NameError: name 'Employee' is not defined
The last print statement in the above code raised an error because we tried
to print the Employee dictionary that was already deleted.
o Using pop() method
The pop() method accepts the key as an argument and removes the
associated value. Consider the following example.
# Creating a Dictionary
Dict = {1: 'JavaTpoint,' 2: 'Peter,' 3: 'Thomas'}
# Deleting a key
# using pop() method
pop_ele = Dict.pop(3)
print(Dict)
Output:
{1: 'JavaTpoint', 2: 'Peter'}
Python also has built-in methods for removing entries from the dictionary,
pop item(), and clear(). The pop item() method removes a single element
from a dictionary, whereas the clear() method removes all entries.
Iterating Dictionary
A dictionary can be iterated using for loop, as given below.
Example 1
# for loop to print all the keys of a dictionary
1. Employee = {"Name": "Guru", "Age": 29, "salary":25000,"Company":"GOOGL
E"}
2. for x in Employee:
3. print(x)
Output:
Name
Age
salary
Company
Example 2
#for loop to print all the values of the dictionary
1. Employee = {"Name": "Guru", "Age": 29, "salary":25000,"Company":"GOOGL
E"}

112
Python Programming

2. for x in Employee:
3. print(Employee[x])
Output:
Guru
29
25000
GOOGLE
Example - 3
#for loop, print the dictionary values using the values() method.
1. Employee = {"Name": "Guru", "Age": 29, "salary":25000,"Company":"GOOGL
E"}
2. for x in Employee.values():
3. print(x)
Output:
Guru
29
25000
GOOGLE
Example 4
#for loop to print the dictionary items using the items() method.
1. Employee = {"Name": "Guru", "Age": 29, "salary":25000,"Company":"GOOGL
E"}
2. for x in Employee.items():
3. print (x)
Output:
('Name', 'Guru')
('Age', 29)
('salary', 25000)
('Company', 'GOOGLE')
Properties of Dictionary keys
1. We cannot store multiple values for the same keys in the dictionary. If
we pass more than one value for a single key, the value previously
assigned is the key's value.
Consider the following example.
Employee={"Name":
"Guru","Age":29,"Salary":25000,"Company":"GOOGLE","Name":"Guru"}
for x,y in Employee.items():
print (x,y)
Output:
Name Guru

113
Python Programming

Age 29
Salary 25000
Company GOOGLE
The key in Python cannot be any mutable object. We can use integers,
strings, or tuples as the key, but we cannot use any changeable object,
such as a list, as the key in the dictionary.
Consider the following example.
Employee={"Name":"Guru","Age":29,"salary":25000,"Company":"GOOGLE",[
100,201,301]:"DepartmentID"}
for x,y in Employee.items():
print(x,y)

Output:
Traceback (most recent call last):
File "dictionary.py", line 1, in
Employee = {"Name": "Guru", "Age": 29,
"salary":25000,"Company":"GOOGLE",[100,201,301]:"Department ID"}
TypeError: unhashable type: 'list.'
6.3 BUILT-IN DICTIONARY FUNCTIONS
The built-in python dictionary methods and the description are given
below.

S Function Description
N

1 CMP(dict1, It compares the items of both the


dict2) dictionary and returns true if the first
dictionary values are greater than the
second. Otherwise, it returns false.

2 len(dict) It is used to calculate the length of the


dictionary.

3 str(dict) It converts the dictionary into a printable


string representation.

4 type(variab It is used to print the type of the passed


le) variable.

114
Python Programming

Built-in Dictionary methods


The built-in python dictionary methods and the description are given
below.

S Method Description
N

1 dic.clear() It is used to delete all the


items from the dictionary.

2 dict.copy() It returns a shallow copy of the


dictionary.

3 dict.fromkeys(iterable Create a new dictionary from


, value = None, /) the iterable with values equal
to the value.

4 dict.get(key, default = It is used to get the value


"None") specified for the passed key.

5 dict.has_key(key) It returns true if the dictionary


contains the specified key.

6 dict.items() It returns all the key-value


pairs as a tuple.

7 dict.keys() It returns all the keys to the


dictionary.

8 dict.setdefault(key,de It is used to set the key to the


fault= "None") default value if the key is not
specified in the dictionary

9 dict.update(dict2) It updates the dictionary by


adding the key-value pair of
dict2 to this dictionary.

115
Python Programming

10 dict.values() It returns all the values of the


dictionary.

11 len()

12 popItem()

13 pop()

14 count()

15 index()

116
Python Programming

CHAPTER – 7
FILE, MODULES

7.1 PYTHON PACKAGES


Python packages let developers work with the application development
environment by offering a hierarchical directory structure in which a
package comprises sub-packages, modules, and sub-modules. The
packages are used to classify the application-level code properly.
Let's create a package in your home directory named Employees. Consider
the following steps.
1. Create a directory with the name Employees on path /home.
2. Create a python source file with ITEmployees.py on the path
/home/Employees.
ITEmployees.py
1. def Geonames():
2. List = ["Guru", "Guru", "Nick", "Martin"]
3. return List;
3. Similarly, create one more python file with the name BPOEmployees.py
and create a function getBPONames().
4. The directory Employees we created in the first step contains two
python modules. To make this directory a package, we need to include one
more file here, __init__.py, which contains the import statements of the
modules defined in this directory.
__init__.py
1. from ITEmployees import getITNames
2. from BPOEmployees import getBPONames
5. The directory Employees has become the package containing two
python modules. Here we must notice that we must create __init__.py
inside a directory to convert this directory to a package.
6. To use the modules defined inside the Employees package, we must
import this into our python source file. Let's create a simple python source
file in our home directory (/home), which uses the modules defined in this
package.
Test.py
1. import Employees
2. print(Employees.get names())
Output:
['Guru', 'Guru', 'Nick', 'Martin']
Within the packages, we can have sub-packages. We can stack the
packages to any level, depending on the application's needs.

117
Python Programming

The picture below depicts an application's library management system's


directory structure, comprising three sub-packages: Admin, Librarian, and
Student. Python modules are contained in the sub-packages.

7.2 PYTHON FILE


We previously took input from the console and wrote it back to the console
to interact with the user.
It is not always sufficient to display the data on the console. The data to be
displayed may be quite big. Only a limited amount of data may be
displayed on the console since memory is volatile, making it difficult to
restore the programmatically created data repeatedly.
File handling is critical when data must be stored permanently in a file. A
file is a named location on a disk where relevant information is stored.
After the program has terminated, we may retrieve the stored information
(non-volatile).
The file-handling implementation in the other programming language is
significantly longer or more difficult, but it is easier and shorter in Python.
In Python, files are handled in two ways: text or binary. The file can be in
text or binary format, and each file line is terminated with a special
character.
As a result, a file operation can be performed in the following order.
Open a file
Read or write - Performing operation
o Close the file
Opening a file
Python has an open() function that takes two arguments: the file name and
the access mode in which the file is accessed. The function returns a file
object that may be used for various tasks such as reading, writing, etc.
Syntax:
1. file object = open(<file-name>, <access-mode>, <buffering>)

118
Python Programming

The files can be accessed using various modes like reading, writing, or
appending. The following are the details about the access mode to open a
file.

S Acce Description
N ss
mod
e

1 r It opens the file to read-only mode. The file


pointer exists at the beginning. The file is the
default open in this mode if no access mode
is passed.

2 RB It opens the file to read-only in binary format.


The file pointer exists at the beginning of the
file.

3 r+ It opens the file to read and write both. The


file pointer exists at the beginning of the file.

4 rb+ It opens the file to read and write both in


binary format. The file pointer exists at the
beginning of the file.

5 w It opens the file to write only. It overwrites the


file if it previously existed or creates a new
one if no file exists with the same name. The
file pointer exists at the beginning of the file.

6 wb It opens the file to write only in binary


format. It overwrites the file if it exists
previously or creates a new one if no file
exists. The file pointer exists at the beginning
of the file.

119
Python Programming

7 w+ It opens the file to write and read both. It is


different from r+ in that it overwrites the
previous file if one exists, whereas r+ doesn't
overwrite the previously written file. It creates
a new file if no file exists. The file pointer
exists at the beginning of the file.

8 wb+ It opens the file to write and read both in


binary format. The file pointer exists at the
beginning of the file.

9 a It opens the file in the append mode. The file


pointer exists at the end of the previously
written file, if any exists. It creates a new file
if no file exists with the same name.

10 ab It opens the file in the append mode in binary


format. The pointer exists at the end of the
previously written file. It creates a new file in
binary format if no file exists with the same
name.

11 a+ It opens a file to append and read both. The


file pointer remains at the end of the file if a
file exists. It creates a new file if no file exists
with the same name.

12 ab+ It opens a file to append and read both in


binary format. The file pointer remains at the
end of the file.

Let's look at the simple example of opening a file named "file.txt" (stored in
the same directory) in read mode and printing its content on the console.
Example
#opens the file file.txt in reading mode
fileptr = open("file.txt","r")
if fileptr:
print("file is opened successfully")
Output:

120
Python Programming

<class '_io.TextIOWrapper'>
the file is opened successfully
In the above code, we passed the filename as the first argument and
opened the file in reading mode by specifying r as the second. The file ptr
stores the file object, and if the file is successfully opened, it will execute
the print statement.
The close() method
After we have completed all of the actions on the file, we must shut it using
the close() method in our Python script. Any unwritten information is
deleted when a file object's close() method is invoked.
We may execute any action on the file using the file system presently open
in Python; thus, it is best practice to shut the file once all operations are
opened.
The syntax for calling the close() method is shown below.
Syntax
file object. close()
Consider the following example.
# opens the file file.txt in read mode
fileptr = open("file.txt","r")
if fileptr:
print("file is opened successfully")
#closes the opened file
fileptr.close()
After closing the file, we cannot perform any operation in the file. The file
needs to be properly closed. If any exception occurs while performing some
operations in the file, the program terminates without closing the file.
We should use the following method to overcome such type of problem.
try:
fileptr = open("file.txt")
# perform file operations
finally:
fileptr.close()
The with statement
The with statement was introduced in python 2.5. The with statement is
useful in the case of manipulating the files. It is used when a pair of
statements is to be executed with a block of code in between.
The syntax to open a file using the statement is given below.
with open(<file name>, <access mode>) as <file-pointer>:
#statement suite

121
Python Programming

The advantage of using with statement is that it guarantees to close the file
regardless of how the nested block exits.
It is always suggestible to use them with the statement in the case of files
because if the break, return, or exception occurs in the nested block of
code, it automatically closes the file; we don't need to write
the close() function. It doesn't let the file corrupt.
Consider the following example.
Example
with open("file.txt",'r') as f:
content = f.read();
print(content)
Writing the file
To write some text to a file, we need to open the file using the open method
with one of the following access modes.
w: It will overwrite the file if any file exists. The file pointer is at the
beginning of the file.
a: It will append the existing file. The file pointer is at the end of the file. It
creates a new file if no file exists.
Consider the following example.
Example
# open the file.txt in append mode. Create a new file if no such file exists.
fileptr = open("file2.txt", "w")
# appending the content to the file
file
ptr.write('''''Python is the modern day language. It makes things so simple.
It is the fastest-growing programming language''')
# closing the opened the file
fileptr.close()
Output:
File2.txt
Python is the modern-day language. It makes things so simple. It is the
fastest-growing programming language.
Snapshot of the file2.txt

122
Python Programming

We have opened the file in w mode. The file1.txt file doesn't exist, it
created a new file, and we have written the content in the file using
the write() function.
Example 2
#open the file.txt in write mode.
fileptr = open("file2.txt","a")

#overwriting the content of the file


fileptr.write(" Python has an easy syntax and user-friendly interaction.")
#closing the opened file
fileptr.close()
Output:
Python is the modern-day language. It makes things so simple.
It is the fastest-growing programing language Python has an easy syntax
and user-friendly interaction.
Snapshot of the file2.txt

We can see that the content of the file is modified. We have opened the file
in a mode, and it appended the content in the existing file2.txt.
To read a file using the Python script, Python provides the read() method.
The read() method reads a string from the file. It can read the data in text
and a binary format.
The syntax of the read() method is given below.
Syntax:
1. file obj.read(<count>)
Here, the count is the number of bytes to be read from the file starting
from the beginning. If the count is not specified, it may read the file's
content until the end.
Consider the following example.
Example
#open the file.txt in reading mode. Causes error if no such file exists.
fileptr = open("file2.txt","r")
#stores all the data of the file into the variable content
content = fileptr.read(10)
# prints the type of data stored in the file
print(type(content))

123
Python Programming

#prints the content of the file


print(content)
#closes the opened file
fileptr.close()
Output:
<class 'str'>
Python is
In the above code, we have read the content of file2.txt by using
the read() function. We have passed the count value as ten, meaning it will
read the first ten characters from the file.
If we use the following line, it will print all file content.
1. content = fileptr.read()
2. print(content)
Output:
Python is the modern-day language. It makes things so simple.
It is the fastest-growing programing language Python has an easy syntax
and user-friendly interaction.
Read the file through for loop
We can read the file using for loop. Consider the following example.
#open the file.txt in reading mode. Causes an error if no such file exists.
fileptr = open("file2.txt","r");
#running a for loop
for i in fileptr:
print(i) # i contains each line of the file
Output:
Python is the modern-day language.
It makes things so simple.
Python has an easy syntax and user-friendly interaction.
Red Lines of the file
Python uses a function readline() method to read the file line by line.
The deadline() method reads the lines of the file from the beginning, i.e., if
we use the readline() method two times, then we can get the first two lines
of the file.
Consider the following example, which contains a function readline() that
reads the first line of our file "file2.txt" containing three lines. Consider
the following example.
Example 1: Reading lines using readline() function
#open the file.txt in reading mode. causes an error if no such file exists.
fileptr = open("file2.txt","r");
#stores all the data of the file into the variable content

124
Python Programming

content = fileptr.readline()
content1 = fileptr.readline()
#prints the content of the file
print(content)
print(content1)
#closes the opened file
fileptr.close()
Output:
Python is the modern-day language.
It makes things so simple.
We called the readline() function two times. That's why it read two lines
from the file.
Python also provides the readlines() method used for the reading lines. It
returns the list of the lines till the end of the file(EOF) is reached.
Example 2: Reading Lines Using the readlines() function
#open the file.txt in reading mode. Causes error if no such file exists.
fileptr = open("file2.txt","r");
#stores all the data of the file into the variable content
content = fileptr.readlines()
#prints the content of the file
print(content)
#closes the opened file
fileptr.close()
Output:
['Python is the modern-day language.\n', 'It makes things so simple.\n',
'Python has an easy syntax and user-friendly interaction.']
Creating a new file
The new file can be created using one of the following access modes with
the function open().
x: it creates a new file with the specified name. It causes an error a file
exists with the same name.
a: It creates a new file with the specified name if no such file exists. It
appends the file's content if it already exists with the specified name.
w: It creates a new file with the specified name if no such file exists. It
overwrites the existing file.
Consider the following example.
Example 1
#open the file.txt in reading mode. Causes error if no such file exists.
fileptr = open("file2.txt","x")
print(fileptr)

125
Python Programming

if fileptr:
print("File created successfully")
Output:
<_io.TextIOWrapper name='file2.txt' mode='x' encoding='cp1252'>
File created successfully
File Pointer positions
Python provides the tell() method, which prints the byte number at which
the file pointer currently exists. Consider the following example.
# open the file file2.txt in read mode
fileptr = open("file2.txt","r")
#initially, the file pointer is at 0
print("The file pointer is at byte :",file ptr.tell())
#reading the content of the file
content = fileptr.read();
#after the read operation file pointer modifies. tell() returns the location of t
he fileptr.
print("After reading, the file pointer is at:",fileptr.tell())
Output:
The filepointer is at byte : 0
After reading, the filepointer is at 117
Modifying file pointer position
In real-world applications, sometimes, we need to change the file pointer
location externally since we may need to read or write the content at
various locations.
For this purpose, Python provides us with the seek() method, which
enables us to modify the file pointer position externally.
The syntax to use the seek() method is given below.
Syntax:
1. <file-ptr>.seek(offset[, from)
The seek() method accepts two parameters:
Offset: It refers to the new position of the file pointer within the file.
from: It indicates the reference position from where the bytes are to be
moved. If it is set to 0, the beginning of the file is used as the reference
position. If it is set to 1, the current position of the file pointer is used as
the reference position. If it is set to 2, the end of the file pointer is used as
the reference position.
Consider the following example.
Example
# open the file file2.txt in read mode
fileptr = open("file2.txt","r")

126
Python Programming

#initially, the filepointer is at 0


print("The file pointer is at byte :",fileptr.tell())
#changing the file pointer location to 10.
fileptr.seek(10);
#tell() returns the location of the fileptr.
print("After reading, the file pointer is at:",fileptr.tell())
Output:
The filepointer is at byte : 0
After reading, the filepointer is at 10
Renaming the file
The Python os module enables interaction with the operating system. The
os module provides the functions involved in file processing operations like
renaming, deleting, etc. It provides the rename() method to rename the
specified file to a new name. The syntax to use the rename() method is
given below.
Syntax:
1. rename(current-name, new-name)
The first argument is the current file name, and the second is the modified
name. We can change the file name by bypassing these two arguments.
Example 1:
import os
#rename file2.txt to file3.txt
os.rename("file2.txt","file3.txt")
Output:
The above code renamed the current file2.txt to file3.txt
Removing the file
The os module provides the remove() method, which is used to remove the
specified file. The syntax to use the remove() method is given below.
remove(file-name)
Example 1
import os;
#deleting the file named file3.txt
os.remove("file3.txt")
Creating the new directory
The mkdir() method creates the directories in the current working
directory. The syntax to create the new directory is given below.
Syntax:
mkdir(directory name)
Example 1
import os

127
Python Programming

# create a new directory with the name new


os.mkdir("new")
The getcwd() method
This method returns the current working directory.
The syntax to use the getcwd() method is given below.
Syntax
os.getcwd()
Example
import os
os.getcwd()
Output:
'C:\\Users\\GURU SHARMA'
Changing the current working directory
The chdir() method changes the current working directory to a specified
one.
The syntax to use the chdir() method is given below.
Syntax
chdir("new-directory")
Example
import os
# Changing the current directory with the new directory
os.chdir("C:\\Users\\GURU SHARMA\\Documents")
#It will display the current working directory
os.getcwd()
Output:
'C:\\Users\\GURU SHARMA\\Documents'
Deleting directory
The rmdir() method is used to delete the specified directory.
The syntax to use the rmdir() method is given below.
Syntax
os.rmdir(directory name)
Example 1
import os
#removing the new directory
os.rmdir("directory_name")
It will remove the specified directory.
Writing Python output to the files
In Python, there are requirements to write the output of a Python script to
a file.

128
Python Programming

The check_call() method of the module subprocess is used to execute a


Python script and write the script's output to a file.
The following example contains two python scripts. The script file1.py
executes the script file.py and writes its output to the text file output.txt.
Example
file.py
temperatures=[10,-20,-289,100]
def c_to_f(c):
if c< -273.15:
return "That temperature doesn't make sense!"
else:
f=c*9/5+32
return f
for t in temperatures:
print(c_to_f(t))
file.py
import subprocess
With open("output.txt", "wb") as f:
subprocess.check_call(["python", "file.py"], stdout=f)
The file-related methods
The file object provides the following methods to manipulate the files on
various operating systems.

S Method Description
N

1 file.close() It closes the opened file. Once


closed, the file can't be read or
written anymore.

2 File.flush() It flushes the internal buffer.

3 File.fileno() It returns the file descriptor used


by the underlying
implementation to request I/O
from the OS.

129
Python Programming

4 File.isatty() It returns true if the file is


connected to a TTY device;
otherwise, it returns false.

5 File.next() It returns the next line from the


file.

6 File.read([size]) It reads the file for the specified


size.

7 File.readline([size]) It reads one line from the file and


places the file pointer at the
beginning of the new line.

8 File.readlines([sizeh It returns a list containing all the


int]) lines of the file. It reads the file
until the EOF occurs using the
readline() function.

9 File.seek(offset[,fro It modifies the position of the file


m) pointer to a specified offset with
the specified reference.

10 File.tell() It returns the current position of


the file pointer within the file.

11 File.truncate([size]) It truncates the file to the


optionally specified size.

12 File.write(str) It writes the specified string to a


file

13 File.write lines(seq) It writes a sequence of strings to


a file.

7.3 PYTHON MODULE


Python Modules
130
Python Programming

A python module can be defined as a program file containing python code,


including python functions, classes, or variables. In other words, we can
say that our python code file saved with the extension (.py) is treated as
the module. We may have a runnable code inside the python module.
Modules in Python allow us the flexibility to organize the code logically.
To use the functionality of one module in another, we must import the
specific module.
Example
In this example, we will create a module named file.py, which contains a
function func that contains a code to print some messages on the console.
Let's create the module named file.py.
#displayMsg prints a message to the name being passed.
def displaying(name)
print("Hi "+name);
Here, we need to include this module in our main module to call the
method displaying() defined in the named file.
Loading the module in our python code
We need to load the module in our python code to use its functionality.
Python provides two types of statements, as defined below.
1. The import statement
2. The from-import statement
The import statement
The import statement is used to import all the functionality of one module
into another. Here, we must notice that we can use the functionality of any
python source file by importing that file as the module into another python
source file.
We can import multiple modules with a single import statement, but a
module is loaded once regardless of the times it has been imported into
our file.
The syntax to use the import statement is given below.
1. import module1,module2,........ module n
Hence, if we need to call the function displaying() defined in the file file.py,
we must import that file as a module into our module, as shown in the
example below.
Example:
import file;
name = input("Enter the name?")
file.displaying(name)
Output:
Enter the name. Guru

131
Python Programming

Hi Guru
The from-import statement
Instead of importing the whole module into the namespace, python
provides the flexibility to import only the specific attributes of a module.
Import statement. The syntax to use the from-import statement is given
below.
from < module-name> import <name 1>, <name 2>..,<name n>
Consider the calculation module containing three functions: summation,
multiplication, and divide.
calculation.py:
#place the code in the calculation.py
def summation(a,b):
return a+b
def multiplication(a,b):
return a*b;
def divide(a,b):
return a/b;
Main.py:
from calculation import summation
#it will import only the summation() from calculation.py
a = int(input("Enter the first number"))
b = int(input("Enter the second number"))
print("Sum = ",summation(a,b)) #we do not need to specify the module na
me while accessing summation()
Output:
Enter the first number10
Enter the second number20
Sum = 30
The from...import statement is always better if we know the attributes
imported from the module in advance. It doesn't allow our code to be
heavier. We can also import all the attributes from a module by using *.
Consider the following syntax.
1. from <module> import *
Renaming a module
Python provides us the flexibility to import some modules with a specific
name so that we can use this name to use that module in our python
source file.
The syntax to rename a module is given below.
import <module-name> as <specific-name>

132
Python Programming

Example
#the module calculation of the
previous example is imported in this example as cal.
import calculation as cal;
a = int(input("Enter a?"));
b = int(input("Enter b?"));
print("Sum = ",cal.summation(a,b))
Output:
Enter a? 10
Enter b? 20
Sum = 30
Using dir() function
The dir() function returns a sorted list of names defined in the passed
module. This list contains all the sub-modules, variables, and functions
defined in this module.
Consider the following example.
Example
import json

List = dir(json)
print(List)
Output:
['JSONDecoder', 'JSONEncoder', '__all__', '__author__', '__builtins__',
'__cached__', '__doc__',
'__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__',
'__version__',
'_default_decoder', '_default_encoder', 'decoder', 'dump', 'dumps', 'encoder',
'load', 'loads', 'scanner']
The reload() function
As we have already stated, a module is loaded once regardless of the times
it is imported into the python source file. However, if you want to reload
the imported module to re-execute the top-level code, python provides us
with the reload() function. The syntax to use the reload() function is given
below.
1. reload(<module-name>)
for example, to reload the module calculation defined in the previous
example, we must use the following line of code.
1. reload(calculation)

133
Python Programming

Scope of variables
In Python, variables are associated with two types of scopes. All the
variables in a module contain the global scope unless or until it is defined
within a function.
All the variables defined inside a function contain a local scope limited to
this function. We can not access a local variable globally.
If two variables are defined with the same name with two different scopes,
i.e., local and global, then the priority will always be given to the local
variable.
Consider the following example.
Example
name = "Guru"
def print_name(name):
print("Hi",name) #prints the name local to this function only.
name = input("Enter the name?")
print_name(name)
Output:
Hi Guru

134
Python Programming

CHAPTER 8
FUNCTIONS
8.1 PYTHON FUNCTION
The essential component of an application is its functions. A function is an
organized block of reusable code that may be called anytime it is defined.
Python enables us to break down a big program into fundamental building
pieces known as functions. The function comprises the collection of
programming statements denoted by A function that can be called multiple
times to offer reusability and modularity to the Python program.
The Function assists the programmer in breaking down the program into
smaller parts. It effectively organizes the code and prevents code repetition.
As the program expands, function helps to arrange it.
Python has several built-in functions, such as range() and print ().
However, the user can create its functions, which are called user-defined
functions.
There are mainly two types of functions.
o User-defined functions - The user-defined functions are those defined by
the user to perform a specific task.
o Built-in functions - The built-in functions are those functions that
are pre-defined in Python.
In this tutorial, we will discuss the user define functions.
Advantages of Functions in Python
There are the following advantages of Python functions.
o Using functions, we can avoid repeatedly rewriting the same logic/code in
a program.
o We can call Python functions multiple times in a program and anywhere.
o We can easily track a large Python program when divided into multiple
functions.
o Reusability is the main achievement of Python functions.
o However, Function calling is always overhead in a Python program.
8.2 CREATING A FUNCTION
Python provides the def keyword to define the function. The syntax of the
defined function is given below.
Syntax:
def my_function(parameters):
function_block
return expression
Let's understand the syntax of the function definition.
o The def keyword and the function name are used to define the function.
o The identifier rule must follow the function name.

135
Python Programming

o A function accepts the parameter (argument) and can be optional.


o The function block is started with the colon (:), and block statements must
be at the same indentation.
o The return statement is used to return the value. A function can have only
one return
8.3 FUNCTION CALLING
We can call it from another function after the function is created in
Python. A function must be defined before the call; otherwise, the Python
interpreter gives an error. To call the function, use the function name
followed by the parentheses.
Consider the simple example that prints the message "Hello World."
#function definition
def hello_world():
print("hello world")
# function calling
hello_world()
Output:
Hello world
The return statement
The return statement is used at the end of the function and returns the
result. It terminates the function execution and transfers the result where
the function is called. The return statement cannot be used outside of the
function.
Syntax
1. return [expression_list]
It can contain the expression evaluated, and the value is returned to the
caller function. If the return statement has no expression or does not exist
in the function, it returns the None object.
Consider the following example:
Example 1
# Defining function
def sum():
a = 10
b = 20
c = a+b
return c
# calling sum() function in print statement
print("The sum is:",sum())
Output:
The sum is: 30

136
Python Programming

In the above code, we have defined the function named sum, which has a
statement c = a+b, which computes the given values, and the return
statement to the caller function returns the result.
Example 2 Creating function without return statement
# Defining function
def sum():
a = 10
b = 20
c = a+b
# calling sum() function in print statement
print(sum())
Output:
None
In the above code, we have defined the same function without the return
statement, as we can see that the sum() function returned the None object
to the caller function.
8.4 ARGUMENTS IN FUNCTION
The arguments are several data types that may be passed into the
function. The arguments are included in parentheses. We can pass any
number of parameters, but a comma must separate them.
Consider the following example, which has a function that takes a string
as an argument.
Example 1
#defining the function
def func (name):
print("Hi ",name)
#calling the function
func("Guru")
Output:
Hi Guru
Example 2
#Python function to calculate the sum of two variables
#defining the function
def sum (a,b):
return a+b;
#taking values from the user
a = int(input("Enter a: "))
b = int(input("Enter b: "))
#printing the sum of a and b
print("Sum = ",sum(a,b))

137
Python Programming

Output:
Enter a: 10
Enter b: 20
Sum = 30
Call by reference in Python
In Python, calling a function via reference implies giving the real value as
an argument. All functions are called by reference, which means that any
modifications made to the reference within the function return to the
original value referred by the reference.
Example 1 Passing Immutable Object (List)
#defining the function
def change_list(list1):
list1.append(20)
list1.append(30)
print("list inside function = ",list1)
#defining the list
list1 = [10,30,40,50]

#calling the function


change_list(list1)
print("list outside function = ",list1)
Output:
list inside function = [10, 30, 40, 50, 20, 30]
list outside function = [10, 30, 40, 50, 20, 30]
Example 2 Passing Mutable Object (String)
#defining the function
def change_string (str):
str = str + " Hows you. "
print("printing the string inside function :",str)
string1 = "Hi, I am there."
#calling the function
change_string(string1)
print("printing the string outside function :",string1)
Output:
Printing the string inside the function: Hi, I am there. Hows you
printing the string outside the function: Hi, I am there
Types of arguments
There may be several types of arguments that can be passed at the time of
the function call.
1. Required arguments

138
Python Programming

2. Keyword arguments
3. Default arguments
4. Variable-length arguments
Required Arguments
So far, we've studied function calls in Python. We can, however, supply the
parameters at the time of the function call. Regarding necessary
arguments, these are the parameters that must be passed at the time of
the function call, with the precise match of their places in the function call
and function definition. The Python interpreter will display an error if one
of the parameters is not given in the function call or if the position of the
arguments is changed.
Consider the following example.
Example 1
def func(name):
message = "Hi "+name
return message
name = input("Enter the name:")
print(func(name))
Output:
Enter the name: Guru
Hi Guru
DEFAULT ARGUMENTS
At the function definition, Python allows us to initialize the parameters.
Suppose the value of any arguments is not supplied at the time of the
function call. In that case, that argument can be initialized with the value
indicated in the definition even if the argument is not supplied at the time
of the function call.
Example 1
def printme (name,age=22):
print("My name is",name,"and age is",age)
printme(name = "Guru")
Output:
My name is Guru, and my age is 22
VARIABLE-LENGTH ARGUMENTS (*ARGS)
We may not know the number of arguments passed in advance in huge
projects. In such instances, Python allows us to specify comma-separated
values internally processed as tuples at the function call. We may pass any
number of arguments by utilizing variable-length parameters.
However, in the function definition, we define the variable-length argument
as *variable - name > utilizing the *args (star).

139
Python Programming

Consider the following example.


Example
def printme(*names):
print("type of passed argument is ",type(names))
print("printing the passed arguments...")
for name in names:
print(name)
printme("Guru","Guru","smith","nick")
Output:
type of passed argument is <class 'tuple'>
printing the passed arguments...
Guru
Guru
smith
nick
We passed *names as a variable-length argument in the preceding code.
We called the function and passed values that are internally handled as
tuples. The tuple, like the list, is an iterable sequence. We used a for loop
to traverse the *arg names to print the supplied values.
Keyword arguments(**kwargs) Python allows us to use keyword arguments
to call functions. This function call allows us to pass the parameters in
arbitrary order.
The parameters' names are keywords and matched in function calling and
definition. The parameters' values are copied into the function definition if
an identical match is found.
Consider the following example.
Python allows you to pass multiple keyword arguments represented as
**kwargs. It works the same way as *args, except it saves the argument in
dictionary format.
This type of argument is important when we don't know how many
arguments we'll need ahead of the number.
Consider the following scenario:
Example 6: Many arguments using Keyword argument
def food(**kwargs):
print(kwargs)
food(a="Apple")
food(fruits="Orange", Vagitables="Carrot")
Output:
{'a': 'Apple'}
{'fruits': 'Orange', 'Vagitables': 'Carrot'}

140
Python Programming

8.5 SCOPE OF VARIABLES


The scopes of the variables depend upon the location where the variable is
being declared. The variable declared in one part of the program may not
be accessible to the other parts.
In python, the variables are defined with two types of scopes.
1. Global variables
2. Local variables
The variable defined outside any function is known to have a global scope,
whereas the variable defined inside a function is known to have a local
scope.
Consider the following example.
Example 1 Local Variable
def print_message():
message = "hello !! I am going to print a message." # the variable messag
e is local to the function itself
print(message)
print_message()
print(message) # this will cause an error since a local variable cannot be a
ccessible here.
Output:
Hello!! I am going to print a message.
File "/root/PycharmProjects/PythonTest/Test1.py", line 5, in
print(message)
NameError: name 'message' is not defined
Example 2 Global Variable
def calculate(*args):
sum=0
for arg in args:
sum = sum +arg
print("The sum is",sum)
sum=0
calculate(10,20,30) #60 will be printed as the sum
print("Value of sum outside the function:",sum) # 0 will be printed Output
:
Output:
The sum is 60
Value of sum outside the function: 0
8.6 PYTHON BUILT-IN FUNCTIONS
Python built-in functions are defined as functions with pre-defined
functionality in Python. The Python interpreter contains several functions

141
Python Programming

that are always available for usage. Built-in Functions are the names given
to these functions. Python has numerous built-in functions, which are
mentioned below:
Python abs() Function
The python abs() function returns a number's absolute value. It only
accepts one argument, a number whose absolute value is to be returned.
An integer or a floating-point number can be used as the argument. If the
argument is a complex number, abs(,) returns its magnitude.
Python abs() Function Example
# integer number
integer = -20
print('Absolute value of -40 is:', abs(integer))

# floating number
floating = -20.83
print('Absolute value of -40.83 is:', abs(floating))
Output:
The absolute value of -20 is: 20
The absolute value of -20.83 is: 20.83

Python all() Function


Python's all() function takes an iterable object as input (such as a list,
dictionary, etc.). If all of the items in the passed iterable are true, it returns
true. If not, it returns False. The all() function returns True if the iterable
object is empty.
Python all() Function Example
# all values true
k = [1, 3, 4, 6]
print(all(k))
# all values false
k = [0, False]
print(all(k))
# one false value
k = [1, 3, 7, 0]
print(all(k))
# one true value
k = [0, False, 5]
print(all(k))
# empty iterable
k = []

142
Python Programming

print(all(k))
Output:
True
False
False
False
True

Python bin() Function


The python bin() function returns the binary representation of a specified
integer. A result always starts with the prefix 0b.
Python bin() Function Example
x = 10
y = bin(x)
print (y)
Output:
0b1010

Python bool()
The python bool() converts a value to a boolean(True or False) using the
standard truth testing procedure.
Python bool() Example
test1 = []
print(test1,'is',bool(test1))
test1 = [0]
print(test1,'is',bool(test1))
test1 = 0.0
print(test1,'is',bool(test1))
test1 = None
print(test1,'is',bool(test1))
test1 = True
print(test1,'is',bool(test1))
test1 = 'Easy string'
print(test1,'is',bool(test1))
Output:
[] is False
[0] is True
0.0 is False
None is False
True is True

143
Python Programming

An easy string is True

Python bytes()
The python bytes() in Python are used for returning a byte object. It is an
immutable version of the byte array() function.
It can create empty bytes objects of the specified size.
Python bytes() Example
string = "Hello World."
array = bytes(string, 'utf-8')
print(array)
Output:
b ' Hello World.'

Python callable() Function


A python callable() function in Python can be called. This built-in function
checks and returns true if the object passed appears to be callable;
otherwise false.
Python callable() Function Example
1. x = 8
2. print(callable(x))
Output:
False

Python compile() Function


The python compile() function takes source code as input and returns a
code object which can later be executed by the exec() function.
Python compile() Function Example
# compile string source to code
code_str = 'x=5\ny=10\nprint("sum =",x+y)'
code = compile(code_str, 'sum.py', 'exec')
print(type(code))
exec(code)
exec(x)
Output:
<class 'code'>
sum = 15

Python exec() Function


The python exec() function is used for the dynamic execution of the
Python program, which can either be a string or object code and accepts

144
Python Programming

large blocks of code, unlike the eval() function, which only accepts a single
expression.
Python exec() Function Example
x=8
exec('print(x==8)')
exec('print(x+4)')
Output:
True
12

Python sum() Function


As the name says, the python sum() function is used to get the sum of
numbers of an iterable, i.e., a list.
Python sum() Function Example
s = sum([1, 2,4 ])
print(s)

s = sum([1, 2, 4], 10)


print(s)
Output:
7
17

Python any() Function


The python any() function returns true if any item in an iterable is true.
Otherwise, it returns False.
Python any() Function Example
l = [4, 3, 2, 0]
print(any(l))

l = [0, False]
print(any(l))

l = [0, False, 5]
print(any(l))

l = []
print(any(l))
Output:
True

145
Python Programming

False
True
False

Python ascii() Function


The ASCII () function in Python returns a string containing a printed
representation of an object and escapes non-ASCII characters using the x
or U escapes.
Python ascii() Function Example
normalText = 'Python is interesting'
print(ascii(normalText))

other text = 'Pythön is interesting'


print(ascii(otherText))

print('Pyth\xf6n is interesting')
Output:
'Python is interesting'
'Pyth\xf6n is interesting.'
Pythön is interesting

Python bytearray()
The python byte array () returns a bytearray object and can convert
objects into bytearray objects or create an empty bytearray object of the
specified size.
Python bytearray() Example
string = "Python is a programming language."

# string with encoding 'utf-8.'


arr = bytearray(string, 'utf-8')
print(arr)
Output:
bytearray(CPython is a programming language.')

Python eval() Function


The python eval() function parses the expression passed and runs the
program's python expression(code).
Python eval() Function Example
1. x = 8
2. print(eval('x + 1'))

146
Python Programming

Output:
9

Python float()
The python float() function returns a floating-point number from a
number or string.
Python float() Example
# for integers
print(float(9))

# for floats
print(float(8.19))

# for string floats


print(float("-24.27"))

# for string floats with whitespaces


print(float(" -17.19\n"))

# string float error


print(float("XYZ"))
Output:
1.0
8.19
-24.27
-17.19
ValueError: could not convert string to float: 'XYZ.'

Python format() Function


The python-format() function returns a formatted representation of the
given value.
Python format() Function Example
# d, f, and b are a type

# integer
print(format(123, "d"))

# float arguments
print(format(123.4567898, "f"))

147
Python Programming

# binary format
print(format(12, "b"))
Output:
123
123.456790
1100

Python frozenset()
The python frozenset() function returns an immutable frozenset object
initialized with elements from the given iterable.
Python frozenset() Example
# tuple of letters
letters = ('m', 'r', 'o', 't', 's')

fSet = frozenset(letters)
print('Frozen set is:', fSet)
print('Empty frozen set is:', frozenset())
Output:
Frozen set is: frozenset({'o', 'm', 's', 'r', 't'})
Empty frozen set is: frozenset()

Python getattr() Function


The python getattr() function returns the value of a named attribute of an
object. If it is not found, it returns the default value.
Python getattr() Function Example
class Details:
age = 22
name = "Phill"

details = Details()
print('The age is:', getattr(details, "age"))
print('The age is:', details.age)
Output:
The age is: 22
The age is: 22

Python globals() Function


The python globals() function returns the dictionary of the current global
symbol table.

148
Python Programming

A Symbol table is a data structure containing all the necessary


information about the program. It includes variable names, methods,
classes, etc.
Python globals() Function Example
age = 22
globals()['age'] = 22
print('The age is:', age)
Output:
The age is: 22

Python hasattr() Function


The python any() function returns true if any item in an iterable is true.
Otherwise, it returns False.
Python hasattr() Function Example
l = [4, 3, 2, 0]
print(any(l))

l = [0, False]
print(any(l))
l = [0, False, 5]
print(any(l))
l = []
print(any(l))
Output:
True
False
True
False

Python iter() Function


The python iter() function is used to return an iterator object. It creates an
object which can be iterated one element at a time.
Python iter() Function Example
# list of numbers
list = [1,2,3,4,5]
listIter = iter(list)
# prints '1'
print(next(listIter))
# prints '2'
print(next(listIter))

149
Python Programming

# prints '3'
print(next(listIter))
# prints '4'
print(next(listIter))
# prints '5'
print(next(listIter))
Output:
1
2
3
4
5

Python len() Function


The python len() function returns an object's length (the number of items).
Python len() Function Example
1. strA = 'Python'
2. print(len(strA))
Output:
6
Python list()
The python list() creates a list in python.
Python list() Example
# empty list
print(list())

# string
String = 'abcde'
print(list(String))

# tuple
Tuple = (1,2,3,4,5)
print(list(Tuple))
# list
List = [1,2,3,4,5]
print(list(List))
Output:
[]
['a', 'b', 'c', 'd', 'e']
[1,2,3,4,5]

150
Python Programming

[1,2,3,4,5]

Python locals() Function


The python locals() method updates and returns the dictionary of the
current local symbol table.
A Symbol table is a data structure containing all the necessary
information about the program. It includes variable names, methods,
classes, etc.
Python locals() Function Example
def localsAbsent():
return locals()

def localsPresent():
present = True
return locals()

print('localsNotPresent:', localsAbsent())
print('localsPresent:', localsPresent())
Output:
localsAbsent: {}
localsPresent: {'present': True}

Python map() Function


The python map() function returns a list of results after applying a given
function to each item of an iterable(list, tuple, etc.).
Python map() Function Example
def calculateAddition(n):
return n+n

numbers = (1, 2, 3, 4)
result = map(calculateAddition, numbers)
print(result)

# converting map object to set


numbersAddition = set(result)
print(numbersAddition)
Output:
<map object at 0x7fb04a6bec18>
{8, 2, 4, 6}

151
Python Programming

Python memoryview() Function


The python memoryview() function returns a memoryview object of the
given argument.
Python memoryview () Function Example
#A random bytearray
randomByteArray = bytearray('ABC', 'utf-8')

m= memoryview(randomByteArray)

# access the memory view's zeroth index


print(mv[0])

# It creates a byte from the memory view


print(bytes(mv[0:2]))

# It creates a list from the memory view


print(list(mv[0:3]))
Output:
65
baby
[65, 66, 67]

Python object()
The python object() returns an empty object. It is a base for all the classes
and holds the built-in properties and methods default for all the classes.
Python object() Example
python = object()

print(type(python))
print(dir(python))
Output:
<class 'object'>
['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__',
'__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__ne__',
'__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__',
'__str__', '__subclasshook__']

Python open() Function


The python open() function opens the file and returns a corresponding file
object.

152
Python Programming

Python open() Function Example


# opens python.text file of the current directory
f = open("python.txt")
# specifying the full path
f = open("C:/Python33/README.txt")
Output:
Since the mode is omitted, the file is opened in 'r' mode; it opens for
reading.

Python chr() Function


Python chr() function is used to get a string representing a character that
points to a Unicode code integer. For example, chr(97) returns the string
'a'. This function takes an integer argument and throws an error if it
exceeds the specified range. The standard range of the argument is from 0
to 1,114,111.
Python chr() Function Example
# Calling function
result = chr(102) # It returns a string representation of a char
result2 = chr(112)
# Displaying result
print(result)
print(result2)
# Verify, is it string type?
print("is it string type:", type(result) is str)
Output:
ValueError: chr() arg not in range(0x110000)

Python complex()
The python complex() function converts numbers or strings into complex
numbers. This method takes two optional parameters and returns a
complex number. The first parameter is called a real, and the second is an
imaginary part.
Python complex() Example
# Python complex() function example
# Calling function
a = complex(1) # Passing single parameter
b = complex(1,2) # Passing both parameters
# Displaying result
print(a)
print(b)

153
Python Programming

Output:
(1.5+0j)
(1.5+2.2j)

Python delattr() Function


The python delete() function is used to delete an attribute from a class. It
takes two parameters, the first is an object of the class, and the second is
an attribute we want to delete. After deleting the attribute, it is no longer
available in the class and throws an error if you try to call it using the
class object.
Python delattr() Function Example
class Student:
id = 101
name = "Pranshu"
email = "[email protected]"
# Declaring function
def getinfo(self):
print(self.id, self.name, self.email)
s = Student()
s.getinfo()
delattr(Student,'course') # Removing attribute which is not available
s.getinfo() # error: throws an error
Output:
101 Pranshu [email protected]
AttributeError: course

Python dir() Function


Python dir() function returns the list of names in the current local scope. If
the object on which the method is called has a method named __dir__(),
this method will be called and must return the list of attributes. It takes a
single object-type argument.
Python dir() Function Example
# Calling function
att = dir()
# Displaying result
print(att)
Output:
['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__',
'__loader__',
'__name__', '__package__', '__spec__']

154
Python Programming

Python divmod() Function


Python divmod() function is used to get the remainder and quotient of two
numbers. This function takes two numeric arguments and returns a tuple.
Both arguments are required, and numeric
Python divmod() Function Example
# Python divmod() function example
# Calling function
result = divmod(10,2)
# Displaying result
print(result)
Output:
(5, 0)

Python enumerate() Function


Python enumerates () function returns an enumerated object. It takes two
parameters, the first is a sequence of elements, and the second is the start
index of the sequence. We can get the elements in sequence through a loop
or the next() method.
Python enumerate() Function Example
# Calling function
result = enumerate([1,2,3])
# Displaying result
print(result)
print(list(result))
Output:
<enumerate object at 0x7ff641093d80>
[(0, 1), (1, 2), (2, 3)]

Python dict()
Python dict() function is a constructor which creates a dictionary. Python
dictionary provides three different constructors to create a dictionary:
o If no argument is passed, it creates an empty dictionary.
o A dictionary is created with the same key-value pairs if a positional
argument is given. Otherwise, pass an iterable object.
o If keyword arguments are given, the keyword arguments and their values
are added to the dictionary created from the positional argument.
Python dict() Example
# Calling function
result = dict() # returns an empty dictionary

155
Python Programming

result2 = dict(a=1,b=2)
# Displaying result
print(result)
print(result2)
Output:
{}
{'a': 1, 'b': 2}

Python filter() Function


Python filter() function is used to get filtered elements. This function takes
two arguments, the first is a function, and the second is iterable. The filter
function returns a sequence of those elements of the iterable object for
which the function returns a true value.
The first argument can be none if the function is unavailable and returns
only true elements.
Python filter() Function Example
# Python filter() function example
def filterdata(x):
if x>5:
return x
# Calling function
result = filter(filterdata,(1,2,6))
# Displaying result
print(list(result))
Output:
[6]

Python hash() Function


The python hash() function is used to get the hash value of an object.
Python calculates the hash value by using the hash algorithm. The hash
values are integers used to compare dictionary keys during a dictionary
lookup. We can hash only the types which are given below:
Hashable types: * bool * int * long * float * string * Unicode * tuple * code
object.
Python hash() Function Example
# Calling function
result = hash(21) # integer value
result2 = hash(22.2) # decimal value
# Displaying result
print(result)

156
Python Programming

print(result2)
Output:
21
461168601842737174

Python help() Function


Python help() function is used to get help related to the object passed
during the call. It takes an optional parameter and returns help
information. If no argument is given, it shows the Python help console. It
internally calls python's help function.
Python help() Function Example
# Calling function
info = help() # No argument
# Displaying result
print(info)
Output:
Welcome to Python 3.5's help utility!

Python min() Function


Python min() function is used to get the smallest element from the
collection. This function takes two arguments; the first is a collection of
elements, and the second is key and returns the smallest element from the
collection.
Python min() Function Example
# Calling function
small = min(2225,325,2025) # returns smallest element
small2 = min(1000.25,2025.35,5625.36,10052.50)
# Displaying result
print(small)
print(small2)
Output:
325
1000.25

Python set() Function


In python, a set is a built-in class, and this function is a constructor of
this class. It creates a new set using elements passed during the call. It
takes an iterable object as an argument and returns a new set object.
Python set() Function Example
# Calling function

157
Python Programming

result = set() # empty set


result2 = set('12')
result3 = set('java point)
# Displaying result
print(result)
print(result2)
print(result3)
Output:
set()
{'1', '2'}
{'a', 'n', 'v', 't', 'j', 'p', 'i', 'o'}

Python hex() Function


The python hex() function generates the hex value of an integer argument.
It takes an integer argument and returns an integer converted into a
hexadecimal string. If we want to get a hexadecimal value of a float, then
use float.hex() function.
Python hex() Function Example
# Calling function
result = hex(1)
# integer value
result2 = hex(342)
# Displaying result
print(result)
print(result2)
Output:
0x1
0x156

Python id() Function


The python id() function returns the identity of an object. This is an
integer that is guaranteed to be unique. This function takes an argument
as an object and returns a unique integer number representing identity.
Two objects with non-overlapping lifetimes may have the same id() value.
Python id() Function Example
# Calling function
val = id("Javatpoint") # string object
val2 = id(1200) # integer object
val3 = id([25,336,95,236,92,3225]) # List object
# Displaying result

158
Python Programming

print(val)
print(val2)
print(val3)
Output:
139963782059696
139963805666864
139963781994504

Python setattr() Function


Python setattr() function is used to set a value to the object's attribute. It
takes three arguments, i.e., an object, a string, and an arbitrary value, and
returns none. It is helpful when we want to add a new attribute to an
object and set a value.
Python setattr() Function Example
class Student:
id = 0
name = ""

def __init__(self, id, name):


self.id = id
self.name = name

student = Student(102,"Sohan")
print(student.id)
print(student.name)
#print(student.email) product error
setattr(student, 'email','[email protected]') # adding new attribute
print(student.email)
Output:
102
Sohan
[email protected]

Python slice() Function


The python slice() function is used to get a slice of elements from the
collection of elements. Python provides two overloaded slice functions. The
first function takes a single argument, while the second takes three
arguments and returns a slice object. This slice object can be used to get a
subsection of the collection.
Python slice() Function Example

159
Python Programming

# Calling function
result = slice(5) # returns slice object
result2 = slice(0,5,3) # returns slice object
# Displaying result
print(result)
print(result2)
Output:
slice(None, 5, None)
slice(0, 5, 3)

Python sorted() Function


Python sorted() function is used to sort elements. By default, it sorts
elements in ascending order but can be sorted in descending also. It takes
four arguments and returns a collection in sorted order. In the case of a
dictionary, it sorts only keys, not values.
Python sorted() Function Example
str = "javatpoint" # declaring string
# Calling function
sorted1 = sorted(str) # sorting string
# Displaying result
print(sorted1)
Output:
['a', 'a', 'i', 'j', 'n', 'o', 'p', 't', 't', 'v']

Python next() Function


Python next() function is used to fetch the next item from the collection. It
takes two arguments, i.e., an iterator and a default value, and returns an
element.
This method calls on the iterator and throws an error if no item is present.
To avoid the error, we can set a default value.
Python next() Function Example
number = iter([256, 32, 82]) # Creating an iterator
# Calling function
item = next(number)
# Displaying result
print(item)
# second item
item = next(number)
print(item)
# third item

160
Python Programming

item = next(number)
print(item)
Output:
256
32
82

Python input() Function


Python input() function is used to get input from the user. It prompts the
user to input and reads a line. After reading data, it converts it into a
string and returns it. It throws an error EOFError if EOF is read.
Python input() Function Example
1. # Calling function
2. val = input("Enter a value: ")
3. # Displaying result
4. print("You entered:",val)
Output:
Enter a value: 45
You entered: 45

Python int() Function


The python int() function is used to get an integer value. It returns an
expression converted into an integer number. If the argument is a floating
point, the conversion truncates the number. If the argument is outside the
integer range, it converts the number into a long type.
If the number is not a number or if a base is given, the number must be a
string.
Python int() Function Example
# Calling function
val = int(10) # integer value
val2 = int(10.52) # float value
val3 = int('10') # string value
# Displaying result
print("integer values :",val, val2, val3)
Output:
integer values: 10 10 10

161
Python Programming

Python isinstance() Function


Python instance() function is used to check whether the given object is an
instance of that class. If the object belongs to the class, it returns true.
Otherwise returns False. It also returns true if the class is a subclass.
The isinstance() function takes two arguments, i.e., object and classify,
and returns either True or False.
Python instance() function Example
class Student:
id = 101
name = "Guru"
def __init__(self, id, name):
self.id=id
self.name=name

student = Student(1010,"Guru")
lst = [12,34,5,6,767]
# Calling function
print(isinstance(student, Student)) # isinstance of Student class
print(isinstance(lst, Student))
Output:
True
False

Python oct() Function


The python oct() function is used to get an octal value of an integer
number. This method takes an argument and returns an integer converted
into an octal string. It throws an error TypeError if the argument type is
other than an integer.
Python oct() function Example
# Calling function
val = oct(10)
# Displaying result
print("Octal value of 10:",val)
Output:
The octal value of 10: 0o12

Python ord() Function


The python ord() function returns an integer representing the Unicode
code point for the Unicode character.
Python ord() function Example

162
Python Programming

# Code point of an integer


print(ord('8'))

# Code point of an alphabet


print(ord('R'))

# Code point of a character


print(ord('&'))
Output:
56
82
38

Python pow() Function


The python pow() function is used to compute the power of a number. It
returns x to the power of y. If the third argument(z) is given, it returns x to
the power of y modulus z, i.e. (x, y) % z.
Python pow() function Example
# positive x, positive y (x**y)
print(pow(4, 2))

# negative x, positive y
print(pow(-4, 2))

# positive x, negative y (x**-y)


print(pow(4, -2))

# negative x, negative y
print(pow(-4, -2))
Output:
16
16
0.0625
0.0625

Python print() Function


The python print() function prints the object to the screen or other
standard output devices.
Python print() function Example
print("Python is a programming language.")

163
Python Programming

x=7
# Two objects passed
print("x =", x)

y=x
# Three objects passed
print('x =', x, '= y')
Output:
Python is a programming language.
x=7
x=7=y

Python range() Function


The python range() function returns an immutable sequence of numbers
starting from 0 by default, increments by 1 (by default), and ends at a
specified number.
Python range() function Example
# empty range
print(list(range(0)))

# using the range(stop)


print(list(range(4)))

# using the range(start, stop)


print(list(range(1,7 )))
Output:
[]
[0, 1, 2, 3]
[1, 2, 3, 4, 5, 6]

Python reversed() Function


The python reversed() function returns the reversed iterator of the given
sequence.
Python reversed() function Example
# for string
String = 'Java'
print(list(reversed(String)))

# for tuple

164
Python Programming

Tuple = ('J', 'a', 'v', 'a')


print(list(reversed(Tuple)))

# for range
Range = range(8, 12)
print(list(reversed(Range)))

# for list
List = [1, 2, 7, 5]
print(list(reversed(List)))
Output:
['a', 'v', 'a', 'J']
['a', 'v', 'a', 'J']
[11, 10, 9, 8]
[5, 7, 2, 1]

Python round() Function


The python round() function rounds off the digits of a number and returns
the floating point number.
Python round() Function Example
# for integers
print(round(10))

# for floating point


print(round(10.8))

# even choice
print(round(6.6))
Output:
10
11
7

Python issubclass() Function


The python issubclass() function returns true if the object argument(first
argument) is a subclass of the second class(second argument).
Python issubclass() Function Example
class Rectangle:
def __init__(rectangle type):
print('Rectangle is a ', rectangleType)

165
Python Programming

class Square(Rectangle):
def __init__(self):
Rectangle.__init__('square')

print(issubclass(Square, Rectangle))
print(issubclass(Square, list))
print(issubclass(Square, (list, Rectangle)))
print(issubclass(Rectangle, (list, Rectangle)))
Output:
True
False
True
True

Python str
The python str() converts a specified value into a string.
Python str() Function Example
1. str('4')
Output:
'4'
Python tuple() Function
The python tuple() function is used to create a tuple object.
Python tuple() Function Example
t1 = tuple()
print('t1=', t1)

# creating a tuple from a list


t2 = tuple([1, 6, 9])
print('t2=', t2)

# creating a tuple from a string


t1 = tuple('Java')
print('t1=',t1)

# creating a tuple from a dictionary


t1 = tuple({4: 'four', 5: 'five'})
print('t1=',t1)
Output:
t1= ()

166
Python Programming

t2= (1, 6, 9)
t1= ('J', 'a', 'v', 'a')
t1= (4, 5)

Python type()
The Python type() returns the type of the specified object if a single
argument is passed to the type() built-in function. If three arguments are
passed, it returns a new object type.
Python type() Function Example
List = [4, 5]
print(type(List))

Dict = {4: 'four', 5: 'five'}


print(type(Dict))

class Python:
a=0

InstanceOfPython = Python()
print(type(InstanceOfPython))
Output:
<class 'list'>
<class 'dict'>
<class '__main__.Python'>

Python vars() function


The python vars() function returns the __dict__ attribute of the given
object.
Python vars() Function Example
class Python:
def __init__(self, x = 7, y = 9):
self.x = x
self.y = y

InstanceOfPython = Python()
print(vars(InstanceOfPython))
Output:
{'y': 9, 'x': 7}

167
Python Programming

Python zip() Function


The python zip() Function returns a zip object, which maps a similar index
of multiple containers. It takes iterables (can be zero or more), makes it an
iterator that aggregates the elements based on iterables passed, and
returns an iterator of tuples.
Python zip() Function Example
numList = [4,5, 6]
strList = ['four', 'five', 'six']

# No tables are passed


result = zip()

# Converting iterator to list


resultList = list(result)
print(resultList)

# Two iterables are passed


result = zip(numList, strList)

# Converting itertor to set


resultSet = set(result)
print(resultSet)
Output:
[]
{(5, 'five'), (4, 'four'), (6, 'six')}
8.7 PYTHON LAMBDA FUNCTIONS
The Lambda function in Python is anonymous since it is defined without a
name. Python prevents us from traditionally declaring the function, i.e.,
using the def keyword. Rather, the lambda keyword is used to declare
anonymous functions. On the other hand, Lambda functions can take an
unlimited number of parameters but can only return one value as an
expression.
A small amount of code is included in the anonymous function. It
resembles C and C++ inline functions, although it is not quite an inline
function.
The following syntax is used to define an anonymous function.
Syntax
lambda arguments: expression
It can accept any number of arguments and has only one expression. It is
useful when the function objects are required.

168
Python Programming

Consider the following example of the lambda function.


Example 1
# a is an argument,
and a+10 is an expression that got evaluated and returned.
x = lambda a:a+10
# Here, we are printing the function object
print(x)
print("sum = ",x(20))
Output:
<function <lambda> at 0x0000019E285D16A8>
sum = 30
In the above example, we have defined the lambda a: a+10 anonymous
function where a is an argument and a+10 is an expression. The given
expression gets evaluated and returns the result. The above lambda
function is the same as the normal function.
def x(a):
return a+10
print(sum = x(10))
Example 2
Multiple arguments to the Lambda function
# a and b are the arguments,
and a*b is the expression that gets evaluated and returned.
x = lambda a,b: a*b
print("mul = ", x(20,10))
<p><strong>Output:</strong></p>
<diclass="codeblock3"><pre>
mul = 200
</pre></div>
<h2 class="h2">Why use lambda function?</h2>
<p>The main role of the lambda function is better described in the scenari
os when we use them anonymously inside another function. In Python, the
lambda function can be used as an argument to the <strong>higher-
order functions</strong>,
which accepts other functions as arguments.</p>
<p>Consider the following example:</p>
<h3 class="h3">Example 1:</h3>
<diclass="codeblock"><textarea name="code" class="python">
#the function table(n) prints the table of n
def table(n):

169
Python Programming

return lambda a:a*n # a will contain the iteration variable i,


and a multiple of n is returned at each function call
n = int(input("Enter the number:"))
b = table(n) #,
the entered number is passed into the function table. b will contain a lamb
da function which is called again and again with the iteration variable i
for i in range(1,11):
print(n,"X",i,"=",b(i)) #the lambda function b is called with the iteration v
ariable i
Output:
Enter the number:10
10 X 1 = 10
10 X 2 = 20
10 X 3 = 30
10 X 4 = 40
10 X 5 = 50
10 X 6 = 60
10 X 7 = 70
10 X 8 = 80
10 X 9 = 90
10 X 10 = 100
The lambda function is commonly used with Python's built-
in filter() and map() functions.
Use lambda function with filter()
The Python built-in filter() function accepts a function and a list as
arguments. It provides an effective way to filter out all elements of the
sequence. It returns the new sequence in which the function evaluates
to True.
Consider the following example where we filter out only the odd number
from the given list.
#program to filter out the tuple which contains odd numbers
lst = (10,22,37,41,100,123,29)
oddlist = tuple(filter(lambda x:(x%3 == 0),lst)) # the tuple contains all the it
ems of the tuple for which the lambda function evaluates to true
print(oddlist)
Output:
(37, 41, 123, 29)
Using lambda function with map()
The map() function in Python accepts a function and a list. It gives a new
list that contains all modified items returned by the function for each item.

170
Python Programming

Consider the following example of map() function.


#program to filter out the list which contains odd numbers
lst = (10,20,30,40,50,60)
square_list = list(map(lambda x:x**2,lst)) # the tuple contains all the items
of the list for which the lambda function evaluates to true
print(square_tuple)
Output:
(100, 400, 900, 1600, 2500, 3600)

171
Python Programming

CHAPTER 9
FILE SYSTEM
9.1 FILE SYSTEM
Access to your file system occurs mostly through the Python os module.
This module serves as the primary interface to your operating system
facilities and services from Python. The os module is actually a front-end
to the real module that is loaded, a module that is clearly operating
system-dependent. This "real" module may be one of the following: posix
(Unix), nt (Windows), mac (Macintosh), dos (DOS), os2 (OS/2), etc. You
should never import those modules directly. Just import os and the
appropriate module will be loaded, keeping all the underlying work hidden
from sight. Depending on what your system supports, you may not have
access to some of the attributes which may be available in other operating
system modules.
In addition to managing processes and the process execution environment,
the os module performs most of the major file system operations that the
application developer may wish to take advantage of. These features
include removing and renaming files, traversing the directory tree, and
managing file accessibility. Lists some of the more common file or directory
operations available to you from the osmodule.
A second module that performs specific pathname operations is also
available. The os.path module is accessible through the os module.
Included with this module are functions to manage and manipulate file
pathname components, obtain file or directory information, and make file
path inquiries. outlines some of the more common functions in os.path.
These two modules allow for consistent access to the file system regardless
of platform or operating system. The program in(ospathex.py) test drives
some of these functions from the osand os.pathmodules.
Table 9.1osModule File/Directory Access Functions
osModule File/Directory Function Operation
File Processing
remove()/unlink() delete file
rename() rename file
*stat()[a] return file statistics
symlink() create symbolic link
utime() update timestamp
Directories/Folders
chdir() change working directory

172
Python Programming

listdir() list files in directory

getcwd() return current working


directory
mkdir()/makedirs() create directory(ies)
rmdir()/removedirs() remove directory(ies)
File Execution
Whether we want to simply run an operating system command, invoke a
binary executable, or another type of script (perhaps a shell script, Perl, or
Tcl/Tk), this involves executing another file somewhere else on the system.
Even running other Python code may call for starting up another Python
interpreter, although that may not always be the case. In any regard, we
will defer this subject to. Please proceed there if you are interested in how
to start other programs, perhaps even communicating with them, and for
general information regarding Python's execution environment.
9.2 PERSISTENT STORAGE MODULES, RELATED MODULES
Persistent Storage Modules
In many of the exercises in this text, user input is required for those
applications. After many iterations, it may be somewhat frustrating being
required to enter the same data repeatedly. The same may occur if you are
entering a significant amount of data for use in the future. This is where it
becomes useful to have persistent storage, or a way to archive your data so
that you may access it at a later time instead of having to re-enter all of
that information. When simple disk files are no longer acceptable and full
relational database management systems (RDBMSs) are overkill, simple
persistent storage fills the gap. The majority of the persistent storage
modules deals with storing strings of data, but there are ways to archive
Python objects as well.
pickle and marshal Modules
Python provides a variety of modules which implement minimal persistent
storage. One set of modules (marshal and pickle) allows for pickling of
Python objects. Pickling is the process whereby objects more complex than
primitive types can be converted to a binary set of bytes that can be stored
or transmitted across the network, then be converted back to their original
object forms. Pickling is also known as flattening, serializing, or
marshalling. Another set of modules (dbhash/bsddb, dbm, gdbm,
dumbdbm) and their "manager" (anydbm) can provide persistent storage of
Python strings only. The last module (shelve) can do both.
As we mentioned before, both marshal and pickle can flatten Python
173
Python Programming

objects. These modules do not provide "persistent storage" per se, since
they do not provide a namespace for the objects, nor can they provide
concurrent write access to persistent objects. What they can do, however,
is to pickle Python objects to allow them to be stored or transmitted.
Storage, of course, is sequential in nature (you store or transmit objects
one after another). The difference between marshal and pickle is that
marshal can handle only simple Python objects (numbers, sequences,
mapping, and code) while pickle can transform recursive objects, objects
that are multi-referenced from different places, and user-defined classes
and instances. The pickle module is also available in a turbo version called
cPickle,which implements all functionality in C.
DBM-style Modules
The *db* series of modules writes data in the traditional DBM format.
There are a large number of different implementations: dbhash/bsddb,
dbm, gdbm, and dumbdbm. We highly recommend the use of the anydbm
module, which detects which DBM-compatible modules are installed on
your system and uses the "best" one at its disposal. The dumbdbm module
is the most limited one, and is the default used if none of the other
packages are available. These modules do provide a namespace for your
objects, using objects which behave similar to a combination of a
dictionary object and a file object. The one limitation of these systems is
that they can store only strings. In other words, they do not serialize
Python objects.
Shelve Module
Finally, we have a somewhat more complete solution, the shelve module.
The shelve module uses the anydbm module to find a suitable DBM
module, then uses cPickle to perform the pickling process. The shelve
module permits concurrent read access to the database file, but not
shared read/write access. This is about as close to persistent storage as
you will find in the Python standard library. There may other external
extension modules which implement "true" persistent storage. The diagram
shows the relationship between the pickling modules and the persistent
storage modules, and how the shelve object appears to be the best of both
worlds.

174
Python Programming

Figure : 9.1 Python Modules for Serialization and Persistency


Related Modules
There are plenty of other modules related to files and input/output, all of
which work on most of the major platforms. lists some of the file-related
modules.
Table 9.2 Related File Modules
Module(s) Contents
Fileinput iterates over lines of multiple input text files
Getopt provides command-line argument parsing/manipulation
glob/fnmatch provides Unix-style wildcard character matching
gzip/zlib/zipfile[a] allows file access to include automatic de/compression
Shutil offers high-level file access functionality
c/StringIO implements file-like interface on top of string objects
Tempfile generates temporary file names or files

The fileinput module iterates over a set of input files and reads their
contents one line at a time, allowing you to iterate over each line, much
like the way the Perl ( < > ) operator works without any provided
175
Python Programming

arguments. File names that are not explicitly given will be assumed to be
provided from the command-line.
The glob and fnmatch modules allow for file name pattern-matching in the
good old fashioned Unix shell-style, for example, using the asterisk ( * )
wildcard character for all string matches and the ( ? ) for matching single
characters.
The gzip and zlib modules provide direct file access to the zlib compression
library. The gzip module, written on top of the zlib module, allows for
standard file access, but provides for automatic gzip-compatible
compression and decompression. Note that if you are compiling your
Python interpreter, you have to enable the zlib module to be built (by
editing the Modules/Setup file). It is not turned on by default. The new
zipfile module, also requiring the zlib module, allows the programmer to
create, modify, and read ziparchive files.
The shutil module furnishes high-level file access, performing such
functions as copying files, copying file permissions, and recursive directory
tree copying, to name a few.
The tempfile module can be used to generate temporary file names and
files. In our earlier chapter on strings, we described the StringIO module
(and its C-compiled companion cStringIO), and how it overlays a file
interface on top of string objects. This interface includes all of the standard
methods available to regular file objects.
The modules we mentioned in the Persistent Storage section above include
examples of a hybrid file- and dictionary-like object.Some other Python
modules which generate file-like objects include network and file socket
objects (socket module), the popen*() file objects that connect your
application.
9.3 EXCEPTIONS:
EXCEPTIONS IN PYTHON, DETECTING AND HANDLING EXCEPTIONS,
CONTEXT EXCEPTIONS
Python provides two very important features to handle any unexpected
error in your Python programs and to add debugging capabilities in them −
 Exception Handling − This would be covered in this tutorial. Here is a list
standard Exceptions available in Python: Standard Exceptions.
 Assertions − This would be covered in Assertions in Pythontutorial.
List of Standard Exceptions −
Sr.No. Exception Name & Description

1 Exception

176
Python Programming

Base class for all exceptions

2 StopIteration
Raised when the next() method of an iterator does not point to any
object.

3 SystemExit
Raised by the sys.exit() function.

4 StandardError
Base class for all built-in exceptions except StopIteration and
SystemExit.

5 ArithmeticError
Base class for all errors that occur for numeric calculation.

6 OverflowError
Raised when a calculation exceeds maximum limit for a numeric type.

7 FloatingPointError
Raised when a floating point calculation fails.

8 ZeroDivisionError
Raised when division or modulo by zero takes place for all numeric
types.

9 AssertionError
Raised in case of failure of the Assert statement.

10 AttributeError
Raised in case of failure of attribute reference or assignment.

11 EOFError
Raised when there is no input from either the raw_input() or input()
function and the end of file is reached.

12 ImportError
Raised when an import statement fails.

13 KeyboardInterrupt
Raised when the user interrupts program execution, usually by pressing

177
Python Programming

Ctrl+c.

14 LookupError
Base class for all lookup errors.

15 IndexError
Raised when an index is not found in a sequence.

16 KeyError
Raised when the specified key is not found in the dictionary.

17 NameError
Raised when an identifier is not found in the local or global namespace.

18 UnboundLocalError
Raised when trying to access a local variable in a function or method but
no value has been assigned to it.

19 EnvironmentError
Base class for all exceptions that occur outside the Python environment.

20 IOError
Raised when an input/ output operation fails, such as the print
statement or the open() function when trying to open a file that does not
exist.

21 IOError
Raised for operating system-related errors.

22 SyntaxError
Raised when there is an error in Python syntax.

23 IndentationError
Raised when indentation is not specified properly.

24 SystemError
Raised when the interpreter finds an internal problem, but when this
error is encountered the Python interpreter does not exit.

25 SystemExit
Raised when Python interpreter is quit by using the sys.exit() function. If

178
Python Programming

not handled in the code, causes the interpreter to exit.

26 TypeError
Raised when an operation or function is attempted that is invalid for the
specified data type.

27 ValueError
Raised when the built-in function for a data type has the valid type of
arguments, but the arguments have invalid values specified.

28 RuntimeError
Raised when a generated error does not fall into any category.

29 NotImplementedError
Raised when an abstract method that needs to be implemented in an
inherited class is not actually implemented.
Exceptions can best be described as action that is taken outside of the
normal flow of control because of errors. This action comes in two distinct
phases, the first being the error which causes an exception to occur, and
the second being the detection (and possible resolution) phase.
The first phase takes place when an exception condition (sometimes
referred to as exceptional condition) occurs. Upon detection of an error and
recognition of the exception condition, the interpreter performs an
operation called raising an exception. Raising is also known as triggering,
throwing, or generating, and is the process whereby the interpreter makes
it known to the current control flow that something is wrong. Python also
supports the ability of the programmer's to raise exceptions. Whether
triggered by the Python interpreter or the programmer, exceptions signal
that an error has occurred. The current flow of execution is interrupted to
process this error and take appropriate action, which happens to be the
second phase.
The second phase is where exception handling takes place. Once an
exception is raised, a variety of actions can be invoked in response to that
exception. These can range anywhere from ignoring the error, logging the
error but otherwise taking no action, performing some corrective measures
and aborting the program, or alleviating the problem to allow for
resumption of execution. Any of these actions represents a continuation, or
an alternative branch of control. The key is that the programmer can
dictate how the program operates when an error occurs.
As you may have already concluded, errors during run-time are primarily
179
Python Programming

caused by external reasons, such as poor input, a failure of some sort, etc.
These causes are not under the direct control of the programmer, who can
anticipate only a few of the errors and code the most general remedies.
Languages like Python which support the raising and—more importantly—
the handling of exceptions empowers the developer by placing them in a
more direct line of control when errors occur. The programmer not only
has the ability to detect errors, but also to take more concrete and
remedial actions when they occur. Due to the ability to manage errors
during run-time, application robustness is increased.
Detecting and Handling Exceptions
Exceptions can be detected by incorporating them as part of a try
statement. Any code suite of a try statement will be monitored for
exceptions.
There are two main forms of the try statement: try-except and try-finally.
These statements are mutually exclusive, meaning that you pick only one
of them. A try statement is either accompanied by one or more except
clauses or exactly one finally clause. (There is no such thing as a hybrid
"try-except-finally.")
try-except statements allow one to detect and handle exceptions. There is
even an optional else clause for situations where code needs to run only
when no exceptions are detected. Meanwhile, try-finally statements allow
only for detection and processing of any obligatory clean-up (whether or
not exceptions occur), but otherwise has no facility in dealing with
exceptions.
try-except Statement
The try-except statement (and more complicated versions of this
statement) allows you to define a section of code to monitor for exceptions
and also provides the mechanism to execute handlers for exceptions.
The syntax for the most general try-exceptstatement looks like this:
try:
try_suite # watch for exceptions here

Exception:
Let us give one example, then explain how things work. We will use our
IOError example from above. We can make our code more robust by
adding a try-except "wrapper" around the code:
>>> try:
… f = open('blah')
… except IOError:
… print 'could not open file'

180
Python Programming


could not open file
As you can see, our code now runs seemingly without errors. In actuality,
the same IOError still occurred when we attempted to open the
nonexistent file. The difference? We added code to both detect and handle
the error. When the IOError exception was raised, all we told the
interpreter to do was to output a diagnostic message. The program
continues and does not "bomb out" as our earlier example—a minor
illustration of the power of exception handling. So what is really happening
codewise?
During run-time, the interpreter attempts to execute all the code within
the try statement. If an exception does not occur when the code block has
completed, execution resumes past the except statement. When the
specified exception named on the except statement does occur, control
flow immediately continues in the handler (all remaining code in the try
clause is skipped). In our example above, we are catching only IOError
exceptions. Any other exception will not be caught with the handler we
specified. If, for example, you want to catch an OSError, you have to add a
handler for that particular exception. We will elaborate on the try-except
syntax more as we progress further in this chapter.
9.4 EXCEPTIONS AS STRINGS
Prior to Python 1.5, standard exceptions were implemented as strings.
However, this became limiting in that it did not allow for exceptions to
have any relationships to each other. With the advent of exception classes,
this is no longer the case. As of 1.5, all standard exceptions are now
classes. It is still possible for programmers to generate their own
exceptions as strings, but we recommend using exception classes from
now on.
For backwards compatibility, it is possible to revert to string-based
exceptions. Starting the Python interpreter with the command-line option -
X will provide you with the standard exceptions as strings. This feature will
be obsoleted beginning with Python 1.6.
If you must use string exceptions, we will now show you how to do it right.
The following piece of code may or may not work:
# this may not work… risky!
try:
raise 'myexception'
:
except 'myexception'
suite_to_handle_my_string_exception

181
Python Programming

except:
suite_for_other_exceptions
The reason why the above code may not work is because exceptions are
based on object identity as opposed to object value. There are two different
string objects above, both with the same value. To rectify the potential
problem, create a static string object with which to use:
# this is a little bit better
myexception = 'myexception' try:
raise myexception
except myexception:
suite_to_handle_my_string_exception
except:
suite_for_other_exceptions
Raising Exceptions
The interpreter was responsible for raising all of the exceptions which we
have seen so far. These exist as a result of encountering an error during
execution. A programmer writing an API may also wish to throw an
exception on erroneous input, for example, so Python provides a
mechanism for the programmer to explicitly generate an exception: the
raisestatement.
raise Statement
The raise statement is quite flexible with the arguments which it supports,
translating to a large number of different formats supported syntactically.
The general syntax for raise is:
raise [Exception [, args [, traceback]]]
The first argument, Exception, is the name of the exception to raise. If
present, it must either be a string, class, or instance (more below).
Exception must be given if any of the other arguments (arguments or
traceback) are present. A list of all Python standard exceptions is given in
table.
The second expression contains optional args (a.k.a. parameters, values)
for the exception. This value is either a single object or a tuple of objects.
When exceptions are detected, the exception arguments are always
returned as a tuple. If args is a tuple, then that tuple represents the same
set of exception arguments which are given to the handler. If args is a
single object, then the tuple will consist solely of this one object (i.e., a
tuple with one element). In most cases, the single argument consists of a
string indicating the cause of the error. When a tuple is given, it usually
equates to an error string, an error number, and perhaps an error location,
such as a file, etc.

182
Python Programming

The final argument, traceback, is also optional (and rarely used in


practice), and, if present, is the traceback object used for the exception—
normally a traceback object is newly created when an exception is raised.
This third argument is useful if you want to re-raise an exception (perhaps
to point to the previous location from the current). Arguments which are
absent are represented by the value None.
Table 9.3: Using the raiseStatement
raisesyntax Description
raise exclass raise an exception, creating an instance of exclass(without any
exception arguments)
raise same as above since classes are now exceptions; invoking the
exclass() class name with the function call operator instantiates an
instance
of exclass, also with no arguments
raise exclass, same as above, but also providing exception arguments args,
args which can be a single argument or a tuple
raise same as above
exclass(args)
raise exclass, same as above, but provides traceback object tbto use
args, tb
raise exclass, raise exception using instance(normally an instance of exclass);
instance if instance is an instance of a subclass of exclass, then the new
exception will be of the subclass type (not of exclass type); if
instance is not an instance of exclass nor an instance of a
subclass of exclass, then a new instance of exclass will be
created with exception arguments copied from instance
raise instance raise exception using instance:the exception type is the class
which instantiated instance; equivalent to raise
9.5 ASSERTIONS
Assertions in Python
An assertion is a sanity-check that you can turn on or turn off when you
are done with your testing of the program.
The easiest way to think of an assertion is to liken it to a raise-if statement
(or to be more accurate, a raise-if-not statement). An expression is tested,
and if the result comes up false, an exception is raised. Assertions are
carried out by the assert statement, the newest keyword to Python,
introduced in version 1.5. Programmers often place assertions at the start
of a function to check for valid input, and after a function call to check for
valid output.

183
Python Programming

The assert Statement


When it encounters an assert statement, Python evaluates the
accompanying expression, which is hopefully true. If the expression is
false, Python raises an AssertionError exception.
The syntax for assert is −
assert Expression[, Arguments]
If the assertion fails, Python uses ArgumentExpression as the argument
for the AssertionError. AssertionError exceptions can be caught and
handled like any other exception using the try-except statement, but if not
handled, they will terminate the program and produce a traceback.
Assertions are diagnostic predicates which must evaluate to Boolean true;
otherwise, an exception is raised to indicate that the expression is false.
These work similarly to the assert macros which are part of the C language
preprocessor, but in Python these are run- time constructs (as opposed to
pre-compile directives).
If you are new to the concept of assertions, no problem. The easiest way to
think of an assertion is to liken it to a raise-if statement (or to be more
accurate, a raise-if-not statement). An expression is tested, and if the
result comes up false, an exception is raised.
Assertions are carried out by the assert statement, the newest keyword to
Python, introduced in version 1.5.
assert Statement
The assert statement evaluates a Python expression, taking no action if
the assertion succeeds (similar to a pass statement), but otherwise raises
an AssertionError exception. The syntax for assertis:assert arguments]
Here are some examples of the use of the assertstatement:
assert 1 == 1
assert (2 + 2) == (2 * 2)
assert len(['my list', 12]) < 10
assert range(3) == [0, 1, 2]
Standard Exceptions
All exceptions are loaded into the interpreter as a built-in so they are ready
before your script starts or by the time you receive the interpreter prompt,
if running interactively.
All standard/built-in exceptions are derived from the root class Exception.
There are currently two immediate subclasses of Exception: SystemExit
and StandardError. All other built-in exceptions are subclasses of
StandardError. Every level of indentation of an exception indicates one
level of exception class derivation.

184
Python Programming

Table 3.4. Python Standard Exceptions


Exception Name Description
Exception[a] root class for all exceptions
SystemExit request termination of Python interpreter
StandardError[a] base class for all standard built-in exceptions
ArithmeticError[a] base class for all numeric calculation errors
FloatingPointError[a] error in floating point calculation
OverflowError calculation exceeded maximum limit for numerical
type
ZeroDivisionError division (or modulus) by zero error (all numeric types)
AssertionError[a] failure of assert statement
AttributeError no such object attribute
EOFError end-of-file marker reached without input from built-in
EnvironmentError[b] base class for operating system environment errors
IOError failure of input/output operation
OSError[b] operating system error
WindowsError[c] MS Windows system call failure
ImportError failure to import module or object
KeyboardInterrupt user interrupted execution (usually by typing ^C)
LookupError[a] base class for invalid data lookup errors
IndexError no such index in sequence
KeyError no such key in mapping
MemoryError out-of-memory error (non-fatal to Python interpreter)
NameError undeclared/uninitialized object (non-attribute)
UnboundLocalError[c] access of an uninitialized local variable
RuntimeError generic default error during execution
NotImplementedError[b] unimplemented method
SyntaxError error in Python syntax
IndentationError[d] improper indentation
TableError[d] improper mixture of TABs and spaces
SystemError generic interpreter system error
TypeError invalid operation for type
9.6 CREATING EXCEPTIONS
Although the set of standard exceptions is fairly wide-ranging, it may be
advantageous to create your own exceptions. One situation is where you

185
Python Programming

would like additional information from what a standard or module-specific


exception provides. We will present two examples, both related to IOError.
IOError is a generic exception used for input/output problems which may
arise from invalid file access or other forms of communication. Suppose we
wanted to be more specific in terms of identifying the source of the
problem. For example, for file errors, we want to have a FileError exception
which behaves like IOError, but with a name that has more meaning when
performing file operations.
Another exception we will look at is related to network programming with
sockets. The exception generated by the socket module is called
socket.error and is not a built-in exception. It is subclassed from the
generic Exception exception. However, the exception arguments from
socket.error closely resemble those of IOError exceptions, so we are going
to define a new exception called NetworkError which subclasses from
IOErrorbut contains at least the information provided by socket.error.
Why Exceptions (Now)?
There is no doubt that errors will be around as long as software is around.
The difference in today's fast-paced computing world is that our execution
environments have changed, and so has our need to adapt error-handling
to accurately reflect the operating context of the software which we
develop. Modern-day applications generally run as self-contained graphical
user interfaces (GUIs) or in a client-server architecture such as the Web.
The ability to handle errors at the application level has become even more
important recently in that users are no longer the only ones directly
running applications. As the Internet and online electronic commerce
become more pervasive, web servers will be the primary users of
application software. This means that applications cannot just fail orcrash
outright anymore, because if they do, system errors translate to browser
errors, and these in turn lead to frustrated users. Losing eyeballs means
losing advertising revenue and potentially significant amounts of
irrecoverable business.
If errors do occur, they are generally attributed to some invalid user input.
The execution environment must be robust enough to handle the
application-level error and be able to produce a user-level error message.
This must translate to a "non-error" as far as the web server is concerned
because the application must complete successfully, even if all it does is
return an error message to present to the user as a valid hypertext markup
language (HTML) web page displaying the error.
If you are not familiar with what I am talking about, does a plain web
browser screen with the big black words saying, "Internal Server Error"

186
Python Programming

sound familiar? How about a fatal error that brings up a pop-up that
declares "Document contains no data"? As a user, do either of these
phrases mean anything to you? No, of course not (unless you are an
Internet software engineer), and to the average user, they are an endless
source of confusion and frustration. These errors are a result of a failure in
the execution of an application. The application either returns invalid
hypertext transfer protocol (HTTP) data or terminates fatally, resulting in
the web server throwing its hands up into the air, saying, "I give up!"
This type of faulty execution should not be allowed, if at all possible. As
systems become more complex and involve more apprentice users,
additional care should be taken to ensure a smooth user application
experience. Even in the face of an error situation, an application should
terminate successfully, as to not affect its execution environment in a
catastrophic way. Python's exception handling promotes mature and
correct programming.
Why Exceptions at All?
If the above section was not motivation enough, imagine what Python
programming might be like without program-level exception handling. The
first thing that comes to mind is the loss of control client programmers
have over their code. For example, if you created an interactive application
which allocates and utilizes a large number of resources, if a user hit ^C or
other keyboard interrupt, the application would not have the opportunity
to perform clean-up, resulting in perhaps loss of data, or data corruption.
There is also no mechanism to take alternative action such as prompting
the users to confirm whether they really want to quit or if they hit the
control key accidentally.
Another drawback would be that functions would have to be rewritten to
return a "special" value in the face of an error situation, for example, None.
The engineer would be responsible for checking each and every return
value from a function call. This may be cumbersome because you may
have to check return values which may not be of the same type as the
object you are expecting if no errors occurred. And what if your function
wants to return None as a valid data value? Then you would have to come
up with another return value, perhaps a negative number. We probably do
not need to remind you that negative numbers may be valid in a Python
context, such as an index into a sequence. As a programmer of
application programmer interfaces (APIs), you would then have
todocument every single return error your users may encounter based on
the input received. Also, it is difficult (and tedious) to propagate errors (and
reasons) of multiple layers of code.

187
Python Programming

There is no simple propagation like the way exceptions do it. Because error
data needs to be transmitted upwards in the call hierarchy, it is possible to
misinterpret the errors along the way. A totally unrelated error may be
stated as the cause when in fact it had nothing to do with the original
problem to begin with. We lose the bottling-up and safekeeping of the
original error that exceptions provide as they are passed from layer to
layer, not to mention completely losing track of the data we were originally
concerned about! Exceptions simplify not only the code, but the entire
error management scheme which should not play such a significant role in
application development. And with Python's exception handling
capabilities, it does not have to.
9.7 THE SYS MODULE
An alternative way of obtaining exception information is by accessing the
exc_info() function in the sys module. This function provides a 3-tuple of
information, more than what we can achieve by simply using only the
exception argument. Let us see what we get using sys.exc_info():
>>> try:
… float('abc123')
… except:
… import sys
… exc_tuple = sys.exc_info()

>>> print exc_tuple
(<class exceptions.ValueError at f9838>, <exceptions.ValueError instance
at 122fa8>,
<traceback object at 10de18>)
>>>
>>> for eachItem in exc_tuple:
… print eachItem
… exceptions.ValueError
invalid literal for float(): abc123
<traceback object at 10de18>
What we get from sys.exc_info()in a tuple are:
exception class object
(this) exception class instance object traceback object
The first two items we are familiar with: the actual exception class and this
particular exception's instance (which is the same as the exception
argument which we discussed in the previous section). The third item, a
traceback object, is new. This object provides the execution context of
where the exception occurred. It contains information such as the

188
Python Programming

execution frame of the code that was running and the line number where
the exception occurred.
In older versions of Python, these three values were available in the sys
module as sys.exc_type, sys.exc_value, and sys.exc_traceback.
Unfortunately, these three are global variables and not thread-safe. We
recommend using sys.exc_info()instead.
Related Modules
The classes found in module Lib/exceptions.py are automatically loaded as
built-in names on start-up, so no explicit import of this module is ever
necessary. We recommend you take a look at this source code to
familiarize yourself with Python's exceptions and how they interrelate and
interoperate. Starting with 2.0, exceptions are now built into the
interpreter (see Python/exceptions.c).
9.8 MODULES
Modules and Files, Namespaces, Importing Modules, Importing
Module Attributes
Modules:
A module allows you to logically organize your Python code. Grouping
related code into a module makes the code easier to understand and use.
A module is a Python object with arbitrarily named attributes that you can
bind and reference.
Simply, a module is a file consisting of Python code. A module can define
functions, classes and variables. A module can also include runnable code.
Example
The Python code for a module named aname normally resides in a file
named aname.py. Here's an example of a simple module, support.py
def print_func( par ):
print "Hello : ", par
return
The import Statement
You can use any Python source file as a module by executing an import
statement in some other Python source file. The import has the following
syntax −
import module1[, module2[,... moduleN]
A module is loaded only once, regardless of the number of times it is
imported. This prevents the module execution from happening over and
over again if multiple imports occur.

189
Python Programming

The from...import Statement


Python's from statement lets you import specific attributes from a module
into the current namespace. The from...import has the following syntax −
from modname import name1[, name2[, ... nameN]]
For example, to import the function fibonacci from the module fib, use the
following statement −
from fib import fibonacci
This statement does not import the entire module fib into the current
namespace; it just introduces the item fibonacci from the module fib into
the global symbol table of the importing module.
The from...import * Statement
It is also possible to import all names from a module into the current
namespace by using the following import statement −
from modname import *
This provides an easy way to import all the items from a module into the
current namespace; however, this statement should be used sparingly.
Locating Modules
When you import a module, the Python interpreter searches for the module
in the following sequences −
 The current directory.
 If the module isn't found, Python then searches each directory in the shell
variable PYTHONPATH.
 If all else fails, Python checks the default path. On UNIX, this default path
is normally /usr/local/lib/python/.
The module search path is stored in the system module sys as
the sys.pathvariable. The sys.path variable contains the current directory,
PYTHONPATH, and the installation-dependent default.
Namespaces and Scoping
Variables are names (identifiers) that map to objects. A namespace is a
dictionary of variable names (keys) and their corresponding objects
(values).
A Python statement can access variables in a local namespace and in
the global namespace. If a local and a global variable have the same name,
the local variable shadows the global variable.
Each function has its own local namespace. Class methods follow the
same scoping rule as ordinary functions.
Python makes educated guesses on whether variables are local or global. It
assumes that any variable assigned a value in a function is local.

190
Python Programming

Therefore, in order to assign a value to a global variable within a function,


you must first use the global statement.
The statement global VarName tells Python that VarName is a global
variable. Python stops searching the local namespace for the variable.
For example, we define a variable Money in the global namespace. Within
the function Money, we assign Money a value, therefore Python
assumes Moneyas a local variable. However, we accessed the value of the
local variable Moneybefore setting it, so an UnboundLocalError is the
result. Uncommenting the global statement fixes the problem.
#!/usr/bin/python
Money = 2000
def AddMoney():
# Uncomment the following line to fix the code:
# global Money
Money = Money + 1
print Money
AddMoney()
print Money
The dir( ) Function
The dir() built-in function returns a sorted list of strings containing the
names defined by a module.
The list contains the names of all the modules, variables and functions
that are defined in a module. Following is a simple example −
#!/usr/bin/python
# Import built-in module math
import math
content = dir(math)
print content
When the above code is executed, it produces the following result −
['__doc__', '__file__', '__name__', 'acos', 'asin', 'atan',
'atan2', 'ceil', 'cos', 'cosh', 'degrees', 'e', 'exp',
'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log',
'log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh',
'sqrt', 'tan', 'tanh']
Here, the special string variable __name__ is the module's name,
and __file__is the filename from which the module was loaded.

191
Python Programming

The globals() and locals() Functions


The globals() and locals() functions can be used to return the names in the
global and local namespaces depending on the location from where they
are called.
If locals() is called from within a function, it will return all the names that
can be accessed locally from that function.
If globals() is called from within a function, it will return all the names that
can be accessed globally from that function.
The return type of both these functions is dictionary. Therefore, names can
be extracted using the keys() function.
The reload() Function
When the module is imported into a script, the code in the top-level
portion of a module is executed only once.
Therefore, if you want to reexecute the top-level code in a module, you can
use the reload() function. The reload() function imports a previously
imported module again. The syntax of the reload() function is this −
reload(module_name)
Here, module_name is the name of the module you want to reload and not
the string containing the module name. For example, to
reload hello module, do the following −
reload(hello)
Packages in Python
A package is a hierarchical file directory structure that defines a single
Python application environment that consists of modules and subpackages
and sub-subpackages, and so on.
Consider a file Pots.py available in Phone directory. This file has following
line of source code −
#!/usr/bin/python
def Pots():
print "I'm Pots Phone"
Similar way, we have another two files having different functions with the
same name as above −
 Phone/Isdn.py file having function Isdn()
 Phone/G3.py file having function G3()
Now, create one more file __init__.py in Phone directory −
 Phone/__init__.py
To make all of your functions available when you've imported Phone, you
need to put explicit import statements in __init__.py as follows −

192
Python Programming

from Pots import Pots


from Isdn import Isdn
from G3 import G3
After you add these lines to __init__.py, you have all of these classes
available when you import the Phone package.
#!/usr/bin/python
# Now import your Phone Package.
import Phone
Phone.Pots()
Phone.Isdn()
Phone.G3()
When the above code is executed, it produces the following result −
I'm Pots Phone
I'm 3G Phone
I'm ISDN Phone

In the above example, we have taken example of a single functions in each


file, but you can keep multiple functions in your files. You can also define
different Python classes in those files and then you can create your
packages out of those classes.

193
Python Programming

CHAPTER 10
REGULAR EXPRESSIONS, SYMBOLS AND CHARACTERS
10.1 EXPRESSIONS
A regular expression is a special sequence of characters that helps you
match or findother strings or sets of strings, using a specialized syntax
held in a pattern. Regular expressions are widely used in UNIX world. The
module re provides full support for Perl-like regular expressions i n
Python. The re module raises the exception re.error if an error occurs
while compiling or using a regular expression.
We would cover two important functions, which would be used to handle
regular expressions. Nevertheless, a small thing first: There are various
characters, which would have special meaning when they are used in
regular expression.
To avoid any confusion while dealing with regular expressions, we would
use Raw Strings as r'expression'
Table 10.1

Sr.No. Expression & Matches

1 a, X, 9, <ordinary characters just match themselves exactly.

2 . (a period) matches any single character except newline '\n'

3 \w matches a "word" character: a letter or digit or underbar [a-zA-


Z0-9_].

4 \W matches any non-word character.

5 \b boundary between word and non-word

6 \s matches a single whitespace character -- space, newline, return,


tab

7 \S matches any non-whitespace character.

194
Python Programming

8 \t, \n, \r tab, newline, return

9 \d decimal digit [0-9]

10 ^ matches start of the string

11 $ match the end of the string

12 \ inhibit the "specialness" of a character.

REs and Python


The re module was introduced to Python in version 1.5 re Module: Core
Functions and Methods
the more popular functions and methods from the re module.
Many of these functions are also available as methods of compiled regular
expression objects "regex objects" and RE "match objects." In this
subsection, we will look at the two main functions/methods, match() and
search(), as well as the compile() function.
We will introduce several more in the next section, but for more
information on all these and the others which we do not cover, we refer
you to the Python documentation
Compiling REs with compile()
Almost all of the re module functions we will be describing shortly are
available as methods for regex objects. Remember, even with our
recommendation, precompilation is not required. If you compile, you will
use methods; if you don't, you will just use functions. The good news is
that either way, the names are the same whether a function or a method.
(This is the reason why there are module functions and methods which are
identical, i.e., search(), match(), etc., in case you were wondering.) Since it
saves one small step for most of our examples, we will use strings instead.
We will throw in a few with compilation though just so you know how it is
done. Optional flags may be given as arguments for specialized
compilation. These flags allow for case-insensitive matching, using system
locale settings for matching alphanumeric characters, etc. Please refer to
the documentation for more details. These flags, some of which have been
briefly mentioned (i.e. DOTALL, LOCALE), may also be given to the module

195
Python Programming

versions of match() and search() for a specific pattern match attempt—


these flags are mostly for compilation reasons, hence the reason why they
can be passed to the module versions of match() and search() which do
compile an RE pattern once. If you want to use these flags with the
methods, they must already be integrated into the compiled regex objects.
In addition to the methods below, regex objects also have some data
attributes, two of which include any compilation flags given as well as the
regular expression pattern compiled.
Match objects and the group() and groups() Methods
There is another object type in addition to the regex object when dealing
with regular expressions, the match object. These objects are those which
are returned on successful calls to match() or search(). Match objects have
two primary methods, group() and groups(). group() will either return the
entire match, or a specific subgroup, if requested. groups() will simply
return a tuple consisting of only/all the subgroups. If there are no
subgroups requested, then groups() returns an empty tuple while group()
still returns the entire match. Python REs also allow for named matches,
which are beyond the scope of this introductory section on REs. We refer
you to the complete re module documentation regarding all the more
advanced details we have omitted here.
Matching strings with match()
match() is the first re module function and RE object (regex object) method
we will look at. The match() function attempts to match the pattern to the
string, starting at the beginning. If the match is successful, a match object
is returned, but on failure, None is returned. The group() method of a
match object can be used to show the successful match. Here is an
example of how to use match() [and group()]:
>>> m = re.match('foo', 'foo') # pattern matches string
>>> if m != None: # show match if successful
… m.group()

`foo'
The pattern "foo" matches exactly the string "foo." We can also confirm that
m is an example of a match object from within the interactive interpreter:
>>> m # confirm match
10.2 MULTITHREADED PROGRAMMING
Introduction, Threads and Processes, Python
MT programming is ideal for programming tasks that are asynchronous in
nature, require multiple concurrent activities, and where the processing of
each activity may be nondeterministic, i.e., random and unpredictable.

196
Python Programming

Such programming tasks can be organized or partitioned into multiple


streams of execution where each has a specific task to accomplish.
Depending on the application, these subtasks may calculate intermediate
results that could be merged into a final piece of output. While CPU-bound
tasks may be fairly straightforward to divide into subtasks and executed
sequentially or in a multithreaded manner, the task of managing a single
threaded process with multiple external sources of input is not as trivial.
A programming task without multithreading, a sequential program must
use one or more timers and implement a multiplexing scheme.
A sequential program will need to sample each I/O (input/output) terminal
channel to check for user input; however, it is important that the program
does not block when reading the I/O terminal channel because the arrival
of user input is nondeterministic, and blocking would prevent processing
of other I/O channels. The sequential program must use non-blocked I/O
or blocked I/O with a timer (so that blocking is only temporary).
Because the sequential program is a single thread of execution, it must
juggle the multiple tasks that it needs to perform, making sure that it does
not spend too much time on any one task, and it must ensure that user
response time is appropriately distributed.
The use of a sequential program for this type of programming task often
results in a complicated flow of control program that is difficult to
understand and maintain.
Using an MT program with a shared data structure such as a Queue (a
multithreaded queue data structure discussed later in this chapter), this
programming task can be organized with a few threads that have specific
functions to perform:
UserRequestThread: responsible for reading client input, perhaps from an
I/O channel. A number of threads would be created by the program, one
for each current client, with requests being entered into the queue
RequestProcessor: a thread that is responsible for retrieving requests from
the queue and processing them, providing output for yet a third thread.
ReplyThread: responsible for taking output destined for the user and
either sending it back, if in a networked application, or writing data to the
local file system or database. Organizing this programming task with
multiple threads reduces the complexity of the program and enables an
implementation that is clean, efficient, and well-organized. The logic in
each thread is typically less complex because it has a specific job to do.
For example, the UserRequestThread simply reads input from a user and
places the data into a queue for further processing by another thread, etc.
Each thread has its own job to do; and you merely have to design each

197
Python Programming

type of thread to do one thing and do it well. Use of threads for specific
tasks is not unlike Henry Ford's assembly line model for manufacturing
automobiles.
Threads and Processes
What Are Processes?
Computer programs are merely executables, binary (or otherwise), which
reside on disk. They do not take on a life of their own until loaded into
memory and invoked by the operating system. A process (sometimes called
a heavyweight process) is a program in execution. Each process has its
own address space, memory, a data stack, and other auxiliary data to keep
track of execution. The operating system manages the execution of all
processes on the system, dividing the time fairly between all processes.
Processes can also fork or spawn new processes to perform other tasks,
but each new process has its own memory, data stack, etc., and cannot
generally share information unless interprocess communication (IPC) is
employed.
What Are Threads?
Threads (sometimes called lightweight processes) are similar to processes
except that they all execute within the same process, thus all share the
same context. They can be thought of as "mini-processes" running in
parallel within a main process or "main thread."
A thread has a beginning, an execution sequence, and a conclusion. It has
an instruction pointer that keeps track of where within its context it is
currently running. It can be preempted (interrupted) and temporarily put
on hold (also known as sleeping) while other threads are running—this is
called yielding.
Multiple threads within a process share the same data space with the
main thread and can therefore share information or communicate with
each other more easily than if they were separate processes. Threads are
generally executed in a concurrent fashion, and it is this parallelism and
data sharing that enable the coordination of multiple tasks. Naturally, it is
impossible to run truly in a concurrent manner in a single CPU system, so
threads are scheduled in such a way that they run for a little bit, then
yield to other threads (going to the proverbial "back-of-the-line" to await
getting more CPU time again). Throughout the execution of the entire
process, each thread performs its own, separate tasks, and communicates
the results with other threads as necessary.
Of course, such sharing is not without its dangers. If two or more threads
access the same piece of data, inconsistent results may arise because of
the ordering of data access. This is commonly known as a race condition.

198
Python Programming

Fortunately, most thread libraries come with some sort of synchronization


primitives which allow the thread manager to control execution and
access.
Another caveat is that threads may not be given equal and fair execution
time. This is because some functions block until they have completed. If
not written specifically to take threads into account, this skews the
amount of CPU time in favor of such greedy functions.
10.3 GLOBAL INTERPRETER LOCK, THREAD MODULE, THREADING
MODULE, RELATED MODULES
Global Interpreter Lock
Execution by Python code is controlled by the Python Virtual Machine
(a.k.a. the interpreter main loop), and Python was designed in such a way
that only one thread of control may be executing in this main loop, similar
to how multiple processes in a system share a single CPU. Many programs
may be in memory, but only one is live on the CPU at any given moment.
Likewise, although multiple threads may be "running" within the Python
interpreter, only one thread is being executed by the interpreter at any
given time. Access to the Python Virtual Machine is controlled by a global
interpreter lock (GIL).
This lock is what ensures that exactly one thread is running. The Python
Virtual Machine executes in the following manner in an MT environment:
Set the GIL,
Switch in a thread to run,
Execute for a specified number of bytecode instructions,
Put the thread back to sleep (switch out thread),
Unlock the GIL, and,
Do it all over again (rinse, lather, repeat).
When a call is made to external code, i.e., any C/C++ extension built-in
function, the GIL will be locked until it has completed (since there are no
Python bytecodes to count as the interval). Extension programmers do
have the ability to unlock the GIL however, so you being the Python
developer shouldn't have to worry about your Python code locking up in
those situations. As an example, for any Python I/O-oriented routines
(which invoke built-in operating system C code), the GIL is released before
the I/O call is made, allowing other threads to run while the I/O is being
performed. Code which doesn't have much I/O will tend to keep the
processor (and GIL) to the full interval a thread is allowed before it yields.
In other words, I/O-bound Python programs stand a much better chance
of being able to take advantage of a multithreaded environment than CPU-
bound code.

199
Python Programming

Those of you interested in the source code, the interpreter main loop, and
the GIL can take a look at eval_code2() routine in the Python/ceval.c file,
which is the Python Virtual Machine.
Exiting Threads
When a thread completes execution of the function they were created for,
they exit. Threads may also quit by calling an exit function such as
thread.exit(), or any of the standard ways of exiting a Python process, i.e.,
sys.exit() or raising the SystemExit exception.
There are a variety of ways of managing thread termination. In most
systems, when the main thread exits, all other threads die without
cleanup, but for some systems, they live on. Check your operating system
threaded programming documentation regarding their behavior in such
occasions.
Main threads should always be good managers, though, and perform the
task of knowing what needs to be executed by individual threads, what
data or arguments each of the spawned threads requires, when they
complete execution, and what results they provide. In so doing, those main
threads can collate the individual results into a final conclusion.
Accessing Threads From Python
Python supports multithreaded programming, depending on the operating
system that it is running on. It is supported on most versions of Unix,
including Solaris and Linux, and Windows. Threads are not currently
available on the Macintosh platform. Python uses POSIX-compliant
threads, or "pthreads," as they commonly known.

200
Python Programming

CHAPTER 11
GUI PROGRAMMING
11.1 INTRODUCTION, TKINTER AND PYTHON PROGRAMMING
GUIs, Related Modules and Other GUIs
Graphical User nterfaces:
In graphical user interface we are going to discuss about
Behavior of terminal based programs and GUI-based programs
Coding simple GUI-based programs
Other useful GUI resources
Behavior of terminal based programs and GUI-based programs:
Terminal-Based Version:
The terminal-based version of the bouncy program displays a greeting and
then a menu of command options. The user is prompted for a command
number and then enters a number from the keyboard. The program
responds by either terminating execution, prompting for the information
for a bouncing ball, or printing a message indicating an unrecognized
command. After the program processes a command, it displays the menu
again, and the same process starts over.
This terminal-based user interface has several obvious effects on its users:
 The user is constrained to reply to a definite sequence of
prompts for inputs. Once an input is entered, there is no
way to back up and change it.
 To obtain results for a different set of input data, the user
must wait for the command menu to be displayed again.
At that point, the same command and all of the other
inputs must be re-entered.
 The user can enter an unrecognized command.
Each of these effects poses a problem for users that can be solved by
converting the interface to a GUI.
GUI-Based Version:
The GUI-based version of the bouncy program displays a window that
contains various components, also called window objects or widgets. Some
of these components look like text, while others provide visual cues as to
their use. The snapshot on the left shows the interface at program start-
up, whereas the snapshot on the right shows the interface after the user
has entered inputs and selected the Compute button. This program was
run on a Macintosh; on a Windows- or Linux-based PC, the windows look
slightly different.

Other useful GUI resources:

201
Python Programming

Other useful GUI resources are


1. Colors
2. Text Attributes
3. Sizing and Justifying an Entry
4. Sizing the Main Window
5. Grid Attributes
6. Using Nested Frames to Organize Components
7. Multi-Line Text Widgets
8. Scrolling List Boxes
9. Mouse Events
10. Keyboard Events
GUI Programming:
In GUI Programming we are going to discuss about
 Graphical User Interfaces
 Using the tkinter Module
 Display text with Label Widgets
 Organizing Widgets with Frames
 Button Widgets and Info Dialog Boxes
 Getting Input with Entry Widget
 Using Labels as Output Fields
 Radio Buttons, Check Buttons
Graphical User Interfaces:
Python provides various options for developing graphical user
interfaces (GUIs). Most important are listed below.
 Tkinter − Tkinter is the Python interface to the Tk GUI toolkit
shipped with Python.
 wxPython − This is an open-source Python interface for wxWindows
 JPython − JPython is a Python port for Java which gives Python
scripts seamless access to Java class libraries on the local machine.
Using the tkinter Module:
Tkinter is the standard GUI library for Python. Python when combined
with Tkinter provides a fast and easy way to create GUI applications.
Tkinter provides a powerful object- oriented interface to the Tk GUI
toolkit.
Creating a GUI application using Tkinter is an easy task. All you need
to do is perform the following steps −
Import the Tkinter module.
eate the GUI application main window.
or more of the above-mentioned widgets to the GUI
application.
202
Python Programming

Enter the main event loop to take action against each event
triggered by the user.
Example
#!/usr/bin/python
import Tkinter
top = Tkinter.Tk()
# Code to add
widgets will go
here...
top.mainloop()
This would create a following window −

Display text with Label Widgets:


 This widget implements a display box where you can place text
or images. The text displayed by this widget can be updated at any
time you want.
 It is also possible to underline part of the text (like to identify a
keyboard shortcut) and span the text across multiple lines.
Syntax
Here is the simple syntax to create this widget −
w = Label ( master, option, ... )
Parameters
 master − This represents the parent window.
 options − Here is the list of most commonly used options for this
widget. These options can be used as key-value pairs separated by
commas.
Example
Try the following example yourself −
from Tkinter import *
root = Tk()
var = StringVar()
label = Label( root, textvariable=var, relief=RAISED )
var.set("Hey!? How are you doing?")

203
Python Programming

label.pack()
root.mainloop()
11.2 WEB PROGRAMMING
Wed surfing with Python, Creating simple web clients, Advanced web
clients:
Web Surfing: Client-Server Computing (Again?!?)
Web surfing falls under the same client-server architecture umbrella that
we have eenrepeatedly. This time, Web clients are browsers; applications
allow users to seek documents on the World Wide Web. On the other side
are Web servers, processes which run on an information provider's host
computers. These servers wait for clients and their document requests,
process them, and return the requested data. As with most servers in a
client-server system, Web servers are designed to run "forever." Clients
may issue a variety of requests to Web servers. Such requests may include
obtaining a Web page for viewing or submitting a form with data for
processing. The request is then serviced by the Web server, and the reply
comes back to the client in a special format for display purposes.
The "language" which is spoken by Web clients and servers, the standard
protocol used for Web communication, is called HTTP, which stands for
HyperText Transfer Protocol. HTTP is written "on top of" the TCP and IP
protocol suite, meaning that it relies on TCP and IP to carry out its lower-
level communication functionality. Its responsibility is not to route or
deliver messages—
TCP and IP handle that—but to respond to client requests.
HTTP is known as a "stateless" protocol because it does not keep track of
information from one client request to the next, similar to the client-server
architecture we have seen so far. The server stays running, but client
interactions are singular events structured in such a way that once a
client request is serviced, it quits. New requests can always be sent, but
they are considered separate service requests. Because of the lack of
context per request, you may notice that some URLs have a long set of
variables and values chained as part of the request to provide some sort of
state information. Another alternative is the use of "cookies"—static data
stored on the client side which generally contains state information as
well. In later parts of this chapter, we will look at how to use both long
URLs and cookies to maintain state information.
Web Surfing with Python: Creating Simple Web Clients
Uniform Resource Locators:
Simple Web surfing involves using Web addresses called Uniform Resource
Locators (URLs). Such addresses are used to locate a document on the

204
Python Programming

Web or to call a CGI program to generate a document for your client. URLs
are part of a larger set of identifiers known as URIs (Uniform Resource
Identifiers). This superset was created in anticipation of other naming
conventions which have yet to be developed. A URL is simply a URI which
uses an existing protocol or scheme (i.e., http, ftp, etc.) as part of its
addressing. To complete this picture, we'll add that non-URL URIs are
sometimes known as URNs (Uniform Resource Names), but because URLs
are the only URIs in use today.
11.3 WEB (HTTP) SERVERS
Creating Web Servers in Python
The base (Web) server is a boilerplate item, a must have. Its role is to
perform the necessary HTTP communication between client and server.
The base server is (appropriately) named HTTPServer and is found in the
BaseHTTPServer module. The handler is the piece of software which does
the majority of the "Web serving." It processes the client request and
returns the appropriate file, whether static or dynamically-generated by
CGI. The complexity of the handler determines the complexity of your Web
server. The Python standard library provides three different handlers.
The most basic, plain, vanilla handler, named BaseHTTPRequestHandler,
is found in the BaseHTTPServer module, along with the base Web server.
Other than taking a client request, no other handling is implemented at
all, so you have to do it all yourself, such as in our myhttpd.py server
below.
The SimpleHTTPRequestHandler, available in the SimpleHTTP-Server
module, builds on BaseHTTPRequestHandler by implementing the
standard GET and HEAD requests in a fairly straightforward manner. Still
nothing sexy, but it gets the simple jobs done.
Finally, we have the CGIHTTPRequestHandler, available in the
CGIHTTPServer module, which takes the SimpleHTTPRequestHandler and
adds support for POST requests. It has the ability to call CGI scripts to
perform the requested processing and can send the generated HTML back
to the client.
Related Modules
Python has plenty of modules to support most kinds of binary file encoding
for e-mail and other MIME-oriented applications. You can create clients for
common Internet protocols like HTTP, FTP, Telnet, and NNTP with the
appropriate modules. Be aware that urllib provides a high-level interface to
protocols supported by your browser such as HTTP and FTP, so use of the
lower-level protocol modules only makes sense when you cannot get all
you want from urllib.

205
Python Programming

Finally, we have the HTMLgen external module and the commercial Zope
(Z Object Publishing Environment) system by Digital Creations.

206
Python Programming

CHAPTER 12
DATABASE PROGRAMMING
12.1 INTRODUCTION TO PYTHON DB:
From a construction firm to a stock exchange, every organisation depends
on large databases. These are essentially collections of tables, and’
connected with each other through columns. These database systems
support SQL, the Structured Query Language, which is used to create,
access and manipulate the data. SQL is used to access data, and also to
create and exploit the relationships between the stored data. Additionally,
these databases support database normalisation rules for avoiding
redundancy of data. The Python programming language has powerful
features for database programming. Pythonsupports various databases like
MySQL, Oracle, Sybase, PostgreSQL, etc. Python also supports Data
Definition Language (DDL), Data Manipulation Language (DML) and Data
Query Statements. For database programming, the Python DB API is a
widely used module that provides a database application programming
interface
Benefits of Python for database programming
There are many good reasons to use Python for programming database
applications:
 Programming in Python is arguably more efficient and faster
compared to other languages.
 Python is famous for its portability.
 It is platform independent.
 Python supports SQL cursors.
 In many programming languages, the application developer needs
to take care of the open and closed connections of the database,
to avoid further exceptions and errors. In Python, these
connections are taken care of.
 Python supports relational database systems.
 Python database APIs are compatible with various databases, so

12.2 PYTHON DATABASE APPLICATION PROGRAMMER’S


INTERFACE
DB-API (SQL-API) for Python:
Python DB-API is independent of any database engine, which enables you
to write Python scripts to access any database engine. The Python DB API
implementation for MySQL is MySQLdb. For PostgreSQL, it supports
psycopg, PyGresQL and pyPgSQL modules. DB-API implementations for
Oracle are dc_oracle2 and cx_oracle. Pydb2 is the DB-API implementation

207
Python Programming

for DB2. Python’s DB-API consists of connection objects, cursor objects,


standard exceptions and some other module contents, all of which we will
discuss.
Connection objects
Connection objects create a connection with the database and these are
further used for different transactions. These connection objects are also
used as representatives of the database session.
A connection is created as follows:
>>>conn = MySQLdb.connect('library', user='suhas', password='python')
You can use a connection object for calling methods like commit(),
rollback() and close() as shown below:
>>>cur = conn.cursor() //creates new cursor object for executing SQL
statements>>>conn.commit() //Commits the transactions
>>>conn.rollback() //Roll back the transactions
>>>conn.close() //closes the connection
>>>conn.callproc(proc,param) //call stored procedure for execution
>>>conn.getsource(proc) //fetches stored procedure code
Cursor objects
Cursor is one of the powerful features of SQL. These are objects that are
responsible for submitting various SQL statements to a database server.
There are several cursor classes in MySQLdb.cursors:
1. BaseCursor is the base class for Cursor objects.
2. Cursor is the default cursor class.
CursorWarningMixIn, CursorStoreResultMixIn, CursorTupleRow
sMixIn, and BaseCursor are some components of
the cursor class.
3. CursorStoreResultMixIn uses the mysql_store_result() function to
retrieve result sets from the executed query. These result sets are
stored at the client side.
4. CursorUseResultMixIn uses the mysql_use_result() function to
retrieve result sets from the executed query. These result sets are
stored at the server side.
The following example illustrates the execution of SQL commands using
cursor objects. You can use execute to execute SQL commands
like SELECT. To commit all SQL operations you need to close the cursor
as cursor.close().
>>>cursor.execute('SELECT * FROM books')
>>>cursor.execute('''SELECT * FROM books WHERE book_name = 'python'
AND book_author = 'Mark Lutz' )

208
Python Programming

>>>cursor.close()
Error and exception handling in DB-API
Exception handling is very easy in the Python DB-API module. We can
place warnings and error handling messages in the programs. Python DB-
API has various options to handle this,
like Warning, InterfaceError, DatabaseError, IntegrityError, InternalError,
NotSupportedError, OperationalError and ProgrammingError.
Let’s take a look at them one by one:
IntegrityError: Let’s look at integrity error in detail. In the following
example, we will try to enter duplicate records in the database. It will show
an integrity error, _mysql_exceptions.IntegrityError, as shown below:
1. >>> cursor.execute('insert books values
(%s,%s,%s,%s)',('Py9098','Programming With Perl',120,100))
2. Traceback (most recent call last):
3. File "<stdin>", line 1, in ?
4. File "/usr/lib/python2.3/site-packages/MySQLdb/cursors.py",
line 95, in execute
5. return self._execute(query, args)
6. File "/usr/lib/python2.3/site-packages/MySQLdb/cursors.py",
line 114, in _execute
7. self.errorhandler(self, exc, value)
8. raise errorclass, errorvalue
mysql_exceptions.IntegrityError: (1062, "Duplicate entry 'Py9098' for
key 1")
9. OperationalError: If there are any operation errors like no
databases selected, Python DB-API will handle this error
as OperationalError, shown below:
10. >>> cursor.execute('Create database Library')
11. >>> q='select name from books where cost>=%s order by name'
12. >>>cursor.execute(q,[50])
13. Traceback (most recent call last):
14. File "<stdin>", line 1, in ?
15. File "/usr/lib/python2.3/site-packages/MySQLdb/cursors.py",
line 95, in execute
16. return self._execute(query, args)
17. File "/usr/lib/python2.3/site-packages/MySQLdb/cursors.py",
line 114, in _execute
18. self.errorhandler(self, exc, value)

209
Python Programming

19. File "/usr/lib/python2.3/site-


packages/MySQLdb/connections.py", line 33, in
defaulterrorhandler
20. raise errorclass, errorvalue
_mysql_exceptions.OperationalError: (1046, 'No Database Selected')
21. ProgrammingError: If there are any programming errors like
duplicate database creations, Python DB-API will handle this
error as ProgrammingError, shown below:
22. >>> cursor.execute('Create database Library')
23. Traceback (most recent call last):>>> cursor.execute('Create
database Library')
24. Traceback (most recent call last):
25. File "<stdin>", line 1, in ?
26. File "/usr/lib/python2.3/site-packages/MySQLdb/cursors.py",
line 95, in execute
27. return self._execute(query, args)
28. File "/usr/lib/python2.3/site-packages/MySQLdb/cursors.py",
line 114, in _execute
29. self.errorhandler(self, exc, value)
30. File "/usr/lib/python2.3/site-
packages/MySQLdb/connections.py", line 33, in
defaulterrorhandler
31. raise errorclass, errorvalue
_mysql_exceptions.ProgrammingError: (1007, "Can't create database
'Library'. Database exists")
Python and MySQL
Python and MySQL are a good combination to develop database
applications. After starting the MySQL service on Linux, you need to
acquire MySQLdb, a Python DB-API for MySQL to perform database
operations. You can check whether the MySQLdb module is installed in
your system with the following command:
>>>import MySQLdb

If this command runs successfully, you can now start writing scripts for
your database.
To write database applications in Python, there are five steps to follow:

Import the SQL interface with the following command:

210
Python Programming

>>> import MySQLdb

Establish a connection with the database with the following command:

>>> conn=MySQLdb.connect(host='localhost',user='root',passwd='')

Create a cursor for the connection with the following command:

>>>cursor = conn.cursor()

Execute any SQL query using this cursor as shown below—here the
outputs in terms of 1L or 2L show a number of rows affected by this query:

>>> cursor.execute('Create database Library')

1L // 1L Indicates how many rows affected

>>> cursor.execute('use Library')

>>>table='create table books(book_accno char(30) primary key, book_name

char(50),no_of_copies int(5),price int(5))'

>>> cursor.execute(table)

0L

Finally, fetch the result set and iterate over this result set. In this step, the
user can fetch the result sets as shown below:
>>> cursor.execute('select * from books')
2L
>>> cursor.fetchall()
\(('Py9098', 'Programming With Python', 100L, 50L), ('Py9099',
'Programming With Python', 100L, 50L))
In this example, the fetchall() function is used to fetch the result sets.

211
Python Programming

More SQL operations


We can perform all SQL operations with Python DB-API. Insert, delete,
aggregate and update queries can be illustrated as follows.
Insert SQL Query
>>>cursor.execute('insert books values
(%s,%s,%s,%s)',('Py9098','Programming With Python',100,50))
lL // Rows affected.
>>> cursor.execute('insert books values
(%s,%s,%s,%s)',('Py9099','Programming With Python',100,50))
1L //Rows affected.
If the user wants to insert duplicate entries for a book’s accession number,
the Python DB-API will show an error as it is the primary key. The
following example illustrates this:
>>> cursor.execute('insert books values
(%s,%s,%s,%s)',('Py9099','Programming With Python',100,50))
>>>cursor.execute('insert books values
(%s,%s,%s,%s)',('Py9098','Programming With Perl',120,100))

Traceback (most recent call last):

File "<stdin>", line 1, in ?

File "/usr/lib/python2.3/site-packages/MySQLdb/cursors.py", line 95, in


execute

return self._execute(query, args)

File "/usr/lib/python2.3/site-packages/MySQLdb/cursors.py", line 114,


in _execute

self.errorhandler(self, exc, value)

File "/usr/lib/python2.3/site-packages/MySQLdb/connections.py", line


33, in defaulterrorhandler

raise errorclass, errorvalue

212
Python Programming

_mysql_exceptions.IntegrityError: (1062, "Duplicate entry 'Py9098' for key


1")

The Update SQL query can be used to update existing records in the
database as shown below:

1. >>> cursor.execute('update books set price=%s where


no_of_copies<=%s',[60,101])

2. 2L

3. >>> cursor.execute('select * from books')

4. 2L

5. >>> cursor.fetchall()

(('Py9098', 'Programming With Python', 100L, 60L), ('Py9099',


'Programming With Python', 100L, 60L))

The Delete SQL query can be used to delete existing records in the
database as shown below:

>>> cursor.execute('delete from books where no_of_copies<=%s',[101])

2L

>>> cursor.execute('select * from books')

0L

>>> cursor.fetchall()

()

213
Python Programming

>>> cursor.execute('select * from books')

3L

>>> cursor.fetchall() (('Py9099', 'Python-Cookbook', 200L, 90L), ('Py9098',


'Programming With Python', 100L, 50L), ('Py9097', 'Python-Nut shell',
300L, 80L))

Aggregate functions can be used with Python DB-API in the database as


shown below:

>>> cursor.execute('select * from books')

4L

>>> cursor.fetchall()

(('Py9099', 'Python-Cookbook', 200L, 90L), ('Py9098', 'Programming With


Python', 100L, 50L), ('Py9097', 'Python-Nut shell', 300L, 80L), ('Py9096',
'Python-Nut shell', 400L, 90L))

>>> cursor.execute("select sum(price),avg(price) from books where


book_name='Python-Nut shell'")

1L

>>> cursor.fetchall()

12.3 OBJECT RELATIONAL MAPPERS (ORM’S)


Object-relational mappers (ORMs)
An object-relational mapper (ORM) is a code library that automates the
transfer of data stored in relational databases tables into objects that are
more commonly used in application code.

214
Python Programming

Fig 12.1 Relational python objects


Why are ORMs useful?
ORMs provide a high-level abstraction upon a relational database that
allows a developer to write Python code instead of SQL to create, read,
update and delete data and schemas in their database. Developers can use
the programming language they are comfortable with to work with a
database instead of writing SQL statements or stored procedures.
For example, without an ORM a developer would write the following SQL
statement to retrieve every row in the USERS table where
the zip_code column is 94107:

SELECT * FROM USERS WHERE zip_code=94107;

The equivalent Django ORM query would instead look like the following
Python code:

# obtain everyone in the 94107 zip code and assign to users variable
users = Users.objects.filter(zip_code=94107)

The ability to write Python code instead of SQL can speed up web
application development, especially at the beginning of a project. The
potential development speed boost comes from not having to switch from
Python code into writing declarative paradigm SQL statements. While some
software developers may not mind switching back and forth between
languages, it's typically easier to knock out a prototype or start a web
application using a single programming language.
ORMs also make it theoretically possible to switch an application between
various relational databases. For example, a developer could use SQLite for
local development and MySQL in production. A production application
could be switched from MySQL to PostgreSQL with minimal code
modifications.
In practice however, it's best to use the same database for local
development as is used in production. Otherwise unexpected errors could
215
Python Programming

hit in production that were not seen in a local development environment.


Also, it's rare that a project would switch from one database in production
to another one unless there was a pressing reason.
Do I have to use an ORM for my web application?
Python ORM libraries are not required for accessing relational databases.
In fact, the low-level access is typically provided by another library called
a database connector, such aspsycopg (for PostgreSQL) or MySQL-
python (for MySQL). Take a look at the table below which shows how
ORMs can work with different web frameworks and connectors and
relational databases.

The above table shows for example that SQLAlchemy can work with
varying web frameworks and database connectors. Developers can also use
ORMs without a web framework, such as when creating a data analysis
tool or a batch script without a user interface.
What are the downsides of using an ORM?
There are numerous downsides of ORMs, including
1. Impedance mismatch
2. Potential for reduced performance
3. Shifting complexity from the database into the application code
Impedance mismatch
The phrase "impedance mismatch" is commonly used in conjunction with
ORMs. Impedance mismatch is a catch-all term for the difficulties that
occur when moving data between relational tables and application objects.
The gist is that the way a developer uses objects is different from how data
is stored and joined in relational tables.

216
Python Programming

This article on ORM impedance mismatch does a solid job of explaing what
the concept is at a high level and provides diagrams to visualize why the
problem occurs.
Potential for reduced performance
One of the concerns that's associated with any higher-level abstraction or
framework is potential for reduced performance. With ORMs, the
performance hit comes from the translation of application code into a
corresponding SQL statement which may not be tuned properly.
ORMs are also often easy to try but difficult to master. For example, a
beginner using Django might not know about
the select_related() function and how it can improve some queries' foreign
key relationship performance. There are dozens of performance tips and
tricks for every ORM. It's possible that investing time in learning those
quirks may be better spent just learning SQL and how to write stored
procedures.
There's a lot of hand-waving "may or may not" and "potential for" in this
section. In large projects ORMs are good enough for roughly 80-90% of use
cases but in 10-20% of a project's database interactions there can be
major performance improvements by having a knowledgeable database
administrator write tuned SQL statements to replace the ORM's generated
SQL code.
Shifting complexity from the database into the app code
The code for working with an application's data has to live somewhere.
Before ORMs were common, database stored procedures were used to
encapsulate the database logic. With an ORM, the data manipulation code
instead lives within the application's Python codebase. The addition of data
handling logic in the codebase generally isn't an issue with a sound
application design, but it does increase the total amount of Python code
instead of splitting code between the application and the database stored
procedures.
Python ORM Implementations
There are numerous ORM implementations written in Python, including

 SQLAlchemy
 Peewee
 The Django ORM
 PonyORM
 SQLObject
 Tortoise ORM

217
Python Programming

There are other ORMs, such as Canonical's Storm, but most of them do
not appear to currently be under active development. Learn more about
the major active ORMs below.
Django's ORM
The Django web framework comes with its own built-in object-relational
mapping module, generally referred to as "the Django ORM" or "Django's
ORM".
Django's ORM works well for simple and medium-complexity database
operations. However, there are often complaints that the ORM makes
complex queries much more complicated than writing straight SQL or
using SQLAlchemy.
It is technically possible to drop down to SQL but it ties the queries to a
specific database implementation. The ORM is coupled closely with Django
so replacing the default ORM with SQLAlchemy is currently a hack
workaround. Note though it is possible that swappable ORM backends will
be possible in the future as it is now possible to change thetemplate
engine for rendering output in Django.
Since the majority of Django projects are tied to the default ORM, it is best
to read up on advanced use cases and tools for doing your best work
within the existing framework.
SQLAlchemy ORM
SQLAlchemy is a well-regarded Python ORM because it gets the
abstraction level "just right" and seems to make complex database queries
easier to write than the Django ORM in most cases. There is an entire page
on SQLAlchemy that you should read if you want to learn more about
using the library.
Peewee ORM
Peewee is a Python ORM implementation that is written to be "simpler,
smaller and more hackable" than SQLAlchemy. Read the full Peewee
page for more information on the Python ORM implementation.
Pony
Pony ORM is another Python ORM available as open source, under the
Apache 2.0 license.
SQLObject ORM
SQLObject is an ORM that has been under active open source development
for over 14 years, since before 2003.
Schema migrations
Schema migrations, for example when you need to add a new column to an
existing table in your database, are not technically part of ORMs. However,
since ORMs typically lead to a hands-off approach to the database (at the

218
Python Programming

developers peril in many cases), libraries to perform schema migrations


often go hand-in-hand with Python ORM usage on web application
projects.

219
Python Programming

REFERENCES

 Think Python, Allen Downey, Green Tea Press


 Introduction to Python, Kenneth A. Lambert, Cengage
 Python Programming: A Modern Approach, Vamsi Kurama, Pearson
 Learning Python, Mark Lutz, O’Reilly.
 Core Python Programming, Wesley J. Chun, Second Edition,
Pearson.

220

View publication stats

You might also like