PythonProgramming book
PythonProgramming book
net/publication/370637742
CITATIONS READS
0 465
5 authors, including:
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.
GCS PUBLISHERS
INDIA
PYTHON PROGRAMMING
Authors
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.
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]
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.
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.
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
2
Python Programming
3
Python Programming
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
8
Python Programming
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:
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.
13
Python Programming
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()
15
Python Programming
def display(self):
print("ID: %d \nName: %s" % (self.id, self.name))
emp1.display()
16
Python Programming
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
Example
class Student:
def __init__(self, name, id, age):
self.name = name
self.id = id
self.age = 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
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
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.
class Base2:
<class-suite>
.
.
.
class 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
24
Python Programming
25
Python Programming
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
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.
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.
33
Python Programming
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
Operations on string:
i. Indexing
ii. Slicing
iii. Concatenation
iv. Repetitions
v. Member ship
35
Python Programming
36
Python Programming
37
Python Programming
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
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
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
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)
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:
44
Python Programming
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
45
Python Programming
Output:
a>b=> True
a>b=> False
a==b=> False
a!=b=> True
a>=b=> False
a>=b=> True
Assignment Operators:
46
Python Programming
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
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:
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:
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:
49
Python Programming
Identity Operators
They are used to check if two values (or variables) are located on the same
part of the memory.
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
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. 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
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
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
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
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
Output
enter your mark:78
grade: B
Output
enter the color of light: green
GO
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
output
enter a value:1
enter b value:0
enter c value:0
same and real roots
Nested conditionals
62
Python Programming
Flowchart:
Example:
1. greatest of three numbers
2. positive, negative, or zero
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
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
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
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:
Example:
def add():
a=10
71
Python Programming
b=20
c=a+b
return c
c=add()
print(c)
Void Function
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:
72
Python Programming
4. Variable-length parameters
73
Python Programming
Example
def student( name,*mark):
print(name,mark)
student (" bala ",102,90)
Output:
bala ( 102 ,90)
Local Scope, A variable with a local scope can be used only within the
function.
74
Python Programming
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)
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.
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
Operat Description
or
81
Python Programming
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?"''')
83
Python Programming
2. \\ Backslash print("\\")
Output:
\
84
Python Programming
85
Python Programming
#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
87
Python Programming
88
Python Programming
89
Python Programming
90
Python Programming
91
Python Programming
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.
97
Python Programming
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
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.
#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.
105
Python Programming
S Functi Description
N on
S List Tuple
N
106
Python Programming
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
# 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)
110
Python Programming
111
Python Programming
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
114
Python Programming
S Method Description
N
115
Python Programming
11 len()
12 popItem()
13 pop()
14 count()
15 index()
116
Python Programming
CHAPTER – 7
FILE, MODULES
117
Python Programming
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
119
Python Programming
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")
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
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
127
Python Programming
128
Python Programming
S Method Description
N
129
Python Programming
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
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]
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
140
Python Programming
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
142
Python Programming
print(all(k))
Output:
True
False
False
False
True
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
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.'
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
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
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."
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))
# 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()
details = Details()
print('The age is:', getattr(details, "age"))
print('The age is:', details.age)
Output:
The age is: 22
The age is: 22
148
Python Programming
l = [0, False]
print(any(l))
l = [0, False, 5]
print(any(l))
l = []
print(any(l))
Output:
True
False
True
False
149
Python Programming
# prints '3'
print(next(listIter))
# prints '4'
print(next(listIter))
# prints '5'
print(next(listIter))
Output:
1
2
3
4
5
# 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]
def localsPresent():
present = True
return locals()
print('localsNotPresent:', localsAbsent())
print('localsPresent:', localsPresent())
Output:
localsAbsent: {}
localsPresent: {'present': True}
numbers = (1, 2, 3, 4)
result = map(calculateAddition, numbers)
print(result)
151
Python Programming
m= memoryview(randomByteArray)
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__']
152
Python Programming
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)
154
Python Programming
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}
156
Python Programming
print(result2)
Output:
21
461168601842737174
157
Python Programming
158
Python Programming
print(val)
print(val2)
print(val3)
Output:
139963782059696
139963805666864
139963781994504
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]
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)
160
Python Programming
item = next(number)
print(item)
Output:
256
32
82
161
Python Programming
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
162
Python Programming
# negative x, positive y
print(pow(-4, 2))
# negative x, negative y
print(pow(-4, -2))
Output:
16
16
0.0625
0.0625
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
# for tuple
164
Python Programming
# 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]
# even choice
print(round(6.6))
Output:
10
11
7
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)
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))
class Python:
a=0
InstanceOfPython = Python()
print(type(InstanceOfPython))
Output:
<class 'list'>
<class 'dict'>
<class '__main__.Python'>
InstanceOfPython = Python()
print(vars(InstanceOfPython))
Output:
{'y': 9, 'x': 7}
167
Python Programming
168
Python Programming
169
Python Programming
170
Python Programming
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
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
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
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
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
183
Python Programming
184
Python Programming
185
Python Programming
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
190
Python Programming
191
Python Programming
192
Python Programming
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
194
Python Programming
195
Python Programming
196
Python Programming
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
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.
201
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 −
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
207
Python Programming
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
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:
210
Python Programming
>>> conn=MySQLdb.connect(host='localhost',user='root',passwd='')
>>>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(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
212
Python Programming
The Update SQL query can be used to update existing records in the
database as shown below:
2. 2L
4. 2L
5. >>> cursor.fetchall()
The Delete SQL query can be used to delete existing records in the
database as shown below:
2L
0L
>>> cursor.fetchall()
()
213
Python Programming
3L
4L
>>> cursor.fetchall()
1L
>>> cursor.fetchall()
214
Python Programming
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
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
219
Python Programming
REFERENCES
220