Python
Python
Python
For B.B.A.(C.A) : Semester - V
[Course Code CA-504 : Credits-03]
CBCS Pattern
As Per New Syllabus, Effective from June 2021
Price ` 300/-
N4961
PYTHON ISBN 978-93-5451-088-5
First Edition : September 2021
© : Authors
The text of this publication, or any part thereof, should not be reproduced or transmitted in any form or stored
in any computer storage system or device for distribution including photocopy, recording, taping or information
retrieval system or reproduced on any disc, tape, perforated media or other information storage device etc.,
without the written permission of Authors with whom the rights are reserved. Breach of this condition is liable for
legal action.
Every effort has been made to avoid errors or omissions in this publication. In spite of this, errors may have
crept in. Any mistake, error or discrepancy so noted and shall be brought to our notice shall be taken care of in the
next edition. It is notified that neither the publisher nor the authors or seller shall be responsible for any damage
or loss of action to any one, of any kind, in any manner, therefrom. The reader must cross check all the facts and
contents with original Government notification or publications.
DISTRIBUTION CENTRES
PUNE
Nirali Prakashan Nirali Prakashan
(For orders outside Pune) (For orders within Pune)
S. No. 28/27, Dhayari Narhe Road, Near Asian College119, Budhwar Peth, Jogeshwari Mandir
Lane
Pune 411041, Maharashtra Pune 411002, Maharashtra
Tel : (020) 24690204; Mobile : 9657703143 Tel : (020) 2445 2044; Mobile : 9657703145
Email : [email protected] : [email protected]
MUMBAI
Nirali Prakashan
Rasdhara Co-op. Hsg. Society Ltd., 'D' Wing Ground Floor, 385 S.V.P. Road
Girgaum, Mumbai 400004, Maharashtra
Mobile : 7045821020, Tel : (022) 2385 6339 / 2386 9976
Email : [email protected]
DISTRIBUTION
BRANCHES
DELHI BENGALURU NAGPUR
Nirali Prakashan Nirali Prakashan Nirali Prakashan
Room No. 2 Ground Floor Maitri Ground Floor, Jaya Apartments, Above Maratha
Mandir, Shop No. 3, 4575/15 Omkar Tower, Agarwal Road No. 99, 6th Cross, 6th Main, First
Floor, Rani Jhanshi Square,
Darya Ganj, New Delhi 110002 Malleswaram, Bengaluru 560003 Sitabuldi
Nagpur 440012 (MAH) Mobile : 9555778814/9818561840 Karnataka; Mob : 9686821074 Tel
: (0712) 254 7129
Email : [email protected] : [email protected] : [email protected]
Preface …
We take an opportunity to present this book entitled as "Python" to the
students of Fifth Semester - B.B.A.(C.A). The object of this book is to present the
subject matter in a most concise and simple manner. The book is written strictly
according to the New Syllabus (CBCS Pattern).
The book covers theory of Introduction to Python, Modules and Packages,
Classes, Objects and Inheritance, Exception Handling, GUI Programming and
Python Libraries.
The book has its own unique features. It brings out the subject in a very simple
and lucid manner for easy and comprehensive understanding of the basic
concepts, its intricacies, procedures and practices. This book will help the readers
to have a broader view on Core Java. The language used in this book is easy and
will help students to improve their vocabulary of Technical terms and understand
the matter in a better and happier way.
A special words of thank to Shri. Dineshbhai Furia, Mr. Jignesh Furia for showing
full faith in us to write this text book. We also thank to Mr. Akbar Shaikh of M/s
Nirali Prakashan for their excellent co-operation.
We also thank Mr. Akbar Shaikh, Ms. Chaitali Takale, Mr. Ravindra Walodare, Mr.
Sachin Shinde, Mr. Ashok Bodke, Mr. Moshin Sayyed and Mr. Nitin Thorat.
Although every care has been taken to check mistakes and misprints, any errors,
omission and suggestions from teachers and students for the improvement of this
text book shall be most welcome.
Authors
Syllabus …
1. Introduction to Python [Lectures 16] 1.1 History, Feature of Python,
Setting-up Path, Working with Python Interpreter, Basic Syntax, Variable and Data
Types, Operators.
1.2 Conditional Statements - If, If-Else, nested if-else, Examples.
1.3 Looping - For, While, Nested Loops, Examples
1.4 Control Statements - Break, Continue, Pass.
1.5 String Manipulation - Accessing String, Basic Operations, String Slices,
Function and Methods, Examples.
1.6 Lists - Introduction, Accessing List, Operations, Working with Lists,
Function and Methods.
1.7 Tuple - Introduction, Accessing Tuples, Operations Working, Function
and Methods, Examples.
1.8 Dictionaries - Introduction, Accessing Values in Dictionaries, Working
with Dictionaries, Properties, Function, Examples.
1.9 Functions - Defining a Function, Calling a Function, Types of Function,
Function Arguments, Anonymous Function, Global and Local Variable,
Examples.
2. Modules and Packages [Lectures 6]
2.1 Built in Modules
2.1.1 Importing Modules in Python Program
2.1.2 Working with Random Modules.
2.1.3 E.g. built-ins, time, date time, calendar, sys, etc.
2.2 User Defined Functions
2.2.1 Structure of Python Modules
2.3 Packages
2.3.1 Predefined Packages
2.3.2 User defined Packages
3. Classes, Objects and Inheritance [Lectures
8]
3.1 Classes and Objects
3.1.1 Classes as User Defined Data Type
3.1.2 Objects as Instances of Classes
3.1.3 Creating Class and Objects
3.1.4 Creating Objects by Passing Values
3.1.5 Variables and Methods in a Class
3.2 Inheritance
3.2.1 Single Inheritance
3.2.2 Multilevel Inheritance
3.2.3 Multiple Inheritance
3.2.4 Hybrid Inheritance
3.2.5 Hierarchical Inheritance
3.2.6 IS-A Relationship and HAS-A Relationship
4. Exception Handling [Lectures
4]
4.1 Python Exception
4.2 Common Exception
4.3 Exception handling in Python (try-except-else)
4.4 The except Statement with No Exception
4.5 Multiple Exception
4.6 The try-finally Clause
4.7 Custom Exception and Assert Statement
5. GUI Programming [Lectures
10]
5.1 Introduction
5.2 Tkinter Programming
5.4 Tkinter Widgets
5.5 Frame
5.6 Button
5.7 Label
5.8 Entry
6. Python Libraries [Lectures
4]
6.1 Statistical Analysis - NumPy, SciPy, Pandas, StatsModels
6.2 Data Visualization - Matplotlib, Seaborn, Plotly
6.3 Data Modelling and Machine Learning - Scikit-learn, XGBoost, Eli5
6.4 Deep Learning - TensorFlow, Pytorch, Keras
6.5 Natural Language Processing (NLP) - NLTK, SpaCy, Gensim
Contents …
Learning Objectives…
▣ To learn Basic Concepts in Python.
▣ To study Basics of Python.
▣ To understands Data Types, Variables, Constants etc. in Python.
1. INTRODUCTION
1
• Python is a high-level, interpreted, interactive and object-oriented programming language. Today,
Python is the trendiest programming language programming.
• There are several reasons for why Python programming language is the preferable choice of the
programmers/developers over other popular programming languages like C++, Java and so on.
• Python is popular programming language because of it provides more reliability of code, clean syntax
of code, advanced language features, scalability of code, portability of code, support object oriented
programming, broad standard library, easy to learn and read, support GUI mode, interactive, versatile
and interpreted, interfaces to all major commercial databases and so on.
• There are two major Python versions namely, Python 2 and Python 3. Python 3.0 was developed with
the same philosophy as in prior versions.
• Python 3.9.5 is the newest major release of the Python programming language.
Python scripts normally have the file extension .py.
• Some common applications of Python Programming are listed below:
1. Google's App Engine web development framework uses Python as an application language.
2. Maya, a powerful integrated 3D modeling and animation system, provides a Python scripting API.
3. Linux Weekly News, published by using a web application written in Python
programming.
4. Google makes extensive use of Python in its Web Search Systems.
1.1
Python [BBA (CA) - Sem. V] 1.2 Introduction to Python
5. The popular YouTube video sharing service is largely written in Python programming.
6. The NSA (National Security Agency) uses Python programming for cryptography and intelligence
analysis.
7. iRobot uses Python programming to develop commercial and military robotic devices.
8. The Raspberry Pi single-board computer promotes Python programming as its educational
language.
9. Netflix and Yelp have both documented the role of Python in their software infrastructures.
10. Industrial Light and Magic, Pixar and others uses Python programming in the production of animated
movies.
1.1.1 History
• Python laid its foundation in the late 1980s. Python was developed by Guido Van Rossum at
National Research Institute for Mathematics and Computer Science in Netherlands in 1990.
• Inspired by Monty Python’s Flying Circus, a BBC comedy series, he named the language Python.
• Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol68, SmallTalk,
and Unix shell and other scripting languages.
• ABC programming language is said to be the predecessor of Python language which was capable of
Exception Handling and interfacing with Amoeba Operating System.
• Like Perl, Python source code is now available under the GNU General Public License (GPL). In
February 1991, Guido Van Rossum published Python 0.9.0 (first release). In addition to exception
handling, Python included classes, lists and strings.
• In 1994, Python 1.0 was released with new features like lambda, map, filter, and reduce which aligned
it heavily in relation to functional programming.
• Python 2.0 added new features like list comprehensions, garbage collection system and it supported
Unicode.
• On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was designed to rectify
fundamental flaw of the language. In Python 3.0 the print statement has been replaced with a print()
function.
• Python widely used in both industry and academia because of its simple, concise and extensive
support of libraries.
• Python is available for almost all operating systems such as Windows, Mac, Linux/ Unix etc. Python
can be downloading from http://www.python.org/downloads. Features of Python
1.1.2 • Features of Python programming language are given below:
1. Simple and Easy-to-Learn: Python is a simple language with few keywords, simple structure
and its syntax is also clearly defined. This makes Python a beginner's language. In Python
programming programs are easy to write and execute as it omits some cumbersome, poorly
understandable and confusing features of other programming language such as C++ and Java.
2. Interpreted and Interactive: Python is processed at runtime by the interpreter. We need not
compile the Program before executing it. The Python prompt interact with the interpreter to
interpret the programs that we have written. Python has an option namely interactive mode
which allows interactive testing and debugging of code.
Python [BBA (CA) - Sem. V] 1.3 Introduction to Python
Byte Virtual
Compiler
code machine
Running code
Source code
Library
modules
Fig. 1.2
2. Click on new tab of user variables.
Python [BBA (CA) - Sem. V] 1.5 Introduction to Python
Fig. 1.3
Fig. 1.4
4. Copy the path of Python folder and Paste path of Python in variable value.
Fig. 1.5
5. Click on Ok button:
Python [BBA (CA) - Sem. V] 1.6 Introduction to Python
Fig. 1.6
6. Click on Ok button:
Close all windows. Now you can run python.exe without specifying the full path to the file:
Fig. 1.7
Step 2 : Click on All Programs and then click on Python 3.9 (64 bit) as shown in Fig. 1.7. We will see the
Python interactive prompt in Python command line.
Fig. 1.8
Python command prompt contains an opening message >>> called command prompt. The cursor at
command prompt waits for to enter Python command. A complete command is called a
statement. For example check first command to print message, in Fig. 1.9.
Fig. 1.9
Step 3 : To exit from the command line of Python, use Ctrl+z or quit() followed by Enter.
2. Starting Python IDLE:
Python [BBA (CA) - Sem. V] 1.8 Introduction to Python
• When we install Python 3, we also get IDLE (Integrated Development Environment). IDLE includes a
color syntax-highlighting editor, a debugger, the Python Shell, and a complete copy of Python 3’s
online documentation set.
• The steps are given below:
Step 1 : Press Start button and click on IDLE (Python 3.9, 64-bit) options as shown in Fig. 1.10.
Step 2 : We will see the Python interactive prompt i.e. interactive shell.
Fig. 1.10
Python interactive shell prompt contains opening message >>>, called shell prompt. A cursor is waiting
for the command. A complete command is called a statement. When we write a command
and press enter, the python interpreter will immediately display the result.
Fig. 1.11
Executing Python Programs Scripts:
• In Python IDLEs shell window, click on File, and select the New File or press Ctrl+N.
Fig. 1.12
Python [BBA (CA) - Sem. V] 1.9 Introduction to Python
•
As soon as we click on New File, the window appears as shown in Fig. 1.13.
Fig. 1.15
• To run the Python program, click on Run and then Run Module option or we can press Ctrl+F5.
Fig. 1.16
• After clicking Run Module, we will get the output of program on Python shell.
Python [BBA (CA) - Sem. V] 1.10 Introduction to Python
Fig. 1.17
1.1.5 Basic Syntax
• Python program is set of instructions. Python programs are typically organized with one
statement per line. Before to write and run a Python program we understand structure of a Python
program.
• Fig. 1.18 shows a typical program structure of Python programming.
• Python programming programs are structured as a sequence of statements. A Python statement is
smallest program unit.
• Statements are the instructions that are written in a program to perform a specific task. A Python
statement is a complete instruction executed by the Python
interpreter.
• By default, the Python interpreter executes all statements sequentially, but we can change order of
execution using control statements.
Documentation Section
Import Statement
Class Section
Essential
Data members
Member functions
Subprogram Section
•
3. Global Declaration Section is used to define the global variables for the programs.
4. Class Section describes the information about the user defined classes in the Python program. A
class is a collection of data members and member functions called method that operate on data
members.
5. Sub Program Section includes use defined functions. The functions include the set of
statements that need to be executed when the function is called form anywhere.
6. Play Ground Section is the main section of Python program and the main section starts where
the function calling.
Python has two basic modes namely, script and interactive.
1. Interactive Mode:
• The interactive mode is a command line shell which gives immediate feedback for each statement,
while running previously fed statements in active memory.
• Interactive mode is used for quickly and conveniently running single line or blocks of code. Here’s an
example using the python shell that comes with a basic python installation.
• The “>>>” indicates that the shell is ready to accept interactive commands. For example, if we want to
print the statement “Interactive Mode”, simply type the appropriate code and hit enter.
Fig. 1.19
2. Script Mode:
• The normal script mode is the mode where the scripted and finished .py files are run in the Python
interpreter.
• In the standard Python shell we can go to “File” → “New File” (or just hit Ctrl + N) to pull up a blank
script to write the code. Then save the script with a “.py” extension.
• We can save it anywhere we want for now, though we may want to make a folder somewhere to store
the code as we test Python out. To run the script, either select “Run” → “Run Module” or press F5.
• We should see something like the following, (See Fig. 1.20 (a) and 1.20 (b)).
Python [BBA (CA) - Sem. V] 1.12 Introduction to Python
•
Following simple Python program shows structure of Python program:
•
1. Numbers: Represents numeric data to perform mathematical operations. Numbers can be
integers (like 1 and 2), floats (like 1.1 and 1.2), fractions (like 1/2 and 2/3), or even complex
numbers.
2. String: Represents text characters, special symbols or alphanumeric data. String is sequence of
Unicode characters.
3. List: Represents sequential data that the programmer wishes to sort, merge etc.
4. Tuple: Represents sequential data with a little difference from list.
5. Dictionary: Represents a collection of data that associate a unique key with each value.
6. Boolean: Represents truth values (true or false).
7. None: Python defines a special variable None denoting a “null object”.
• To determine a variable's type in Python programming we can use the type() function. The value of
some objects can be changed. Objects whose value can be changed are called mutable and objects
whose value is unchangeable (once they are created) are called immutable.
• Let us see above data types in detail:
1. Boolean (bool Data Type):
• The simplest build-in type in Python is the bool data type, it represents the two values, True and False.
Internally the true value is represented as 1 and false is 0.
Example:
>>> size = 1
>>> size < 0
False
>>> size = 0
>>> size < 0
False
>>> size = -1
>>> size < 0
True
2. None Data Type:
• Python defines a special variable None denoting a “null object”, which is convenient to use when a
variable is available but its value is considered undefined.
• None in Python is used for defining null variables and objects. None is an instance of the NoneType
class.
Python [BBA (CA) - Sem. V] 1.15 Introduction to Python
•
None object is accessed through the built-in name None. It is a data type of the class NoneType
object.
answer = None
<may update answer from other data...>
if answer is None:
quit = True elif
answer == 'quit':
quit = True
else:
quite = False
• To check if a variable answer is None or not, always use if answer is None or if answer is not None.
Testing just if not answer is dangerous, because the test is true if answer is an empty string. The
difference between the is and == operators: is tests for object identity, while == tests if two objects
have the same value (i.e., the same content).
3. Number Data Types:
• Number data types store numeric values. Integers, floating point numbers and complex numbers are
falls under Python numbers category. They are defined as int, float and complex in Python.
Integer Float Complex
10 1.5 3+4j
Fig. 1.21: Types of Numbers Data Type (i) Integers (int Data Type): o
An int data type represents an integer number. An integer number is a number without any decimal or
fractional point. o For example, a = 57, here a is called the int type variable and stores integer value
57. o These represent numbers in the range − 2147483648 to 2147483647.
o An integer is a whole number that can be positive (+) or negative (−). Integers can be of any
length, it is only limited by the memory available.
Example: For number data types are integers.
>>> a=10
>>> a
10
o To determine the type of a variable type() function is used.
>>> type(a)
<class ‘int’>
• In Python programming one can write integers in Hexadecimal (base 16), Octal (base 8) and Binary
(base 2) formats by using one of the following prefixes to the integer.
Sr. No. Prefix Interpretation Base
1. ‘0b’ or ‘0B’ Binary 2
2. ‘0o’ or ‘0O’ Octal 8
3. ‘0x’ or ‘0X’ Hexadecimal 16
Python [BBA (CA) - Sem. V] 1.16 Introduction to Python
• String is a collection of group of characters. Strings are identified as a contiguous set of characters
enclosed in single quotes (' ') or double quotes (" ").
• Any letter, a number or a symbol could be a part of the string. Strings are unchangeable (immutable).
Once a string is created, it cannot be modified.
• Strings in python support Unicode characters. The default encoding for Python source code is UTF-8.
So, we can also say that String is a sequence of Unicode characters.
• Strings are ordered. Strings preserved the order of characters inserted. Example: For string data
type.
>>> s1="Hello" # string in double quotes >>>
s2='Hi' # string in single quotes
>>> s3="Don't open the door" # single quote string in double
quotes >>> s4='I said "yipee"' # double quote string in single
quotes
>>> s1
'Hello'
>>> s2
'Hi'
>>> s3
"Don't open the door"
>>> s4
'I said "yipee"'
>>>
5. List Data Type:
• Lists are the most versatile of Python's compound data types. List is an ordered sequence of items. It is
one of the most used data type in Python and is very flexible.
• List can contain heterogeneous values such as integers, floats, strings, tuples, lists and dictionaries but
they are commonly used to store collections of homogeneous objects.
• The list data type in Python programming is just like an array that can store a group of elements and
we can refer to these elements using a single name.
• Declaring a list is pretty straight forward. Items separated by commas (,) are enclosed within square
brackets [ ].
Example: For list.
>>> first=[10, 20, 30] # homogenous values in list >>>
second=["One","Two","Three"] # homogenous values in list
>>> first
[10, 20, 30]
>>> second
Python [BBA (CA) - Sem. V] 1.18 Introduction to Python
tuple_obj=(70,2.50, "tybca")
• Tuples are immutable objects whose contents cannot be altered: words = ('flower',
'homophone', 'flour')
words[1] = 'and' # illegal - Python issues an error
message
7. Dictionary Data Type:
• Dictionary data type in Python is an unordered collection of key-value pairs. Dictionaries in Python
work like associative arrays or hashes found in Perl and consist of key-value pairs.
• When we have the large amount of data, the dictionary data type is used. The dictionary data type is
mutable in nature which means we can update modify/update any value in the dictionary.
• Items in dictionaries are enclosed in curly braces { } and separated by the comma (,). A colon (:) is used
to separate key from value. Values can be assigned and accessed using square braces ([]).
Example: For dictionary data type.
>>> dic1={1:"First","Second":2}
>>> dic1
{1: 'First', 'Second': 2}
>>> type(dic1)
<class 'dict'>
>>> dic1[3]="Third"
>>> dic1
{1: 'First', 'Second': 2, 3: 'Third'}
>>> dic1.keys() dict_keys([1,
'Second', 3]) >>> dic1.values()
dict_values(['First', 2,
'Third'])
>>>
1.2.2 Variables
• A variable is like a container that stores values that we can access or change. It is a way of
pointing to a memory location used by a program.
• We can use variables to instruct the computer to save or retrieve data to and from this memory
location.
• A variable is a name given to a location in the computer's memory location, where the value can be
stored that can be used in the program.
• When we create a variable, some space in the memory is reserved or allocated for that variable to
store a data value in it.
Python [BBA (CA) - Sem. V] 1.20 Introduction to Python
• The size of the memory reserved by the variable depends on the type of data it is going to hold. The
period of time that a variable exists is called its lifetime.
• The variable is so called because its value may vary during the time of execution, but at a given
instance only one value can be stored in it.
Variable Declaration:
• A variable is an identifier that holds a value. In programming, we say that we assign a value to a
variable. Technically speaking, a variable is a reference to a computer memory, where the value is
stored.
• Basic rules to declare variables in python programming language:
1. Variables in Python can be created from alphanumeric characters and underscore(_) character.
2. A variable cannot begin with a number.
3. The variables are case sensitive. Means Amar is differ the 'AMAR' are two separate variables.
4. Variable names should not be reserved word or keyword.
5. No special characters are used except underscore (_) in variable declaration. 6. Variables can be of
unlimited length.
• Python variables do not have to be explicitly declared to reserve memory space. The variable is
declared automatically when the variable is initialized, i.e., when we assign a value to the variable first
time it is declared with the data type of the value assigned to it.
• This means we do not need to declare the variables. This is handled automatically according to the
type of value assigned to the variable. The equal sign (=) i.e., the assignment operator is used to assign
values to variables.
• The operand to the left of the = operator is the name of the variable and the operand to the right of
the = operator is the literal value or any other variable value that is stored in the variable.
Syntax: variable=value Example:
For variable.
>>> a=10
>>> a
10
>>>
• Python language allows assigning a single value to several variables simultaneously. Example:
a=b=c=1
All above three variables are assigned to same memory location, when integer object is created with
value 1.
• Multiple objects can also have assigned to multiple variables:
Example: a, b, c = 10,5.4,"hello"
In above example Integer object a assigned with value 10, float object b assigned with value 5.4 and string
object c assigned with value “hello”.
Example: If x, y, z are defined as three variable in a program, then x = 10 will store the value 10 in the
memory location named as x, y = 5 will store the value 5 in the memory location named as y and x + y
will store the value 15 in the memory location named as z (as a result after computation of x + y).
Python [BBA (CA) - Sem. V] 1.21 Introduction to Python
>>> x = 10
>>> y = 5
>>> name = "Python"
>>> z = x + y
>>> print(x); print(y); print(name); Print
(z) 10
5
Python
15
• Output means the data comes from computer after processing. In Python programming the print()
function display the input value on screen.
Syntax: print(expression/constant/variable) Example:
For output in python.
>>> print ("Hello")
Hello
>>> a="Hello"
>>> b="Python"
>>> print(a+b)
Output:
Python [BBA (CA) - Sem. V] 1.22 Introduction to Python
HelloPython
Formatting Output:
• Sometimes we would like to format our output to make it look attractive. This can be done by using
the str.format() method. This method is visible to any string object.
x = 10; y = 20
print('The value of x is {} and y is {}'.format(x,y))
Output: The value of x is 10 and y is 20
• Here the curly braces {} are used as placeholders. The output is printed according to the order given as
follows:
print('I love {0} and {1}'.format('apple','milk'))
# Output: I love apple and milk print('I love
{1} and {0}'.format('apple','milk'))
# Output: I love milk and apple
1.2.4 Operators
• Python language supports the following types of operators.
o Arithmetic Operators o Comparison
(Relational) Operators o Assignment
Operators o Logical Operators o Bitwise
Operators o Membership Operators o
Identity Operators
• Arithmetic, logical, Relational operators supported by Python language are same as other languages
like C, C++.
1. Arithmetic Operators:
• Arithmetic operators are used to perform mathematical operations like addition, subtraction,
multiplication etc.
Operator Meaning Example
+ Add two operands or unary plus x+y+2
- Subtract right operand from the left or unary minus x–y–2
Program 1.2: For arithmetic operators we will take simple example of addition.
x = 15
y = 4
print('x + y
=',x+y) # Output:
x + y = 19
print('x - y =',x-y)
# Output: x - y = 11
print('x * y =',x*y)
# Output: x * y = 60
print('x / y =',x/y)
# Output: x / y = 3.75
print('x // y =',x//y)
# Output: x // y = 3
print('x ** y
=',x**y) # Output: x **
y = 50625
2. Logical operators:
• The logical operators are used to perform logical operations like (and, or, not) and to combine two or
more conditions to provide a specific result i.e. true or false.
Operator Meaning Example
and True if both the operands are true x and y
or True if either of the operands is true x or y
not True if operand is false (complements the operand) not x
Program 1.3: For Logical operators we will take simple example.
x = 4
print(x > 2 and x <
10) print(x > 2 or x <
Python [BBA (CA) - Sem. V] 1.24 Introduction to Python
4. Assignment Operators:
• Assignment operators are used in Python to assign values to variables.
• a = 5 is a simple assignment operator that assigns the value 5 on the right to the variable a on the left.
Python [BBA (CA) - Sem. V] 1.25 Introduction to Python
• There are various compound operators in Python like a += 5 that adds to the variable and later assigns
the same. It is equivalent to a = a + 5.
• The following are assignment operators in python.
Operator Example Same like
= x=4 x=4
+= x += 4 x=x+4
-= x -= 4 x=x-4
*= x *= 4 x=x*4
/= x /= 4 x=x/4
%= x %= 4 x=x%4
//= x //= 4 x = x // 4
**= x **= 4 x = x ** 4
&= x &= 4 x=x&4
|= x |= 4 x=x|4
^= x ^= 4 x=x^4
Program 1.5: For Assignment operators.
x = 4 x
*= 2
print
(x)
y = 10
y += 5
print(y
) z = 9
z /= 3
print(z)
a = 12
a //= 3
print(a) b
= 5 b **=
3 print(b)
Output:
8
15
3.0
4
125
Python [BBA (CA) - Sem. V] 1.26 Introduction to Python
5. Bitwise Operators:
• Bitwise operators act on operands. It operates bit by bit, hence the name is bitwise.
• For example, 2 is 10 in binary and 7 is 111.
• The following are bitwise operators in python which are same as in C, C++.
Operator Meaning
& bitwise AND: Sets each bit to 1 if both bits are 1
| bitwise OR: Sets each bit to 1 if one of two bits is 1
^ bitwise XOR: Sets each bit to 1 if only one of two bits is 1
~ bitwise NOT: Inverts all the bits
<< bitwise left shift: Shift left by pushing zeros in from the right and let the
leftmost bits fall off
>> bitwise right shift: Shift right by pushing copies of the leftmost bit in from the
left, and let the rightmost bits fall off
Special Operators:
• Python language offers some special type of operators like the identity operator or the membership
operator. They are described below with examples.
1. Identity operators
• is and is not are the identity operators in Python. They are used to check if two values (or variables)
are located on the same part of the memory. Two variables that are equal does not imply that they are
identical.
Operator Meaning Example
is True if the operands are identical (refer to the same object) x is True
is not True if the operands are not identical (do not refer to the same object) x is not True
• Here, we see that x1 and y1 are integers of same values, so they are equal as well as identical. Same is
the case with x2 and y2 (strings).
• But x3 and y3 are list. They are equal but not identical. It is because interpreter locates them
separately in memory although they are equal.
2. Membership operators
• in and not in are the membership operators; used to test whether a value or variable is in a sequence.
(string, list, tuple, set and dictionary). In a dictionary we can only test for presence of key, not the
value.
Operator Meaning Example
in True if value/variable is found in the sequence 5 in x
not in True if value/variable is not found in the sequence 5 not in x
• Here, 'H' is in x but 'hello' is not present in x (remember, Python is case sensitive). Similarly, 1 is key
and 'a' is the value in dictionary y. Hence, 'a' in y returns False.
2. The line after the colon must be indented. It is standard in Python to use four spaces for
indenting.
Program 1.7: Program for if statement.
a = 10 b = 20
if b > a: print("b is
greater than a") Output:
b is greater than a
Program 1.9: Write a program to check whether the number N is even or odd.
N = 4 if N
%2 == 0:
print('Number is Even')
else: print(' Number
is Odd')
Output:
Number is Even
place. If no condition satisfy means evaluate to true then the corresponding action of trailing else is
performed.
Syntax:
if expression:
sequence of statements-1
elif condition-n:
sequence of statements-n
else:
default sequence of statements
a = -10
if a > 0:
print("Positive Number")
else:
print("Negative Number")
#nested if
if -10 <= a:
print("Two digit Negative Number")
Output:
Negative Number
Two digit Negative Number
7
8
9
10
2. for loop:
• The “for” loops in Python executes a certain block of code for a known number of iterations. The
speciality of “for” loop in Python is that the block of code can be iterated for the number of items
existing within a list, dictionary, string variable, over a particular range of numbers in counted number
of steps, and for the number of items existing in a tuple. It has the ability to iterate over the items of
any sequence, such as a list or a string.
Syntax:
for iterating_var in sequence:
statements(s)
• Iterating by Sequence Index: An alternative way of iterating through each item is by index offset into
the sequence itself.
• Syntax:
for i in [Python Iterable]:
expression(i)
Example: Here “Python Iterable” can be a list, tuple or other advanced data structures. for x
in'Hi': print x
print(letter)
Output:
1
a b c
2 a b
c 3 a
b
c
1.5 CONTROL STATEMENTS-BREAK, CONTINUE, PASS
• Python supports the following Loop Control Statements:
1. break Statement:
• Break statement is a jump statement which is used to transfer execution control. It breaks the current
execution and in case of inner loop, inner loop terminates immediately and resumes execution at the
next statement. The break statement can be used in both while and for loops.
Syntax:
break
2. continue Statement:
Python [BBA (CA) - Sem. V] 1.34 Introduction to Python
• It returns the control to the beginning of the while loop. The continue statement rejects all the remaining
statements in the current iteration of the loop and moves the control back to the top of the loop. The
continue statement can be used in both while and for loops.
Syntax: Continue
3. pass Statement:
• It is used when a statement is required syntactically but you do not want any command or code to
execute. The pass statement is a null operation; nothing happens when it executes.
Syntax:
pass
Python [BBA (CA) - Sem. V] 1.35 Introduction to Python
my_string = "Hello"
print(my_string)
my_string = '''Hello'''
print(my_string)
Hello
Hello
Hello, welcome to
the world of Python
String Representation
• In Python, Strings are stored as individual characters in a contiguous memory location.
• The benefit of using String is that it can be accessed from both the directions (forward and backward).
• Both forward as well as backward indexing are provided using Strings in Python.
o Forward indexing starts with 0,1,2,3,....
o Backward indexing starts with -1,-2,-3,-4,....
Example:
Forward
Indexing
0 1 2 3 4 5
strBackward P Y T H O N
Indexing
-6 -5 -4 -3 -2 -1
Fig. 1.22
str[0] = 'P' = str[-6], str[1] = 'Y' = str[-5], str[2] = 'T' = str[-4], str[3] = 'H' = str[-3], str[4] = 'O' = str[-2], str[5] =
'N' = str[-1].
18. max(str): Returns the max alphabetical character from the string str.
19. min(str): Returns the min alphabetical character from the string str.
20. replace(old, new [, max]): Replaces all occurrences of old in string with new or at most max
occurrences if max given.
21. rfind(str, beg=0,end=len(string)): Same as find(), but search backwards in string. 22.
rjust(width,[, fillchar]): Returns a space-padded string with the original string right-justified to a
total of width columns.
23. rstrip(): Removes all trailing whitespace of string.
24. split(str="", num=string.count(str)): Splits string according to delimiter str
(space if not provided) and returns list of substrings; split into at most num substrings if given.
25. splitlines(num=string.count('\n')): Splits string at all (or num) NEWLINEs and returns a list of
each line with NEWLINEs removed.
26. swapcase(): Inverts case for all letters in string.
27. title(): Returns "titlecased" version of string, that is, all words begin with uppercase and the rest
are lowercase.
28. translate(table, deletechars=""): Translates string according to translation table str(256 chars),
removing those in the del string.
29. upper(): Converts lowercase letters in string to uppercase. E.g print s.upper() #s is string.
30. zfill(width): Returns original string leftpadded with zeros to a total of width characters; intended
for numbers, zfill() retains any sign given (less one zero). 31. isdecimal(): Returns true if a unicode
string contains only decimal characters and false otherwise.
32. center(width, fillchar): Returns a space-padded string with the original string centered to a total
of width columns.
33. encode(): Returns encoded string version of string; on error, default is to raise a ValueError unless
errors is given with 'ignore' or 'replace'.
34. index(): Returns Index of Substring
35. find(str, beg=0 end=len(string)): Determine if str occurs in string or in a substring of string if
starting index beg and ending index end are given returns index if found and -1 otherwise.
Program 1.24: Write a Python program to get a string made of the first 2 and the last 2 chars from a given
a string. If the string length is less than 2, return instead of the empty string.
string=raw_input("Enter string:")
count=0 for i in string:
count=count+1
new=string[0:2]+string[count-
2:count] print("Newly formed
string is:")
print(new)
Output:
Python [BBA (CA) - Sem. V] 1.40 Introduction to Python
Examples:
Program 1.25: Write a Python program to get a string from a given string where all occurrences of its first
char have been changed to '$'.
str1input:{"Enter a
String:",} print("Origina1
String:",strl} char = str1[0]
str1 = str1.replace(char, '$')
str1 = char + str1[1:]
print("Replaced String:",str1}
Output:
Enter a String: onion
Original String: onion
Replaced String: oni$n
Program 1.26: Python Program to Replace all Occurrences of ‘a’ with $ in a String.
string=raw_input("Enter
string:")
string=string.replace('a','$')
string=string.replace('A','$')
print("Modified string:")
print(string) Output:
Enter string:Asia
Modified string:
$si$
• We can use the index operator[ ] to access an item in a list. Index starts from 0. So, a list having 5
elements will have index from 0 to 4.
• Trying to access an element other that this will raise an IndexError. The index must be an integer. We
can't use float or other types, this will result into TypeError.
Negative Indexing:
• Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to the
second last item and so on.
Slicing List:
• We can access a range of items in a list by using the slicing operator: (colon).
• Slicing can be best visualized by considering the index to be between the elements. So if we want to
access a range, we need two index that will slice that portion from the list.
• Basic Syntax to Access Python List is:
<list_name>[index] Examples:
list1=[1,2,3,4]
list2=['a','b','c']
print(list1[0])
print(list1[0:2])
print(list2[-3:-1])
print(list1[0:])
print(list2[:2])
Output:
1
[1, 2]
['a', 'b']
[1, 2, 3, 4]
['a', 'b']
1.7.2 List Operation
• Lists respond to the + and * operators much like strings; they mean concatenation and repetition here
too, except that the result is a new list, not a string.
• In fact, lists respond to all of the general sequence operations we used on strings in the previous
section.
Python Expression Results Description
len([4, 5, 6, 7]) 4 Length
[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation
['Hi!'] * 3 ['Hi!', 'Hi!', 'Hi!'] Repetition
3 in [1, 2, 3] True Membership
Python [BBA (CA) - Sem. V] 1.43 Introduction to Python
Creating Tuple:
• A tuple is created by placing all the items (elements) inside a parentheses (), separated by comma. The
parentheses are optional but is a good practice to write it. A tuple can have any number of items and
they may be of different types (integer, float, list, string etc.).
• For example:
tup1 = ("apple", "orange", 2018); tup2 = (1, 2, 3, 4, 5);
tup3 = "a", "b", "c", "d";
• The empty tuple is written as two parentheses containing nothing.
tup1 = ();
• To write a tuple containing a single value you have to include a comma, even though there is only one
value:
tup1 = (50,);
• Like string indices, tuple indices start at 0, and they can be sliced, concatenated, and so on.
# nested tuple
my_tuple = ("Hello", [8, 4, 6], (1, 2, 3))
print(my_tuple)
(1, 2, 3)
(1, 'Hello', 3.4)
('Hello', [8, 4, 6], (1, 2, 3))
(3, 4.6, 'tybca')
3
4.6
tybca
• Using the addition operator +, with two or more tuples, adds up all the elements into a new tuple.
Example: (1, 2, 3) + (4, 5,
6) Output: (1, 2, 3, 4, 5, 6) 2.
Repetition:
• Multiplying a tuple by any integer, x will simply create another tuple with all the elements from the
first tuple being repeated x number of times. For example, t*3 means, elements of tuple t will be
repeated 3 times.
Example: ('Hi!',) * 4
Output: ('Hi!', 'Hi!', 'Hi!', 'Hi!') 3.
Tuple Membership Test using in keyword:
• In keyword, can not only be used with tuples, but also with strings and lists too. It is used to check, if
any element is present in the sequence or not. It returns True if the element is found, otherwise False.
Example:
#in operation tup =
('a','p','p','l','e',)
print('a' in tup) # Output: True
print('b' in tup) # Output:
# Not in operation False
• Tuples are immutable which means you cannot update or change the values of tuple elements. You
are able to take portions of existing tuples to create new tuples as the following example
demonstrates:
tup1 = (10, 32.76)
tup2 = ('abc',
'xyz')
# tup1[0] = 100 is not valid #
So create a new tuple as
follows: tup3 = tup1 + tup2
print tup3
When the above code is executed, it produces the following result:
(10, 32.76, 'abc', 'xyz')
• We can use + operator to combine two tuples. This is also called concatenation.
• We can also repeat the elements in a tuple for a given number of times using the * operator.
>>> (1,) * 5
(1, 1, 1, 1, 1)
• Both + and * operations result into a new tuple. Deleting Tuples
1.8.3.2 Deleting Tuple:
• Removing individual tuple elements is not possible. There is, of course, nothing wrong with putting
together another tuple with the undesired elements discarded.
• To explicitly remove an entire tuple, just use the del statement.
Example:
tup = ("apple", "orange",
2018); print tup del tup print
"After deleting tup: " print tup
Output:
('apple', 'orange', 2018);
After deleting tup:
Traceback (most recent call last):
File "test.py", line 5, in <module>
print tup;
NameError: name 'tup' is not defined
• This produces an exception, this is because after del tup tuple does not exist any more.
Deleting elements of tuple:
• One way to delete the elements from the tuple , we have to convert into list and then perform
deletion.
Program 1.30: Write Python program for deleting elements from Tuple.
# Python program to remove an item from a tuple.
Python [BBA (CA) - Sem. V] 1.50 Introduction to Python
Methods:
Python Tuple Methods:
• A method is a sequence of instructions to perform on something. Unlike a function, it does modify the
construct on which it is called. You call a method using the dot operator in python. Python has two
built-in methods that you can use on tuples.
1. index(x): Return index of first item that is equal to x.
Example:
>>> a=(1,2,3,2,4,5,2)
>>> a.index(2) Output: 1
As you can see, we have 2s at indices 1, 3, and 6. But it returns only the first index.
2. Count(x): Return the number of items is equal to x.
Example:
>>> a=(1,2,3,2,4,5,2)
>>> a.count(2)
Output: 3
Program 1.32: Write a Python program to create a list of tuples with the first element as the number and
second element as the square of the number.
Python [BBA (CA) - Sem. V] 1.52 Introduction to Python
Examples:
Program 1.35: Write a Python program to get the 4th element from front and 4th element from last of a
tuple.
#Get an item of the tuple tuplex = ("p", "y", "t",
"h", "o", "n", "b", "o", "o", "k") print(tuplex)
#Get item (4th element)of the tuple by
index item = tuplex[3] print(item)
#Get item (4th element from last)by index
negative item1 = tuplex[-4] print(item1) Output:
('p', 'y', 't', 'h', 'o', 'n', 'b', 'o', 'o',
'k') h
b
Program 1.36: Write a Python program to find the repeated items of a tuple.
#create a tuple tuplex = 2, 4,
5, 6, 2, 3, 4, 4, 7
print(tuplex)
#return the number of times it appears in the tuple.
count = tuplex.count(4)
print(count)
Output:
(2, 4, 5, 6, 2, 3, 4, 4, 7)
3
Program 1.37: Write a Python program to check whether an element exists within a tuple.
tuplex = ("w", 3, "r", "e", "s", "o", "u", "r", "c",
"e") print("r" in tuplex) print(5 in tuplex) Output:
True
False
• Dictionaries are Python’s implementation of a data structure that is more generally known as an
associative array. A dictionary consists of a collection of key-value pairs.
Each key-value pair maps the key to its associated value.
Creation of Dictionary:
• Creating a dictionary is as simple as placing items inside curly braces {} separated by comma. An item
has a key and the corresponding value expressed as a pair, key: value.
• Each key is separated from its value by a colon (:), the items are separated by commas, and the whole
thing is enclosed in curly braces. An empty dictionary without any items is written with just two curly
braces, like this: {}.
• Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any
type, but the keys must be of an immutable data type such as strings, numbers, or tuples.
Syntax:
dictionary_name =
{ <key>: <value>,
<key>: <value>,
.
.
.
<key>: <value>
}
Or
dictionary_name = dict([
(<key>, <value>),
(<key>, <value),
.
.
.
(<key>, <value>)
])
Where dict is built-in function. Example:
# empty dictionary with name dict
dict = {}
# using dict()
dict = dict({1:'apple', 2:'orange'})
• A dictionary can be updated by adding a new entry or a key-value pair, modifying an existing entry, or
deleting an existing entry as shown below:
Python [BBA (CA) - Sem. V] 1.56 Introduction to Python
Program 1.38:
dict = {'Name': 'abc', 'Age': 20, 'Class': 'tybca'}
dict['Age'] = 22 ; # update existing entry
dict['College'] = "College"; # Add new entry
# add item
dict1['address'] =
'pune'
Program 1.39: Print all key names in the dictionary, one by one.
dict1 = {'name':'Omkar', 'address': 'pune',
'phone':9897965867} for x in dict1: print(x) Output:
phone
name
address
print(dict1)
# Output: {}
3. The pop() method removes the item with the specified key name:
Example using pop(): dict1 = {'name':'Omkar', 'address': 'pune',
'phone':9897965867} dict1.pop('address')
print(dict1)
# Output: {'name':'Omkar', 'phone':9897965867}
4. The popitem() method removes the last inserted item.
Example using popitem(): dict1 = {'name':'Omkar', 'address': 'pune',
'phone':9897965867} dict1.popitem( )
print(dict1)
# Output: {'name':'Omkar', 'address': 'pune'}
Program 1.42: To delete and remove elements from dictionary:
squares = {1:1, 2:4, 3:9, 4:16, 5:25}
# remove a particular item
print(squares.pop(4))
print(squares)
# remove an arbitrary item
print(squares.popitem())
print(squares)
# delete a particular
item del squares[3]
print(squares) # remove
all items
squares.clear()
print(squares)
# delete the dictionary
itself del squares
print(squares) Output:
16
{1: 1, 2: 4, 3: 9, 5: 25}
(1, 1)
{2: 4, 3: 9, 5: 25}
{2: 4, 5: 25}
{}
NameError: name 'squares' is not defined
Python [BBA (CA) - Sem. V] 1.59 Introduction to Python
1.9.3 Properties
• Dictionary values have no restrictions. They can be any arbitrary Python object, either
standard objects or user-defined objects. However, same is not true for the keys.
• There are two important points to remember about dictionary keys:
(a) More than one entry per key not allowed. Which means no duplicate key is allowed. When
duplicate keys encountered during assignment, the last assignment wins.
(b) Keys must be immutable. Which means you can use strings, numbers or tuples as dictionary
keys but something like [‘key’] is not allowed.
• In a dictionary, we can add any number of values for one key. Python object, either standard objects or
user-defined objects.
Example:
>>> d = {0: 'a', 1: 'a', 2: 'a', 3: 'a'}
>>> d
{0: 'a', 1: 'a', 2: 'a', 3: 'a'}
>>> d[0] == d[1] == d[2]
True
• More than one entry per key not allowed. Which means no duplicate key is allowed. When duplicate
keys encountered during assignment, the last assignment wins, means the second occurrence will
override the first.
Example:
dict = {'Name': 'Omkar', 'Age': 20, 'Name':
'Mani'} print "dict['Name']: ", dict['Name'] Output:
dict['Name']: Mani
• Keys must be immutable. Which means you can use strings, numbers or tuples as dictionary keys but
something like ['key'] is not allowed.
Example:
dict = {['Name']: 'Omkar', 'Age': 20}
print "dict['Name']: ", dict['Name']
# Output: error
Program having a tuple as a dictionary key, because tuples are immutable:
>>> d = {(1, 1): 'a', (1, 2): 'b', (2, 1): 'c', (2,
2):'d'}
>>> d[(1,1)]
'a'
>>> d[(2,1)]
'c'
Python [BBA (CA) - Sem. V] 1.60 Introduction to Python
dict.update(dict1)
print("Value: %s" % dict)
Examples:
Program 1.44: Write a Python script to sort (ascending and descending) a dictionary by value.
import operator d = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} print('Original
dictionary : ',d) sorted_d = dict(sorted(d.items(),
key=operator.itemgetter(1))) print('Dictionary in ascending order by
value : ',sorted_d) sorted_d = dict(sorted(d.items(),
key=operator.itemgetter(1),reverse=True))
print('Dictionary in descending order by value :
',sorted_d) Output:
Original dictionary : {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
Dictionary in ascending order by value : {0: 0, 2: 1, 1: 2, 4: 3, 3:
4}
Dictionary in descending order by value : {3: 4, 4: 3, 1: 2, 2: 1, 0:
0}
Python [BBA (CA) - Sem. V] 1.62 Introduction to Python
Program 1.46: Write a Python script to check if a given key already exists in a dictionary.
d = {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6:
60} def is_key_present(x): if x in d:
print('Key is present in the dictionary')
else:
print('Key is not present in the
dictionary') is_key_present(5)
is_key_present(9) Output:
Key is present in the dictionary
Key is not present in the dictionary
Program 1.47: Write a Python program to iterate over dictionaries using for loops.
d = {'x': 10, 'y': 20, 'z': 30}
for dict_key, dict_value in
d.items():
print(dict_key,'->',dict_value)
Output:
y -> 20
z -> 30
x -> 10
Program 1.48: Write a Python script to generate and print a dictionary that contains a number (between 1
and n) in the form (x, x*x). Sample Dictionary (n = 5) : Expected Output
: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Python [BBA (CA) - Sem. V] 1.63 Introduction to Python
n=int(input("Input a number
")) d = dict()
for x in range(1,n+1):
d[x]=x*x
print(d) Output:
10
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100}
Program 1.49: Write a Python script to print a dictionary where the keys are numbers between 1 and 15
(both included) and the values are square of keys. d=dict() for x in range(1,16):
d[x]=x**2
print(d) Output:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100,
11:
121, 12: 144, 13: 169, 14: 196, 15: 225}
Program 1.50: Write a Python program to combine two dictionary adding values for common keys. d1 =
{'a': 100, 'b': 200, 'c':300} d2 = {'a': 300, 'b': 200, 'd':400}
Sample output: Counter({'a': 400, 'b': 400, 'd': 400, 'c':
300}) from collections import Counter d1 = {'a': 100, 'b':
200, 'c':300} d2 = {'a': 300, 'b': 200, 'd':400} d =
Counter(d1) + Counter(d2) print(d)
Program 1.51: Write a Python program to create and display all combinations of letters, selecting each
letter from a different key in a dictionary. Sample data :
{'1':['a','b'], '2':['c','d']} Expected Output:
ac
ad
bc
bd
import itertools
d ={'1':['a','b'], '2':['c','d']} for combo in
itertools.product(*[d[k] for k in sorted(d.keys())]):
print(''.join(combo))
Python [BBA (CA) - Sem. V] 1.64 Introduction to Python
Program 1.52: Write a Python program to create a dictionary from two lists without losing duplicate
values.
Sample lists: ['Class-V', 'Class-VI', 'Class-VII', 'Class-VIII'], [1, 2, 2, 3]
Expected Output: defaultdict(<class 'set'>, {'Class-VII': {2},
'Class-VI':
{2}, 'Class-VIII': {3}, 'Class-V': {1}})
from collections import defaultdict
class_list = ['Class-V', 'Class-VI', 'Class-VII', 'Class-
VIII'] id_list = [1, 2, 2, 3] temp = defaultdict(set) for
c, i in zip(class_list, id_list):
temp[c].add(i)
print(temp) Program 1.53:
Write a Python program to match
key values in two dictionaries.
Sample dictionary: {'key1': 1, 'key2':
3, 'key3': 2}, {'key1': 1, 'key2': 2}
Expected output: key1: 1 is present
in both x and y.
1. To makes the code easier to manage, debug, and scale, functions are used.
2. Every time you need to execute a sequence of statements, all we need to do is to call the function,
so that we can reuse the code.
3. Functions allow us to change functionality easily, and different programmers can work on different
functions.
"""function_docstring"
"" function_body
return [expression]
• By default, parameters have a positional behavior and you need to inform them in the same order that
they were defined. Every function must be defined before it is called.
• How function works in Python:
def functionName():
... .. ...
... .. ...
... .. ...
... .. ...
functionName(); .
.. .. ...
... .. ...
Fig. 1.23
Example:
# function without parameters
def my_function():
Python [BBA (CA) - Sem. V] 1.66 Introduction to Python
Example:
# Function definition is here
def func( str ):
"This prints a string passed into this
function" print str return;
# calling func function
func( str = "TYBBA")
Output:
TYBBA
Example:
# Function definition is here
def mydata( name, age ):
Python [BBA (CA) - Sem. V] 1.70 Introduction to Python
3. Default arguments:
• A default argument is an argument that assumes a default value if a value is not provided in the function
call for that argument.
Example:
# Function definition is here
def mydata( name, age = 40 ):
"This prints a passed info into this
function" print "Name: ", name print
"Age: ", age return;
# calling mydata function
mydata( age=50, name="manisha" )
mydata( name="manisha" )
Output:
Name: manisha
Age: 50
Name: manisha
Age: 40
Example:
# function to calculate the square of the sum of two
numbers def nsquare(x, y = 2):
return (x*x + 2*x*y + y*y)
print("The square of the sum of 2 and 2 is: ",
nsquare(2)) print("The square of the sum of 2 and 3 is: ",
nsquare(2,4)) Output:
The square of the sum of 2 and 2 is: 16
The square of the sum of 2 and 4 is: 36
Python [BBA (CA) - Sem. V] 1.71 Introduction to Python
Required Arguments:
• Required arguments are the arguments passed to a function in correct positional order.
• The number of arguments in the function call should match exactly with the function definition.
# Function definition is here
def printme( str ):
"This prints a passed string into this
function" print str return; # calling
function printme() Output:
Traceback (most recent call last):
File "test.py", line 11, in
<module> printme();
TypeError: printme() takes exactly 1 argument (0 given)
Variable-length Arguments:
• The function can have more arguments than the arguments defining the function.
• These arguments are called variable-length arguments and are not named in the function definition,
unlike required and default arguments.
Syntax:
def functionname([formal_args,] *var_args_tuple ):
"function_docstring"
function_suite
return [expression]
• An asterisk (*) is placed before the variable name that holds the values of all nonkeyword variable
arguments. This tuple remains empty if no additional arguments are specified during the function call.
Example:
# Function definition is here def
printinfo( arg1, *vartuple ): "This
prints a variable passed arguments"
print "Output is: " print arg1 for
var in vartuple:
print var
return;
# call printinfo
function printinfo( 10 )
printinfo( 70, 60, 50 )
Output:
Output is:
Python [BBA (CA) - Sem. V] 1.72 Introduction to Python
10
Output is:
70
60
50
return
Statement:
• The statement return [expression] exits a function, optionally passing back an expression to the caller.
A return statement with no arguments is the same as return None.
• def function_name(argument1, argument2, ...):
statement_1
statement_2
.... return expression
function_name(arg1,
arg2)
Example: The following function returns the square of the sum of two numbers.
def nsquare(x, y):
return (x*x + 2*x*y + y*y)
print("The square of the sum of 2 and 3 is: ", nsquare(2,
3)) Output:
The square of the sum of 2 and 3 is: 25
>>>
Square of number is 100
>>>
• Variables that are defined inside a function body have a local scope, and those defined outside have a
global scope.
• The local variables can be accessed only inside the function in which they are declared, whereas
global variables can be accessed throughout the program body by all functions.
• When you call a function, the variables declared inside it are brought into scope.
Program 1.56:
sum = 0; # This is global variable.
# Function definition
def sumfunc( arg1, arg2 ):
# add both the parameters and return them."
sum = arg1 + arg2; # Here sum is local
variable. print "Inside the function local
sum: ", sum return sum;
# calling sumfunc function
sumfunc( 100, 200 );
print "Outside the function global sum: ", sum
Output:
Inside the function local sum: 300
Outside the function global sum: 0
Nonlocal Variables:
• Nonlocal variable are used in nested function whose local scope is not defined. This means, the
variable can be neither in the local nor the global scope.
• In the following code , we use nonlocal keyword to create nonlocal variable.
def outer(): x =
"local" def
inner():
nonlocal x x =
"nonlocal"
print("inner:",
x) inner()
print("outer:",
x) outer()
Python [BBA (CA) - Sem. V] 1.75 Introduction to Python
Program 1.61: Write a Python Program to Calculate the Average of Numbers in a Given
List.
ele=[2,4,6,7,8]
def avg(ele):
return sum(ele)/len(ele)
print("average : ",round(avg(ele),1))
Output:
average : 5.4
Python [BBA (CA) - Sem. V] 1.77 Introduction to Python
Program 1.62: Write a recursive function which print string in reverse order.
def rec(s): if
(len(s)==0): return s
else: return rec(s[1:])
+s[0]
Program 1.64: Write a function which prints a dictionary where the keys are numbers between 1 and 20
(both included) and the values are square of keys.
d={} def
createdict(d): for i
in range(1,21):
d[i]=i**2 return
d
Additional Programs
range(4+1): for j
in range(4-i):
print(a[j],end=" ")
print(" ")
Python [BBA (CA) - Sem. V] 1.80 Introduction to Python
dig=n%10 tot=tot+dig
n=n//10
print("The total sum of digits is:",tot)
Output:
Enter a number:156
The total sum of digits is: 12
Program 1.73: Write a program which accept an integer value ‘n’ and display all prime numbers till ‘n’.
# Python program to ask the user for a range and display all the prime
numbers in that interval
# uncomment to take input from the user
# lower = int(input("Enter lower range:
")) # upper = int(input("Enter upper
range: ")) lower = 10 upper = 20
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num)
Output:
11
13
17
19
Summary
Python is an open source, object-oriented, high-level powerful programming language.
A data type is a set of values, and a set of operators that may be applied to those values. Python
supports five basic numerical types namely Numbers, String, List, Tuple and Dictionary.
String in Python are surrounded by either single quotation marks, or double quotation marks such as
'hello' is the same as "hello".
String is a sequence of characters. Strings in Python are arrays of bytes representing unicode
characters.
Variable is a name which is used to refer memory location. Variable also known as identifier and
used to hold value. The period of time that a variable exists is called its lifetime.
Python variables do not need explicit declaration to reserve memory space. The declaration
happens automatically when you assign a value to a variable. The equal sign (=) is used to assign
values to variables.
A local variable is a variable that is only accessible from within a given function. Such variables are
said to have local scope. In Python, any variable assigned a value in a function becomes a local
variable of the function.
A global variable is a variable that is defined outside of any function definition. Such variables are
said to have global scope.
Tuple is another data type which is a sequence of data similar to list.
Python Dictionary is an unordered sequence of data of key-value pair form.
Python operators can be classified into several categories such as arithmetic, logical, comparison,
bitwise and assignment.
A control statement is a statement that determines the control flow of a set of instructions. A
control structure is a set of instructions and the control statements controlling their execution.
Three fundamental forms of control in programming are sequential, selection, and iterative
control.
Python list is enclosed between square ([]) brackets and elements are stored in the index basis with
starting index 0.
A list is a container which holds comma-separated values (items or elements) between square
brackets where items or elements need not all have the same type. A tuple in Python is an
immutable linear data structure, denoted by a commaseparated list of elements within
parentheses, allowing mixed-type elements.
A tuple is a sequence of immutable objects, therefore tuple cannot be changed. It can be used to
collect different types of object.
Dictionary is an unordered set of key and value pair. It is a container that contains data, enclosed
within curly braces. The pair i.e., key and value is known as item.
Python [BBA (CA) - Sem. V] 1.84 Introduction to Python
Functions are a construct to structure programs. They are known in most programming languages,
sometimes also called subroutines or procedures. Functions are used to utilize code in more than
one place in a program.
Function in Python is defined by the "def" statement followed by the function name and
parentheses ( () ).
Inside the function, the arguments are assigned to variables called parameters.
Practice Questions
Q.I Answer the following Questions in short:
1. Which are data types in Python?
2. What are the types of variables?
3. Which are the different conditional statements?
4. What is looping?
5. What is operator?
6. List out python basic operators.
7. List out loop control statements.
8. Which are special operators in Python?
9. What are the different types of function?
10. How to call function?
11. What is string slice?
12. How to select an element from List?
13. What is the difference between Xrange and range?
14. How to delete tuple?
15. Explain any two tuple operations with an example.
16. List out different dictionary function. Q.II Answer the following Questions:
1. Explain Loop control statements used in Python?
2. Write a python program to display fibonnacci series.
3. Write python program to check whether number is even or odd.
4. Write a python program to display Prime numbers between given range.
5. Write program to find factorial of given number.
6. Write a program which finds sum of digits of a number.
7. Explain any five built-in List functions.
Python [BBA (CA) - Sem. V] 1.86 Introduction to Python
Learning Objectives …
▣ To learn Concepts of Files.
▣ To study Modules. ▣ To
understand Packages.
2.1 INTRODUCTION
• In Python, packages allow us to create a hierarchical file directory structure of modules. For example,
mymodule.mod1 stands for a module mod1, in the package my module.
• A Python package is a collection of modules which have a common purpose. In short, modules are
grouped together to forms packages.
• A file is a collection of related data that acts as a container of storage as data permanently. The file
processing refers to a process in which a program processes and accesses data stored in files.
• A file is a computer resource used for recording data in a computer storage device. The processing on a
file is performed using read/write operations performed by programs.
• Python supports file handling and allows users to handle files i.e., to read and write files, along with
many other file handling options, to operate on files.
• Python programming provides modules with functions that enable us to manipulate text files and
binary files. Python allows us to create files, update their contents and also delete files.
• Files are named locations on disk to store related information. They are used to permanently store data
in a non-volatile memory (e.g. hard disk).
• A text file is a file that stores information in the term of a sequence of characters (textual information),
whiles a binary file stores data in the form of bits (0s and 1s) and used to store information in the form
of text, images, audios, videos etc.
• The file handling plays an important role when the data needs to be stored permanently into the file. A
file is a named location on disk to store related information.
(2.1)
• We can access the stored information (non-volatile) after the program termination. Python has several
functions for creating, reading, updating, and deleting files.
• When an error occurs, or exception as we call it, Python will normally stop and generate an error
message. Exception in Python is nothing but errors which are encountered at the run time.
Python [BBA (CA) - Sem. V] 2.2 Modules and Packages
• Exception Handling is the mechanism it is allow us to handle errors very smartly while the program is
running.
2.2 MODULES
• Modules are primarily the (.py) files which contain Python programming code defining functions,
class, variables, etc. with a suffix .py appended in its file name. A file containing .py python code is
called a module.
• If we want to write a longer program, we can use file where we can do editing, correction. This is
known as creating a script. As the program gets longer, we may want to split it into several files for
easier maintenance.
• We may also want to use a function that we have written in several programs without copying its
definition into each program.
• In Python we can put definitions in a file and use them in a script or in an interactive instance of the
interpreter. Such a file is called a module.
• Modules and packages are constructs in Python programming that promote code modularization.
• The modularization (modular programming) refers to the process of breaking a large programming task
into separate, smaller, more manageable subtasks or modules.
• A module in Python programming allows us to logically organize the python code. A module is a
single source code file. The module in Python have the .py file extension. The name of the module will
be the name of the file.
• A python module can be defined as a python program file which contains a python code including
python functions, class, or variables. In other words, we can say that our Python code file saved with
the extension (.py) is treated as the module.
• Imports the module x, and creates references in the current namespace to all public objects defined by
that module. If we run this statement, we can simply use a plain name to refer to things defined in
module x.
• We can access attribute / mehods directly without dot notation.
2. From x import a, b, c:
• Imports the module x and creates references in the current namespace to the given objects. Or we can use
a, b and c function in our program.
3. From x import *:
• We can use * (asterisk) operator to import everything from the module.
Python [BBA (CA) - Sem. V] 2.5 Modules and Packages
>>> floor(1.001)
1
>>> factorial(5)
120
>>> trunc(1.115)
1
>>> sin(90)
0.8939966636005579
>>> cos(60)
-0.9524129804151563
>>> exp(5)
148.4131591025766
>>> log(16)
2.772588722239781
>>> log(16,2)
4.0
>>> log(16,10)
1.2041199826559246
>>> pow(144,0.5)
12.0
>>> sqrt(144)
12.0
>>>
2. Decimal Module:
• Decimal numbers are just the floating-point numbers with fixed decimal points. We can create decimals
from integers, strings, floats, or tuples.
• A Decimal instance can represent any number exactly, round up or down, and apply a limit to the
number of significant digits.
3. Fractions Module:
• A fraction is a number which represents a whole number being divided into multiple parts. Python
fractions module allows us to manage fractions in our Python programs.
• It is also possible to convert a decimal into a Fractional number. Let’s look at a code snippet:
>>> import fractions
>>> for deci in ['0.6', '2.5', '2.3', '4e-1']:
fract = fractions.Fraction(deci)
print(fract)
Output:
3/5
5/2
23/10
2/5
>>>
4. Statistics Module:
• Statistics module provides access to different statistics functions. Example includes mean (average
value), median (middle value), mode (most often value), standard deviation (spread of values).
Python [BBA (CA) - Sem. V] 2.8 Modules and Packages
• A date in Python is not a data type of its own, but we can import a module named datetime to work with
dates as date objects.
Example: Import the datetime module and display the current date: import
datetime x = datetime.datetime.now()
print(x) Output:
2021-07-24 12:41:12.701464
• The date contains year, month, day, hour, minute, second, and microsecond.
• The datetime module has many methods to return information about the date object.
Example:
import datetime x =
datetime.datetime(2021, 7, 24)
print(x.strftime("%B")) Output:
July
o
• The constants used with datetime are as follows: class datetime.date
An idealized naive date, assuming the current Gregorian calendar always was, and always will be, in effect.
Attributes: year, month, and day.
o
class datetime.time
An idealized time, independent of any particular day, assuming that every day has exactly 24*60*60
seconds. Attributes: hour, minute, second, microsecond, and tzinfo.
Python [BBA (CA) - Sem. V] 2.10 Modules and Packages
o
class datetime.datetime
A combination of a date and a time. Attributes: year, month, day, hour, minute, second, microsecond,
o
and tzinfo. class datetime.timedelta
A duration expressing the difference between two date, time, or datetime instances to microsecond
o
resolution. class datetime.tzinfo
An abstract base class for time zone information objects. These are used by the datetime and time classes to
provide a customizable notion of time adjustment (for example, to account for time zone and/or
daylight saving time).
7. Calendar:
• This module allows you to output Gregorian calendars and provides additional useful functions related
to the calendar.
o
class calendar.Calendar(firstweekday=0)
• Creates a Calendar object. firstweekday is an integer specifying the first day of the week. 0 is Monday
(the default), 6 is Sunday.
• A Calendar object provides several methods that can be used for preparing the calendar data for
formatting.
Example:
# Python program to display calendar of given month of the
year import calendar yy = 2017 mm = 11
# display the calendar
print(calendar.month(yy, mm)) Output:
Example:
Output:
8. sys module:
• The sys module in Python provides various functions and variables that are used to manipulate
different parts of the Python runtime environment. It allows operating on the interpreter as it provides
access to the variables and functions that interact strongly with the interpreter.
Example:
# sys.version is used which returns a string containing the
version of Python Interpreter with some additional information.
>>> import sys
>>> print(sys.version)
3.9.6 (tags/v3.9.6:db3ff76, Jun 28 2021, 15:26:21)
[MSC v.1929 64 bit (AMD64)]
>>>
• The sys modules provide variables for better control over input or output. We can even redirect the
input and output to other devices. This can be done using three variables:
o stdin o
stdout o
stderr
1. stdin: It can be used to get input from the command line directly. It is used for standard input. It
internally calls the input() method. It, also, automatically adds ‘\n’ after each sentence.
Python [BBA (CA) - Sem. V] 2.12 Modules and Packages
Example:
import sys for line in
sys.stdin: if 'q' ==
line.rstrip(): break
print(f'Input:
{line}')
print("Exit")
Output:
======= RESTART:
C:/Users/HP/AppData/Local/Programs/Python/Pyton39/ tre.py ======
tybba Input : tybba yes
Input : yes
2. stdout: A built-in file object that is analogous to the interpreter’s standard output stream in Python.
stdout is used to display output directly to the screen console. import sys
sys.stdout.write('tybba')
Output:
Tybba
3. Stderr: Whenever an exception occurs in Python it is written to sys.stderr.
2.2.4 Working with Random Modules
Random Module:
• Sometimes, we want the computer to pick a random number in a given range, pick a random element
from a list etc.
• The random module provides functions to perform these types of operations. This function is not
accessible directly, so we need to import random module and then we need to call this function using
random static object.
Methods:
1. randrange: Generates integer between lower to upper argument. By default lower bound is 0.
Example:
Python [BBA (CA) - Sem. V] 2.13 Modules and Packages
• All the functions that are written by any us comes under the category of user defined functions. Below
are the steps for writing user defined functions in Python. o In Python, def keyword is used to declare
user defined functions.
o An indented block of statements follows the function name and arguments which contains the body
of the function. Syntax: def function_name(): statements .
.
Calling a Function:
• Defining a function only gives it a name, specifies the parameters that are to be included in the
function and structures the blocks of code.
• Once the basic structure of a function is finalized, you can execute it by calling it from another
function or directly from the Python prompt.
• To call a function means that you are telling the program to execute the function. To call the function,
you write the name of the function followed by parentheses. In case you need to pass
parameters/arguments to the function, you write them inside the parentheses.
• If there is a return value defined, the function would return the value, else the function would return
none. Syntax: function_name(arg1, arg2)
Example:
# Declaring a function
def fun():
print("Inside function")
# Calling function
fun()
Output:
Inside function
Example:
def avg_number(x, y):
print("Average of ",x," and ",y, " is
",(x+y)/2) avg_number(3, 4) Output:
Average of 3 and 4 is 3.5
• If we want to write a longer program, we can use file where we can do editing, correction. This is
known as creating a script. As the program gets longer, we may want to split it into several files for
easier maintenance.
• We may also want to use a function that we have written in several programs without copying its
definition into each program.
• In Python we can put definitions in a file and use them in a script or in an interactive instance of the
interpreter. Such a file is called a module.
2.4 PACKAGES
• Suppose we have developed a very large application that includes many modules. As the number of
modules grows, it becomes difficult to keep track of them all as they have similar names or
functionality.
• It is necessary to group and organize them by some mean which can be achieved by packages.
• A package is a hierarchical file directory structure that defines a single Python application
environment that consists of modules and subpackages and
sub-subpackages and so on.
• Packages allow for a hierarchical structuring of the module namespace using dot notation. Packages
are a way of structuring many packages and modules which help in a well-organized hierarchy of data
set, making the directories and modules easy to access.
• A package is a collection of Python modules, i.e., a package is a directory of Python modules
containing an additional _ _init_ _.py file (For example: Phone/_ _init_ _.py).
Fig. 2.1
• Here mypack a folder/directory which consist of p1.py and p2.py. We can refer these two modules
with dot notation (mypack.p1, mypack.p2) and import them with the one of the following
syntaxes:
Syntax 1: import <module_name>[, <module_name> ...]
Example:
>>> import mypack.p1,mypack.p2
Python [BBA (CA) - Sem. V] 2.16 Modules and Packages
>>> mypack.p1.m1()
first module
>>> p1.m1()
• Some of the most popular mathematical functions are defined in the math module. These include
trigonometric functions, representation functions, logarithmic functions and angle conversion
functions.
• Two mathematical constants are also defined in math module.
• Pie (π) is a well-known mathematical constant, which is defined as the ratio of the circumference to
the diameter of a circle and its value is 3.141592653589793.
• Another well-known mathematical constant defined in the math module is e. It is called Euler's number
and it is a base of the natural logarithm. Its value is 2.718281828459045.
NumPy:
• NumPy is the fundamental package for scientific computing with Python. NumPy stands for
"Numerical Python". It provides a high-performance multidimensional array object, and tools for
working with these arrays.
• An array is a table of elements (usually numbers), all of the same type, indexed by a tuple of positive
integers and represented by a single variable. NumPy's array class is called ndarray. It is also known by
the alias array.
• In NumPy arrays, the individual data items are called elements. All elements of an array should be of
the same type. Arrays can be made up of any number of dimensions.
• In NumPy, dimensions are called axes. Each dimension of an array has a length which is the total
number of elements in that direction.
• The size of an array is the total number of elements contained in an array in all the dimension. The size
of NumPy arrays are fixed; once created it cannot be changed again.
• Numpy arrays are great alternatives to Python Lists. Some of the key advantages of Numpy arrays are
that they are fast, easy to work with, and give users the opportunity to perform calculations across
entire arrays.
SciPy:
• SciPy is a library that uses NumPy for more mathematical functions. SciPy uses NumPy arrays as the
basic data structure, and comes with modules for various commonly used tasks in scientific
programming, including linear algebra, integration (calculus), ordinary differential equation solving,
and signal processing. Matplotlib:
• matplotlib.pyplot is a plotting library used for 2D graphics in python programming language. It can be
used in python scripts, shell, web application servers and other graphical user interface toolkits.
Python [BBA (CA) - Sem. V] 2.18 Modules and Packages
• There are various plots which can be created using python matplotlib like bar graph, histogram, scatter
plot, area plot, pie plot.
Pandas:
• Pandas is an open-source Python Library providing high-performance data manipulation and analysis
tool using its powerful data structures.
• It is built on the NumPy package and its key data structure is called the DataFrame. DataFrames allow
us to store and manipulate tabular data in rows of observations and columns of variables.
def SayHello(name):
print("Hello " + name) return
Mathematics.py
def sum(x,y):
return x+y
def average(x,y):
return (x+y)/2
def power(x,y):
return x**y
Step 2: Create an empty _ _init_ _.py file in the Mypack folder. The package folder contains a special file
called _ _init_ _.py, which stores the package's content. It serves two purposes:
1.
The Python interpreter recognizes a folder as the package if it contains _ _init_
_.py file.
2. _ _init_ _.py exposes specified resources from its modules to be imported.
An empty _ _init_ _.py file makes all functions from above modules available when this package is
imported. Note that _ _init_ _.py is essential for the folder to be recognized by Python as a package.
We can optionally define functions from individual modules to be made available.
Step 3: Create P1.py file in Mypack folder and write following code:
Python [BBA (CA) - Sem. V] 2.19 Modules and Packages
= student['year'] def
get_student_details(self):
return f"Name: {self.name}\nGender: {self.gender}\nYear:
{self.year}"
# faculty.py
class Faculty:
def __init__(self, faculty): self.name =
faculty['name'] self.subject =
faculty['subject'] def
get_faculty_details(self): return f"Name:
{self.name}\nSubject: {self.subject}"
• We have the above in the student.py and faculty.py files. Let's create another file to access those classed
inside it. Now, inside the package directory create a file named testing.py and include the following
code:
# testing.py
# importing the Student and Faculty classes from respective
files from student import Student from faculty import
Faculty
# creating dicts for student and faculty student_dict =
{'name': 'Ram', 'gender': 'Male', 'year': '3'}
faculty_dict = {'name': 'Radha', 'subject': 'Programming'}
# creating instances of the Student and Faculty classes
student = Student(student_dict) faculty =
Faculty(faculty_dict)
# getting and printing the student and faculty
details print(student.get_student_details())
print()
print(faculty.get_faculty_details())
Output:
Name: Ram
Gender: Male
Year: 3
Name: Radha
Subject: Programming
• We have seen how to create and to access a package in Python. And this is a simple package. There
might be plenty of sub-packages and files inside a package. Let's see how to access subpackage
modules.
• Create a directory with the following structure: Package (university) o __init__.py o
Subpackage (student) __init__.py main.py
...
Python [BBA (CA) - Sem. V] 2.21 Modules and Packages
o testing.py
• Copy the above student code and place it here. Now, let's see how to access it in the testing.py file. Add
the following in the testing.py file.
Program 2.2:
# testing.py from student.main import Student #
creating dicts for student student_dict = {'name': 'Ram',
'gender': 'Male', 'year': '3'}
# creating instances of the Student class
student = Student(student_dict)
# getting and printing the student details
print(student.get_student_details()) If you run the testing.py
file, then you will get the following result. Output:
Name: Ram
Gender: Male
Year: 3
dtype: int32
>>>
Program 2.11: Write a Python function to multiply all the numbers in a list. SampleList:(8,2,3,-1,7)
Expected Output: -336 Code:
def mul(str):
sum=1 for i in
str: sum = sum*i
return sum str =
[8,2,3,-1,7]
print(str) print
(mul(str)) Output:
string [8, 2, 3, -1, 7]
-336
Program 2.12: Write a Python function to check whether a number is in a given range. Code:
def ran(n,m):
if n in
range(m):
print("number is in range")
else:
print("number is out is range")
m=int(input("enter range from 1 to: "))
n=int(input("enter number: "))
ran(n,m+1)
Output:
enter range from 1 to:
10 enter number: 5
number is in range
enter range from 1 to:
10 enter number: 11
number is out is range
Program 2.13: Create a function showEmployee() in such a way that it should accept employee name, and
it’s salary and display both, and if the salary is missing in function call it should show it as 9000 Code:
def
show_emp(name,sal=9000):
Python [BBA (CA) - Sem. V] 2.25 Modules and Packages
Program 2.14: Write a Python function that takes a number as a parameter and check the number is prime
or not. Code:
def checkforprime(m):
if m>1:
for i in range(2,m):
if(m%i)==0: return 0
return 1 n=int(input("enter
number: "))
a=checkforprime(n) if a==1:
print(n,": is prime")
else: print(n,": is not
prime") Output:
enter number: 5
5: is prime enter
number: 10 10: is
not prime
Program 2.15: Write a generator function that reverses a given string. Code:
def rev(str):
return str[::-1]
n=input("input string")
print("string: ",n) print("reversed
string: ",rev(n)) Output:
input stringakshay
string: akshay
reversed string:
yahska
Program 2.16: Write a recursive function to calculate the sum of numbers from 0 to 10. Code:
def sum(n):
if n<=1:
return n
else:
return n+sum(n-1)
print("sum: ",sum(10)) Output:
Python [BBA (CA) - Sem. V] 2.26 Modules and Packages
sum: 55
Summary
A module in Python programming allows us to logically organize the python code. A module is a
single source code file. The module in Python have the .py file extension. The name of the module
will be the name of the file.
In Python, packages allow us to create a hierarchical file directory structure of modules. For
example, mymodule.mod1 stands for a module mod1, in the package mymodule.
A Python package is a collection of modules which have a common purpose. In short, modules are
grouped together to forms packages.
The import statement is used to imports a specific module by using its name.
A module is a collection of Python objects such as functions, classes, and so on. Python interpreter
is bundled with a standard library consisting of large number of built-in modules,
math and cmath, Decimal Module, Fractions Module, Statistics Module, itertools Module, functools
Module, Operator Module, Time Module are built in modules having several functions
Datetime, calendar modules will display the date, time, and calendar.
The sys modules provide variables for better control over input or output. We can even redirect the
input and output to other devices. This can be done using three variables – stdin, stdout, stderr
The random module provides functions to perform these types of operations. This function is not
accessible directly, so we need to import random module and then we need to call this function
using random static object.
Function blocks begin with the keyword def followed by the function name and parentheses ( ).
Any input parameters or arguments should be placed within these parentheses. You can also define
parameters inside these parentheses.
A package is a hierarchical file directory structure that defines a single Python application
environment that consists of modules and subpackages and subsubpackages and so on.
A package is a collection of Python modules, i.e., a package is a directory of Python modules
containing an additional _ _init_ _.py file (For example: Phone/_ _init_
_.py).
NumPy and SciPy are the standards packages used by Python programming. matplotlib.pyplot is a
plotting library used for 2D graphics in python.
Pandas is an open-source Python Library providing high-performance data manipulation and analysis
tool using its powerful data structures.
Practice Questions
Q I. Answer the following questions in short.
1. What is module? Write the steps of creating the module.
2. What is the use of import statement?
Python [BBA (CA) - Sem. V] 2.28 Modules and Packages
Learning Objectives …
▣ To learn about Classes, Object and Inheritance in Python.
▣ To understand concept Classes as User Defined Data Types.
▣ To know about Object as Instance of Classes.
▣ To study Variables and methods in class.
▣ To learn Inheritance in details.
▣ To understand IS-A Relationship and HAS-A Relationship.
• An Object is an instance of a Class. A class is like a blueprint while an instance is a copy of the class
with actual values. It's not an idea anymore, it's an actual dog, like a dog of breed pug who's seven
years old. You can have many dogs to create many different instances, but without the class as a guide,
you would be lost, not knowing what information is required.
• An object consists of : o State: It is represented by the attributes of an object. It also reflects the
properties of an object.
o Behavior: It is represented by the methods of an object. It also reflects the response of an object to
other objects.
o Identity: It gives a unique name to an object and enables one object to interact with other objects.
3.1.1 Classes as User Defined Data Type
• A class in python is user defined data type.
• A class combination of data member and member function.
• The data member and member functions of a class can be accessed after creating an instance of a class.
• Instance of class is known as Object.
• We can define a custom data type by creating a class in Python.
Example:
class Data:
pass d=Data()
print(type(d))
Output:
<class '__main__.Data'>
Here Data is the user define class and d is the object of the class.
Program 3.1: Create a class named Person, use the __init__() function to assign values for name and age.
Python [BBA (CA) - Sem. V] 3.3 Classes, Objects and Inheritance
p1 = Person("Omkar", 26)
print(p1.name)
print(p1.age) Output:
Omkar
26
o The self-argument refers to the object itself. Hence the use of the word self. So inside
this method, self will refer to the specific instance of this object that's being operated on. o
Self is the name preferred by convention by Pythons to indicate the first parameter of
instance methods in Python. It is part of the Python syntax to access members of objects.
Step 4 : To make an object of the class.
c = myClass()
Step 5 : To call a method in a class.
c.method1()
c.method2("Testing is fun") o Notice that when we call the method1 or
method2, we don't have to supply the self keyword. That's automatically handled for us by
the Python runtime. o Python runtime will pass "self" value when you call an instance
method on in instance, whether you provide it deliberately or not. o You just have to care
about the non-self arguments.
Step 6 : Here is the complete code
def method2(self,someString):
print("Software Testing:" +
someString) def main(): #
exercise the class methods c = myClass
()
c.method1()
c.method2(" Testing is
fun") if __name__==
"__main__": main() Output:
Nirali Prakashan Software
Testing: Testing is fun
Accessing Members:
• The object's attributes are access by using the dot operator with object. Class variable would be
accessed using class name as follows:
emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount
• The syntax used to assign a value to an attribute of an object is ,
<object> . <attribut> = <value>
• Now, putting all the concepts together:
class Employee:
'Common base class for all employees'
empCount = 0
def displayCount(self):
print("Total Employee %d" %
Employee.empCount)
def displayEmployee(self):
print("Name: ", self.name, ", Salary: ", self.salary)
• You can add, remove, or modify attributes of classes and objects at any time:
emp1.age = 7 # Add an 'age' attribute.
emp1.age = 8 # Modify 'age' attribute.
del emp1.age # Delete 'age' attribute.
• Whereas passing mutable objects can be considered as call by reference because when their values are
changed inside the function, then it will also be reflected outside the function.
test(string)
print("Outside Function:", string)
Output:
Inside Function: Pythonprogramming
Outside Function: Python
# Objects of CSStudent
class a =
CSStudent('Geek', 1) b =
CSStudent('Nerd', 2)
• Static methods are methods that are related to a class in some way, but don't need to access any class-
specific data. Static methods are defined without self arguments and don't need to instantiate an
instance, they can be called directly on the class itself.
• Static methods are great for utility functions, which perform a task in isolation. They don't need to (and
cannot) access class data. They should be completely selfcontained, and only work with data passed in
as arguments. You may use a static method to add two numbers together, or print a given string.
• Static methods and class methods are created by wrapping methods in objects of the static method
classes. Static methods are defined without self arguments, and they can be called directly on the class
itself.
3. Class Methods:
• Class methods know about their class. They can't access specific instance data, but they can call other
static methods.
• Class methods don't need self as an argument, but they do need a parameter called cls. This stands for
class, and like self, gets automatically passed in by Python.
• Class methods are created using the @classmethod decorator. Class methods can manipulate the class
itself, which is useful when you're working on larger, more complex projects.
• Here is a simple example:
class MyClass:
def smeth();
print('This is a static method')
smeth = staticmethod(smeth) def
cmeth(c1s):
print('This is a class method of', cls)
cmeth = classmethod(cmeth)
• In Python 2.4, a new syntax was introduced for wrapping methods like this, called decorators. (They
actually work with any callable objects as wrappers and can be used on both methods and functions.)
You specify one or more decorators (which are applied in reverse order) by listing them above the
method (or function), using the @ operator.
class MyClass: @staticmethod
def smeth(): print('This is a
static method')
@classmethod
def cmeth(cls):
print('This is a class method of', cls)
Once you've defined these methods, they can be used like this (that is, without instantiating the
class):
>>> MyClass.smeth()
This is a static method
>>> MyClass.cmeth()
This is a class method of <class 1__main__.MyClass',
Differentiate between deep and shallow copy:
• A deep copy copies an object into another. This means that if you make a change to a copy of an
object, it won't affect the original object. In Python, we use the function deepcopy() for this, and we
import the module copy. We use it like:
>>> import copy
Python [BBA (CA) - Sem. V] 3.9 Classes, Objects and Inheritance
>>> b=copy.deepcopy(a)
• A shallow copy, however, copies one object's reference to another. So, if we make a change in the
copy, it will affect the original object. For this, we have the function copy(). We use it like:
>>> b=copy.copy(a)
3.2 INHERITANCE
• Inheritance is a feature of Object Oriented Programming. It is used to specify that one class will get
most or all of its features from its parent class. It is a very powerful feature which facilitates users to
create a new class with a few or more modification to an existing class. The new class is called child
class or derived class and the main class from which it inherits the properties is called base class or
parent class.
• Benefits of using Inheritance:
1. Less code repetition, as the code which is common can be placed in the parent class, hence making
it available to all the child classes.
2. Structured Code: By dividing the code into classes, we can structure our software better by
dividing functionality into classes.
3. Make the code more scalable.
• Python Inheritance Syntax: class BaseClass: Body of base class class
DerivedClass(BaseClass): Body of derived class
• Derived class inherits features from the base class where new features can be added to it. This results
in re-usability of code.
Child
<statement-1>
. .
.
<statement-N>
2. class DerivedClassName(modulename.BaseClassName):
<statement-1>
.
Python [BBA (CA) - Sem. V] 3.10 Classes, Objects and Inheritance
.
.
<statement-N>
print('Barking...')
d=Dog() d.eat()
d.bark()
Output:
Eating...
Barking...
Program 3.7: Program to create base class student and derived class test using single inheritance and
display the marks of the student.
class Student:
#Common base class for all students
def getData(self,rollno,name,course):
self.rollno = rollno
self.name = name self.course
= course def
displayStudent(self):
print("Roll Number:", self.rollno)
print("Name:", self.name)
print("Course:", self.course)
#Inheritance class
Test(Student): def
getMarks(self, marks):
self.marks=marks
def displayMarks(self):
print("Total Marks:",
self.marks) r = int(input("Enter Roll
Number:")) n = input("Enter Name:") c =
input("Enter Course Name:") m =
int(input("Enter Marks:")) #creating the
object print ("Result") studl=Test()
studl.getData(r,n,c) studl.getMarks(m)
studl.displayStudent()
studl.displayMarks()
Output:
Enter Roll Number:20
Python [BBA (CA) - Sem. V] 3.11 Classes, Objects and Inheritance
Enter Name:Omkar
Enter Course Name:Python
Enter Marks:80
Result
Roll Number: 20
Name: Omkar
Course: Python
Total Marks: 80
super(Second, self).__init__()
print("second")
Third();
Output:
first
second
third
• You can use issubclass() or isinstance() functions to check a relationships of two classes and instances.
o The issubclass(sub, sup) boolean function returns true if the given subclass sub is indeed a
subclass of the superclass sup.
o The isinstance(obj, Class) boolean function returns true if obj is an instance of class Class or is an
instance of a subclass of Class.
Program 3.9: Program for Inheritance.
class Student:
#Common base class for all students
def getData(self,rollno,name,course):
self.rollno=rollno
self.name=name
self.course=course def
displayStudent(self):
print("Roll Number:",self.rollno)
print("name:", self.name)
print("Course:", self.course)
#Inheritance class Test
(Student): def
getMarks(self, marks):
self.marks=marks def
displayMars (self):
print("Total Marks:", self.marks)
class Sports:
def getSportsMarks(self, spmarks):
self.spmarks=spmarks
def displaySportsMarks(self):
print("Sports Marks:", self,spmarks)
Python [BBA (CA) - Sem. V] 3.13 Classes, Objects and Inheritance
Derived Class 1
Derived Class 2
Syntax: class
class1:
.
.
class class2(class1):
.
.
class class3(class2):
.
.
Program 3.10: Program for Python Multilevel Inheritance.
class Animal:
def eat(self):
print
'Eating...' class
Dog(Animal): def
bark(self):
print
'Barking...' class
BabyDog(Dog):
def weep(self):
print
'Weeping...'
d=BabyDog() d.eat()
d.bark()
d.weep()
Output:
Eating...
Barking...
Weeping
# Driver's code
object = Student3()
object.func1()
object.func2() Output:
This function is in school.
This function is in student 1.
B C D
Fig. 3.4: Hierarchical Inheritance
Program 3.13: Accessing the members of the class using instance of the class inside another class.
Python [BBA (CA) - Sem. V] 3.17 Classes, Objects and Inheritance
class Employee:
# constructor for initialization
def __init__(self, name, age):
self.name = name
self.age = age
# instance method
def emp_data(self):
print('Name of Employee : ', self.name)
print('Age of Employee : ', self.age)
class Data:
def __init__(self, address, salary,
emp_obj):
self.address = address
self.salary = salary
# instance method
def display(self):
• Here we have 2 classes 'Employee' and 'Data'. Inside 'Data' class Constructor we are creating
an object of Employee class due to which we can access the members of the Employee class easily.
Inside the Data class Employee class object becomes an instance variable of "Data" class.
Python [BBA (CA) - Sem. V] 3.18 Classes, Objects and Inheritance
Additional Programs
Program 3.14: Python Program to Create a Class in which One Method Accepts a String from the User and
Another method Prints it. Define a class named Country which has a method called printNationality. Define
subclass named state from Country which has a method called printState. Write a method to print state,
country and nationality.
class accept:
def getDa(self):
self.x= input("Enter a string")
def putDa(self):
print("String is:",self.x)
a=accept()
a.getDa()
a.putDa() class
country: def
getNa(self):
self.cnt= input("Enter a country")
self.na= input("Enter Nationality") def
printNationality(self):
print("Country is:",self.cnt)
print("Nationality is:",self.na)
class state(country):
def getState(self):
self.s= input("Enter a State")
def printState(self):
print("State
is:",self.s) st=state()
st.getNa() st.printNationality()
st.getState() st.printState()
Output:
Enter a string saranga
('String is:', 'saranga')
Enter a country india
Enter Nationality indian
('Country is:', 'india')
('Nationality is:', 'indian')
Enter a State maharashtra
('State is:', 'maharashtra')
Program 3.15: Write a Python class which has two methods get_String and print_String. get_String accept
a string from the user and print_String print the string in upper case. Further modify the program to reverse
a string word by word and print it in lower case.
Python [BBA (CA) - Sem. V] 3.19 Classes, Objects and Inheritance
Program 3.16: Define a class named Rectangle which can be constructed by a length and width. The
Rectangle class has a method which can compute the area and volume.
import math class Rectangle():
def __init__(self,l,b,h):
self.l=l
self.b=b
self.h=h def
area(self):
print "Area of Rectangle
is:",self.l*self.b def volume(self):
print "Volume of Rectangle
is:",self.l*self.b*self.h l=int(input("Enter length of
rectangle")) b=int(input("Enter width of rectangle"))
h=int(input("Enter height of rectangle"))
r=Rectangle(l,b,h) r.area()
r.volume()
Output:
Enter length of rectangle 12
Enter width of rectangle 34
Enter height of rectangle 56
Area of Rectangle is: 408
Volume of Rectangle is: 22848
Program 3.17: Define a class named Shape and its subclass (Square/Circle). The subclass has an init
function which takes a an argument (length/redious). Both classes have an area and volume function which
can print the area and volume of the shape where Shape's area is 0 by default.
import math
class Shape:
def __init__(self):
self.area=0
Python [BBA (CA) - Sem. V] 3.20 Classes, Objects and Inheritance
def area():
print("Inside
shape") class
Square(Shape): def
__init__(self,r):
self.r=r
def area(self):
print("Area of Square
is:",self.r*self.r) def perimeter(self):
print("Perimeter of Square
is:",2*self.r) class Circle(Shape): def
__init__(self,r):
self.r=r
def area(self):
print("Area of Circle
is:",math.pi*self.r*self.r) def perimeter(self):
print("Perimeter of Square
is:",2*math.pi*self.r) s=Square(2) s.area()
s.perimeter()
c=Circle(2)
c.area()
c.perimeter()
Output:
Area of Square is: 4
Perimeter of Square is: 4
Area of Circle is: 12.566370614359172
Perimeter of Square is: 12.566370614359172
Program 3.18: Write a Python Program to Accept, Delete and Display students details such as Roll.No,
Name, Marks in three subject, using Classes. Also display percentage of each student.
class student:
def accept(self):
self.rno=int(raw_input("Enter roll
no")) self.nm=raw_input("Enter
name") self.m=list() for
self.i in range(0,3):
self.a=int(raw_input("Enter marks"))
self.m.append(self.a) def
display(self):
print("Roll NO:",self.rno)
print("Name:",self.nm)
print("Subject marks:",self.m)
print("Percentage: ",sum(self.m)*100/300,"%")
n=int(raw_input("how many object u want:")) s=[]
Python [BBA (CA) - Sem. V] 3.21 Classes, Objects and Inheritance
for j in range(len(s)):
s[j]=student()
s[j].accept()
s[j].display() Output:
how many object u
want:3 enter
object:s1 enter
object:s2 enter
object:s3 ['s1',
's2', 's3'] Enter
roll no 12
Enter name saranga
Enter marks 78
Enter marks 89
Enter marks 87
('Roll NO:', 12)
('Name:', 'saranga')
('Subject marks:', [78, 89, 87])
('Percentage: ', 84, '%')
Enter roll no 13
Enter name ketaki
Enter marks 67
Enter marks 78
Enter marks 89
('Roll NO:', 13)
('Name:', 'ketaki')
('Subject marks:', [67, 78, 89])
('Percentage: ', 78, '%')
Enter roll no 15
Enter name abhi
Enter marks 56
Enter marks 67
Enter marks 78
('Roll NO:', 15)
('Name:', 'abhi')
('Subject marks:', [56, 67, 78])
('Percentage: ', 67, '%')
Python [BBA (CA) - Sem. V] 3.22 Classes, Objects and Inheritance
Program 3.19: Write a Python program that defines a class named circle with attributes radius and center,
where center is a point object and radius is number. Accept center and radius from user. Instantiate a circle
object that represents a circle with its center and radius as accepted input.
class Circle: def
_init_(self):
self.r=raw_input("enter radius of circle:=")
self.c=raw_input("enter Center of circle:=")
def _print_(self):
print("Radius of circle:=",self.r)
print("Center of circle:=",self.c)
c=Circle()
c._init_()
c._print_()
Output:
enter radius of circle:=3
enter Center of circle:=4
('Radius of circle:=', '3')
('Center of circle:=', '4')
Program 3.20: Python Program to Create a Class which Performs Basic Calculator Operations.
class cal(): def
__init__(self,a,b):
self.a=a
self.b=b def
add(self):
print(self.a+self.b)
def mul(self):
print(self.a*self.b)
def div(self):
print(self.a/self.b)
def sub(self):
print(self.a-self.b)
a=int(input("Enter first number:
")) b=int(input("Enter second
number: ")) obj=cal(a,b) obj.add()
obj.mul() obj.div() obj.sub() Output:
Enter first number: 23
Enter second number: 45
68
1035
0
Python [BBA (CA) - Sem. V] 3.23 Classes, Objects and Inheritance
-22
Summary
5. Which feature in OOP used to specify that one class will get most or all of its features from its parent
class.
(a) Inheritance (b) Overriding
(c) Overloading (d) Polymorphism
6. Which of the following best describes inheritance?
(a) Ability of a class to derive members of another class as a part of its own definition
(b) Means of bundling instance variables and methods in order to restrict access to certain class
members
(c) Focuses on variables and passing of variables to functions
(d) Allows for implementation of elegant software that is well designed and easily modified
7. Which of the following statements is wrong about inheritance?
(a) Protected members of a class can be inherited
(b) The inheriting class is called a subclass
(c) Private members of a class can be inherited and accessed
(d) Inheritance is one of the features of OOP
8. What will be the output of the following Python code?
class Test: def
__init__(self):
self.x = 0
class
Derived_Test(Test):
def __init__(self):
self.y = 1
def main():
b = Derived_Test()
print(b.x,b.y) main()
(a) 0 1
(b) 0 0
(c) Error because class B inherits A but variable x isn't inherited
(d) Error because when object is created, argument must be passed like Derived_Test(1)
9. What will be the output of the following Python code?
class A():
def disp(self):
print("A
disp()") class B(A):
pass obj = B()
obj.disp()
(a) Invalid syntax for inheritance
(b) Error because when object is created, argument must be passed
(c) Nothing is printed
(d) A disp()
Python [BBA (CA) - Sem. V] 3.25 Classes, Objects and Inheritance
10. Suppose B is a subclass of A, to invoke the __init__ method in A from B, what is the line of code you
should write?
(a) A.__init__(self) (b) B.__init__(self)
(c) A.__init__(B) (d) B.__init__(A)
11. Suppose B is a subclass of A, to invoke the __init__ method in A from B, what is the line of code you
should write?
(a) A.__init__(self) (b) B.__init__(self)
(c) A.__init__(B) (d) B.__init__(A) 12. What will be the output of the
following Python code?
class Test:
def __init__(self):
self.x = 0
class
Derived_Test(Test):
def __init__(self):
Test.__init__(self)
self.y = 1 def main():
b = Derived_Test()
print(b.x,b.y) main()
(a) Error because class B inherits A but variable x isn't inherited
(b) 0 0
(c) 0 1
(d) Error, the syntax of the invoking method is wrong 13. What will be the output of the
following Python code?
class A:
def __init__(self, x= 1):
self.x = x class
der(A): def
__init__(self,y = 2):
super().__init__()
self.y = y def main():
obj = der()
print(obj.x, obj.y) main()
(a) Error, the syntax of the invoking method is wrong
(b) The program runs fine but nothing is printed
(c) 1 0
(d) 1 2
14. Which of the following is not a type of inheritance?
(a) Double-level (b) Multi-level
(c) Single-level (d) Multiple
15. What does built-in function help do in context of classes?
(a) Determines the object name of any value
Python [BBA (CA) - Sem. V] 3.26 Classes, Objects and Inheritance
class B(A):
def two(self):
return 'B'
obj1=A()
obj2=B()
print(obj1.two(),obj2.two())
(a) A A (b) A B
(c) B B (d) An exception is thrown
17. What type of inheritance is illustrated in the following Python code?
class A():
pass class
B():
pass class
C(A,B):
pass
(a) Multi-level inheritance (b) Multiple inheritance
(c) Hierarchical inheritance (d) Single-level inheritance
18. _____ represents an entity in the real world with its identity and behaviour.
(a) A method (b) An object (c) A class (d) An operator
19. _____ is used to create an object.
(a) class (b) constructor
(c) User-defined functions (d) In-built functions 20. What will be the output
of the following Python code? class test:
def __init__(self,a="Hello World"):
self.a=a
def
display(self):
print(self.a)
obj=test()
obj.display()
(a) The program has an error because constructor can't have default arguments
(b) Nothing is displayed
(c) "Hello World" is displayed
Python [BBA (CA) - Sem. V] 3.27 Classes, Objects and Inheritance
(d) The program has an error display function doesn't have parameters
21. What is setattr() used for?
(a) To access the attribute of the object (b) To set an attribute
(c) To check if an attribute exists or not (d) To delete an attribute
22. What is getattr() used for?
(a) To access the attribute of the object (b) To delete an attribute
(c) To check if an attribute exists or not (d) To set an attribute
23. What will be the output of the following Python code?
class change:
def __init__(self, x, y, z):
self.a = x + y + z
x = change(1,2,3)
y = getattr(x,
'a') setattr(x,
'a', y+1)
print(x.a)
(a) 6 (b) 7
(c) Error (d) 0
Answers
1. (c) 2. (a) 3. (c) 4. (d) 5. (a) 6. (a) 7. (c) 8. (c) 9. (d) 10. (a)
11. (a) 12. (c) 13. (d) 14. (a) 15. (c) 16. (b) 17. (b) 18. (b) 19. (b) 20. (c)
21. (b) 22. (a) 23. (b)
Q.II Write True/False.
1. Python is a procedure oriented Language.
2. The process of creating this object is called instantiation 3. Class variables are
defined within the class construction.
4. Class methods needs self as an argument.
Answers
1. False 2. True 3. True 4. False
class change:
def __init__(self, x, y, z):
self.a = x + y + z
x = change(1,2,3)
y = getattr(x,
'a') setattr(x,
'a', y+1)
print(x.a) Output:
7
3. What will be the output of the following Python code?
class test: def
__init__(self):
self.variable = 'Old'
self.Change(self.variable) def
Change(self, var):
var = 'New'
obj=test()
print(obj.variable)
Output: Old
4. What will be the output of the following Python code?
class fruits:
def __init__(self,
price): self.price
= price obj=fruits(50)
obj.quantity=10 obj.bags=2
print(obj.quantity+len(obj.__dict__))
Output: 13
Practice Questions
Q.I Answer the following Questions in short:
1. Define the term: class, object.
2. What is Syntax of class?
3. How to create class and objects in python?
4. Write the definition of class method.
5. What is a class variables?
Q.II Answer the following Questions:
1. Write benefits of Inheritance.
2. Python Program to Create a Class which Performs Basic Calculator Operations.
4…
Exception Handling
Learning Objectives …
▣ To learn about Concept of Exception.
▣ To learn about Techniques to Handle Exception.
▣ To study about try – finally clause.
▣ To understand Custom Exception and assert statement.
4. PYTHON EXCEPTION
1
• Python has many built-in exceptions that are raised when your program encounters an error
(something in the program goes wrong).
• An exception is also called as runtime error that can halt the execution of the program.
• An exception is an error that happens/occurs during execution of a program. When that error occurs,
Python generate an exception that can be handled, which avoids the normal flow of the program's
instructions.
• When we executes a Python program, there may be a few uncertain conditions which occur, known as
errors. Errors also referred to as bugs that are incorrect or inaccurate action that may cause the
problems in the running of the program or may interrupt the execution of program.
• There are following three type of error occurs:
1. Compile Time Errors: Occurs at the time of compilation, include due error occur to the
violation of syntax rules like missing of a colon (:).
2. Run Time Errors: Occurs during the runtime of a program, example, include error occur due to
wrong input submitted to program by user.
3. Logical Errors: Occurs due to wrong logic written in the program.
• Errors occurs at runtime are known as exception. Errors detected during execution of program. Python
provides a feature (Exception handling) for handling any unreported errors in program.
• When exception occurs in the program, execution gets terminated. In such cases we get system
generated error message.
(4.1)
Python [BBA (CA) - Sem. V] 4.2 Exception Handling
• By handling the exceptions, we can provide a meaningful message to the user about the problem
rather than system generated error message, which may not be understandable to the user.
• Exception can be either built-in exceptions or user defined exceptions.
• The interpreter or built-in functions can generate the built-in exceptions while user defined exceptions
are custom exceptions created by the user.
• Example: For exceptions.
>>> a=3
>>> if (a<5)
SyntaxError: invalid syntax
>>> 5/0
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
5/0
ZeroDivisionError: division by zero
• Python provides two very important features to handle any unexpected error in Python programs and
to add debugging capabilities in them: o Exception Handling o Assertions
4.2 COMMON EXCEPTION
Standard Built-in Exceptions:
• Python has many built-in exceptions which forces your program to output an error when something in
it goes wrong.
• The following table shows some of Standard built-in Exceptions in Python:
Table 4.1: Build-in Exception
Exception Cause of Error
ArithmeticError Base class for all errors that occur for numeric calculation.
AssertionError Raised in case of failure of the assert statement.
AttributeError Raised in case of failure of attribute reference or assignment.
Exception Base class for all exceptions.
EOFError Raised when there is no input from either the raw_input() or input()
function and the end of file is reached.
EnvironmentError Base class for all exceptions that occur outside the Python environment.
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.
KeyboardInterrupt Raised when the user interrupts program execution, usually by pressing
Ctrl+c.
KeyError Raised when the specified key is not found in the dictionary.
LookupError Base class for all lookup errors.
NameError Raised when an identifier is not found in the local or global namespace.
SystemExit Raised when Python interpreter is quit by using the sys.exit() function. If
not handled in the code, causes the interpreter to exit.
TypeError Raised when an operation or function is attempted that is invalid for the
specified data type.
UnboundLocalError Raised when trying to access a local variable in a function or method but
no value has been assigned to it.
ValueError Raised when the built-in function for a data type has the valid type of
arguments, but the arguments have invalid values specified.
ZeroDivisionError Raised when division or modulo by zero takes place for all numeric types.
• For example, if function A calls function B which in turn calls function C and an exception occurs in
function C. If it is not handled in C, the exception passes to B and then to A. When a Python script
raises an exception, it must either handle the exception immediately otherwise it terminates and
quits.
• The exception handling is a process that provides a way to handle exceptions that occur at runtime.
The exception handling is done by writing exception handlers in the program.
• The exception handlers are blocks that execute when some exception occurs at runtime. Exception
handlers displays same message that represents information about the exception.
• For handling exception in Python, the exception handler block needs to be written which consists of
set of statements that need to be executed according to raised exception. There are three blocks that
are used in the exception handling process, namely, try, except and finally.
1. try Block: A set of statements that may cause error during runtime are to be written in the try
block.
2. except Block: It is written to display the execution details to the user when certain exception
occurs in the program. The except block executed only when a certain type exception occurs in
the execution of statements written in the try block.
3. finally Block: This is the last block written while writing, an exception handler in the program
which indicates the set of statements that are used to clean up the resources used by the
program.
Exception Handling using try-except-else:
• In Python, exceptions can be handled using a try statement. A try block consisting of one or more
statements is used by programmers to partition code that might be affected by an exception.
• A critical operation which can raise exception is placed inside the try clause and the code that handles
exception is written in except clause.
• The associated except blocks are used to handle any resulting exceptions thrown in the try block. If
any statement within the try block throws an exception, control immediately shifts to the catch block.
If no exceptions is thrown in the try block, the catch block is skipped.
• There can be one or more except blocks. Multiple except blocks with different exception names can
be chained together.
• The except blocks are evaluated from top to bottom in the code, but only one except block is executed
for each exception that is thrown.
• The first except block that specifies the exact exception name of the thrown exception is executed. If
no except block specifies a matching exception name then an except block that does not have an
exception name is selected, if one is present in the code.
• Syntax:
try:
certain operations
here .....................
. except Exception1:
If there is Exception1, then execute this block.
except Exception2:
Python [BBA (CA) - Sem. V] 4.5 Exception Handling
Enter an integer: 0
Error Occurred
Please enter valid value
Enter an integer: 5
Division is: 2.0
Program 4.5: We can use raise to throw an exception if age is less than 18 conditions occurs.
age = int(input("Enter your age for election: "))
try:
if age < 18:
raise Exception
else:
print("You are eligible for election")
except Exception: print("This value is too
small, try again") Output:
Enter your age for election: 11
This value is too small, try again
Enter your age for election: 18
You are eligible for election
• Here is an example related to RuntimeError. Here, a class is created that is subclassed from
RuntimeError. This is useful when you need to display more specific information when an exception is
caught.
• In the try block, the user-defined exception is raised and caught in the except block.
The variable e is used to create an instance of the class Networkerror.
class Networkerror(RuntimeError):
def __init__(self, arg):
self.args = arg
• So once you have defined the above class, you can raise the exception as follows − try:
raise Networkerror("Bad hostname")
except Networkerror,e:
print e.args
Program 4.6: A python program to create user-defined exception.
# class MyError is derived from super class Exception
class MyError(Exception):
# Constructor or Initializer
def __init__(self, value):
self.value = value
try:
raise(MyError(3*2))
• When we are developing a large Python program, it is a good practice to place all the user-defined
exceptions that our program raises in a separate file. Many standard modules do this. They define
their exceptions separately as exceptions.py or errors.py (generally but not always).
• User-defined exception class can implement everything a normal class can do, but we generally make
them simple and concise. Most implementations declare a custom base class and derive others
exception classes from this base class.
Python [BBA (CA) - Sem. V] 4.10 Exception Handling
assert len(marks) != 0
return
sum(marks)/len(marks) mark1
= []
print("Average of mark1:",avg(mark1))
Output:
AssertionError
mark1 = []
print("Average of mark1:",avg(mark1))
Output:
Average of mark2: 78.0
AssertionError: List is empty.
Program 4.9: A function that converts a given temperature from degrees Kelvin to degrees Fahrenheit.
Since 0° K is as cold as it gets, the function bails out if it sees a negative temperature def
KelvinToFahrenheit(Temperature): assert (Temperature >= 0),"Colder
than absolute zero!" return ((Temperature-273)*1.8)+32
print (KelvinToFahrenheit(273))
print
(int(KelvinToFahrenheit(505.78)))
print (KelvinToFahrenheit(-5)) Output:
32.0
451
Traceback (most recent call last):
File "test.py", line 9, in <module>
print KelvinToFahrenheit(-5)
File "test.py", line 4, in KelvinToFahrenheit
assert (Temperature >= 0),"Colder than absolute
zero!"
AssertionError: Colder than absolute zero!
Python [BBA (CA) - Sem. V] 4.12 Exception Handling
Additional Programs
Program 4.10: Write a program to calculate average of list elements passed by user, element should not
be null in list, if its null raise error, using assertion.
def listing(l):
a=len(l)
assert(a!=0),"List is empty" print("Average of
list element=",sum(l)/a) l=[] n=int(input("enter
how many elements you want in list")) for i in
range(n):
num=int(input("enter element in list"))
assert(num!=0),"element should not be zero"
l.append(num)
print("Entered List is=",l)
listing(l)
Output:
bash-4.1$ python calcavg.py enter how
many elements you want in list4 enter
element in list0
Traceback (most recent call last): File
"calcavg.py", line 11, in <module>
assert(num!=0),"element should not be
zero" AssertionError: element should not
be zero
Program 4.11: Write a python program which define class to find validity of string parentheses,
'(',')','{','}','[',']'. brackets must closed in correct order, if they are valid print valid else raise exception
Invalid.
class Error1(Exception): def
__init__(self,str1): self.str1=str1 def
print_data(self): print(self.str1) class
Python [BBA (CA) - Sem. V] 4.13 Exception Handling
Program 4.12: Write a program to convert temperature, fahrenit to kelvin and kelvin to fahrenit using
assertion.
def temptokf(temp):
ans=temp*9/5+32
print(ans,"F")
ans1=temp*9/5-32
print(ans1,"K")
temp=int(input("enter tempreature:="))
assert(temp>0),"tempreature should not be negative value or
zero" temptokf(temp) Output:
bash-4.1$ python
temp.py enter
tempreature:=12 53.6 F
-10.399999999999999 K
Python [BBA (CA) - Sem. V] 4.14 Exception Handling
Program 4.13: Write a text file test.txt that contains int, char, float, numbers. Write a python program to
read that test.txt file and print appropriate message using exception handling that line contains char, int or
float.
fname=input("enter the filename that you want to
open:=") assert(fname!=""),"file name should not be
null" with open (fname,"r") as f: for line in
f.readlines():
words=line.split()
for letters in words:
if(letters.isdigit())
: print("Digit
Found") else:
print("Character found")
Output:
bash-4.1$ python files.py
enter the filename that you want to open:=TYBCA.txt
Character found
Digit Found
=>TYBCA.txt file(contents)
tybca 12345
Summary
An exception is an error that happens during the execution of a program.
Error handling is generally resolved by saving the state of execution at the moment the error
occurred and interrupting the normal flow of the program to execute a special function or piece
of code, which is known as the exception handler.
Assertions are simply boolean expressions that checks if the conditions return true or not. If it is
true, the program does nothing and move to the next line of code. However, if it's false, the
program stops and throws an error.
try Block: A set of statements that may cause error during runtime are to be written in the try
block.
except Block: It is written to display the execution details to the user when certain exception occurs
in the program. The except block executed only when a certain type exception occurs in the
execution of statements written in the try block.
finally Block: This is the last block written while writing, an exception handler in the program which
indicates the set of statements that are used to clean up the resources used by the program.
Python throws errors and exceptions, when there is a code gone wrong, which may cause program
to stop abruptly. Python also provides exception handling method with the help of try-except.
Most frequently used standard exceptions are: IndexError, ImportError, IOError, ZeroDivisionError,
TypeError and FileNotFoundError.
A user can create his own error using exception class called a user-defined exception.
Practice Questions
Q.I Answer the following Questions in short:
1. What is Exception in Python?
2. What is assertion?
3. What is the use of try-finally clause.
4. Write syntax of Raise statement and explain it.
5. List out standard built in exceptions. Q.II Answer the following Questions:
1. Which are built-in exceptions in Python?
2. How to handle exception in Python?
3. Explain Except clause with no exceptions.
4. Explain user defined exceptions.
5. Which are standard expectations? Q.III Define the terms:
1. Try
2. Except
3. Else
4. Assertion
5. Exception handling
6. Error
5…
GUI Programming
Learning Objectives …
▣ To study Tkinter programming.
▣ To learn about Tkinter widgets.
▣ To understand about Frame.
▣ To Study about Button, Label, Entry
2. wxPython: o This is an open-source Python interface for wxWindows. wxPython comes with a
richer set of widgets out of the box thantkinter, including trees and HTML viewers. wxPython is
Open Source. o wxPython is a cross-platform toolkit. This means that the same program will run
on multiple platforms without modification. Currently, the Supported platforms are Microsoft
Windows, Mac OS X and macOS, and Linux.
3. PyGUI: o PyGUI is a graphical application cross-platform framework for UNIX, Macintosh and
Windows. Compared to some other GUI frameworks, PyGUI is by far the simplest and lightweight
of them all, as the API is purely in synchronous with Python. o PyGUI inserts very less code
between the GUI platform and Python application, hence the display of the application usually
displays the natural GUI of the platform.
4. PyQt: o PyQt is a full featured GUI library and runs portably today on Windows, Mac OS X, and
UNIX. It is a Python interface for Qt, one of the most powerful, and popular cross-platform GUI
library. PyQt is a blend of Python programming language and the Qt library.
o Creating a simple GUI application using PyQt involves the following steps:
1. Import QtGui module.
2. Create an application object.
3. A QWidget object creates top level window. Add QLabel object in it.
4. Set the caption of label as "hello world".
5. Define the size and position of window by setGeometry() method.
6. Enter the mainloop of application by app.exec_() method.
import sys from PyQt4
import QtGui def
window():
app
=QtGui.QApplication(sys.argv)
w =QtGui.QWidget() b
=QtGui.QLabel(w)
b.setText("Hello World!")
w.setGeometry(100,100,200,50)
b.move(50,20)
w.setWindowTitle("PyQt")
w.show()
sys.exit(app.exec_())
if __name__
=='__main__':
window()
o The above code produces the following output:
Python [BBA (CA) - Sem. V] 5.3 GUI Programming
Fig. 5.1
5. PyGTK: o A Python interface to GTK, a portable GUI library originally used as the core of the
Gnome window system on Linux. PyGTK is part of the GNOME project. It offers comprehensive
tools for building desktop applications in Python. o GTK+, or the GIMP Toolkit, is a multi-
platform toolkit for creating graphical user interfaces. GTK+ has been designed from the ground up
to support a wide range of languages. PyGTK is a Python wrapper for GTK+. o The underlying
GTK+ library provides all kinds of visual elements and utilities for it to develop full-featured
applications for the GNOME Desktop. PyGTK is a cross-platform library.
6. Kivy: o Another GUI framework is Kivy. Kivy is an Open source Python library for the rapid
development of applications that make use of innovative user interfaces, such as multi-touch
applications. o Kivy runs on Linux, Windows, OS X, Android, IOS, and Raspberry Pi. You can run
the same code on all supported platforms. It can natively use most inputs, protocols and devices
including WM_Touch, WM_Pen, Mac OS X Trackpad and Magic Mouse, Mtdev, Linux Kernel
HID. Kivy is 100% free to use, under an MIT license.
7. PySide: o PySide is a Python binding for the QT side. It is a Python extension or API for QT
which is probably industry standards for user interface development for cross-platform. So you can
actually run your graphical user interface using PySide in Windows, Mac, and Linux without
changing your source code much.
That is a great advantage.
• Note: Tkinter, Kivy, and wxPython are the free GUI libraries for Python.
5.1.1 Comparison of GUI
Table 5.1: Tkinter vs Kivy
Tkinter Kivy
Tkinter is rock solid with some crossplatform The aim is to permit fast and simple interaction
characteristics. design.
It’s extra flexible and consistent. These include the multi-touch functionalities that are
essential for mobile apps.
It is mature stable and widely ported. Along with rapid prototyping, reusable code, and
deployable functionalities.
Tkinter is a simple API and it is easy to learn. Kivy is greatly suited for touch interfaces and games.
Python [BBA (CA) - Sem. V] 5.4 GUI Programming
Tkinter use native widgets on the mac and windows. Kivy looks attractive sweet in terms of porting to all
major platforms and supporting touch screens.
Tkinter has a very simple syntax. Kivy is designed in python based on OpenGL.
PySide utilizes various library names than PyQt. It can be used on all platforms that support QT,
such as Windows, OS X, Linux, IOS, and android.
contd. …
Kivy works smoothly on Linux, Windows, OS X It is mostly linked with PyQt5 to Qt 5, while
Android, and Raspberry Pi. PyQt4 is supported by Qt v4, and developed in
close relation with Qt v5.
Kivy language is excellent for offering the syntax PyQt relies on bindings, which are set in place
of the Kivy program. through a set of Python modules of extra than
1,000 classes.
Kivy included classes, inherited classes, and Most companies that develop apps rely extra on
widget configuration for better represent PyQt, as this offers a wide array of functionalities
functionalities. and tools for adaptability.
You will need to mix py and kv languages for Yet due to the vast knowledge and steep learning
access complex applications with the aid of curve requirement, most of the programs turn their
specific algorithms. attention for userfriendly Kivy Programming.
Python [BBA (CA) - Sem. V] 5.5 GUI Programming
Kivy is a python library meant to be used for Along with PyQt, these two are labeled as full-
establishing multitouch-enabled media-rich apps. stack frameworks and cross-platform mobile
development software.
Table 5.4: WxPython vs Tkinter
WxPython Tkinter
The WxPython version has 76 lines. The Tkinter version has 48 lines.
The WxPython pattern utilizes nested HBOX and The Tkinter pattern utilizes a grid layout.
VBOX sizers.
The WxPython externalizes the layout classes in its Tkinter internalizes layout.
sizer hierarchy.
WxPython takes 6 seconds of load time. Tkinter takes 1 second of load time.
WxPython is use in commercial products as well as Tkinter you will have to develop your GUI through
in freeware or shareware. typing code.
This is a free and open source. Tkinter is easy to learn.
5. Tkinter PROGRAMMING
2
• Tkinter is the standard GUI library for Python. Python combined with Tkinter provides a fast and easy
way to create GUI applications. Tkinter provides a powerful object-oriented interface to the Tk GUI
toolkit.
• Creating a GUI application using Tkinter is an easy task. All you need to do is perform the following
steps:
1. Import the Tkinter module. import tkinter or
from tkinter import*
2. Create the GUI application main window.
3. Add one or more of widgets to the GUI application.
4. Enter the main event loop (mainloop()) to take action against each event triggered by the user.
• Let's build a very simple GUI with the help of Tkinter and understand it with the help of a flow
diagram.
Optional
Initialize the
ImportTkinter Rename the Define the
Window
Module GUI Window Label Widget
Manager
Geometry
Mainloop Management
Method Using Pack
1. First, you import the key component, i.e., the Tkinter module.
2. Next, you initialize the window manager with the tkinter.Tk() method and assign it to a
variable. This method creates a blank window with close, maximize, and minimize buttons on the
top as a usual GUI should have.
3. Then as an optional step, you will rename the title of the window as you like with
window.title(title_of_the_window).
4. Next, you make use of a widget called Label, which is used to insert some text into the window.
5. Then, you make use of Tkinter's geometry management attribute called pack() to display the
widget in size it requires.
6. Finally, as the last step, you use the mainloop() method to display the window until you
manually close it. It runs an infinite loop in the backend.
• The mainloop() method called last puts the label on the screen and enters a Tkinter wait state, which
watches for user-generated GUI events. Within the mainloop() function, Tkinter internally monitors
things such as the keyboard and mouse to detect user generated events.
• Python/Tkinter programs are entirely event driven: they build displays and register handlers for events,
and then do nothing but wait for events to occur. During the wait, the Tk GUI library runs an event loop
that watches for mouse clicks, keyboard presses, and so on. All application program processing happens
in the registered callback handlers in response to events.
Advantages:
1. If you’re using a recent version of Python, Tkinter is most likely already installed.
2. Tkinter offers a vast collection of well known widgets, including all the most common ones like
buttons, labels, checkboxes etc.
3. Adding code to each widget is straightforward.
Entry The Entry widget is used to display a single-line text field for accepting values from a
user.
Frame The Frame widget is used as a container widget to organize other widgets.
Label The Label widget is used to provide a single-line caption for other widgets. It can also
contain images.
Message The Message widget is used to display multiline text fields for accepting values from a
user.
Radiobutton The Radiobutton widget is used to display a number of options as radio buttons. The
user can select only one option at a time.
PanedWindow A PanedWindow is a container widget that may contain any number of panes, arranged
horizontally or vertically.
LabelFrame A labelframe is a simple container widget. Its primary purpose is to act as a spacer or
container for complex window layouts.
Widget Resizing:
• Widget resizing is done by using pack method by two options: expand and fill.
• When widgets are packed, we can specify whether a widget should expand to take up all available space
by using expand=YES option.
• Asks the packer to expand the allocated space for the widget in general into any unclaimed space in the
widget’s parent by using fill option.
• Fill option can be used to stretch the widget to occupy all of its allocated space.
Program 5.5: Program for GUI with expansion and window title.
from tkinter import * root = Tk() widget
= Label(root) widget.config(text='Hello
GUI world!') widget.pack(side=TOP,
expand=YES, fill=BOTH)
root.title('gui1g.py') root.mainloop()
Python [BBA (CA) - Sem. V] 5.10 GUI Programming
Output
:
highlightcolor Color shown in the focus highlight when the frame has the focus.
relief With the default value, relief=FLAT, the checkbutton does not stand out
from its background. You may set this option to any of the other styles
self.quit=tk.Button(self,text="QUIT",fg="red",
command=self.master.destroy)
self.quit.pack(side="bottom")
defsay_hi(self):
print("hi there,
everyone!")
root=tk.Tk()
app=Application(master=root)
Python [BBA (CA) - Sem. V] 5.12 GUI Programming
app.mainloop()
Output in Pycharm IDLE:
• When we click on button, the msg hi there, everyone! will be display on the console.also when we click
on Quit, the window disappears.
5. BUTTON
5
• Button widget has a property for switching on/off. When a user clicks the button, an event is triggered
in the Tkinter.
command The command option is used to set the function call which is scheduled at
the time when the function is called.
activeforeground This option mainly represents the font color of the button when the mouse
hovers the button.
fg This option represents the foreground color of the button.
font This option indicates the font of the button.
Python [BBA (CA) - Sem. V] 5.13 GUI Programming
height This option indicates the height of the button. This height indicates the
number of text lines in the case of text lines and it indicates the number of
pixels in the case of images.
image This option indicates the image displayed on the button.
higlightcolor This option indicates the highlight color when there is a focus on the button
justify This option is used to indicate the way by which the multiple text lines are
represented. For left justification, it is set to LEFT and it is set to RIGHT
for the right justification, and CENTER for the center justification.
padx This option indicates the additional padding of the button in the horizontal
direction.
pady This option indicates the additional padding of the button in the vertical
direction.
underline This option is used to underline the text of the button.
width This option specifies the width of the button. For textual buttons, It exists
as a number of letters or for image buttons it indicates the pixels.
Wraplength In the case, if this option's value is set to a positive number, the text lines
will be wrapped in order to fit within this length.
state This option's value set to DISABLED to make the button unresponsive.
The ACTIVE mainly represents the active state of the button.
Program 5.7: The following code line creates a Button with a yellow background and blue text. It also sets
the width and height to 25 and 5 text units, respectively.
button=tk.Button
{
text="Click me!",
width=25,
height=5,
bg="yellow",
fg="blue",
}
top.mainloop()
Output:
# You will first create a division with the help of Frame class.
# And align them on TOP and BOTTOM with pack() method.
top_frame = tkinter.Frame(window).pack()
bottom_frame = tkinter.Frame(window).pack(side = "bottom")
"orange").pack(side = "left")
window.mainloop()
Output:
• Here, on one click the msg displayed is "Press twice to exit" and on two clicks, the window is
disappeared with msg "Hello, I must be going…".
Program 5.12: Tkinter Button Widget - Add style and Event handler.
Import sys
import tkinter from tkinter
import * from tkinter import
messagebox
Python [BBA (CA) - Sem. V] 5.16 GUI Programming
top = Tk()
top.geometry("300x150")
def click():
messagebox.showinfo("Hello", "Green Button clicked") a =
Button(top, text="yellow", activeforeground="yellow",
activebackground="orange", pady=10)
b = Button(top, text="Blue", activeforeground="blue",
activebackground="orange", pady=10)
# adding click function to the below button
c = Button(top, text="Green", command=click, activeforeground = "green",
activebackground="orange", pady=10)
d = Button(top, text="red", activeforeground="yellow",
activebackground="orange", pady=10)
a.pack(side = LEFT)
b.pack(side = RIGHT)
c.pack(side = TOP)
d.pack(side = BOTTOM)
top.mainloop() Output:
5.6 LABEL
• Label is used to create a single line widgets like text, images, etc.
• Label widgets display text with the default system text color and the default system text background
color. These are typically black and white, respectively, but you may see different colors if you have
changed these settings in your operating system.
• You can control Label text and background colors using the foreground and background parameters.
Syntax: label_widget = tk.Label(widget, option=placeholder)
• Where, widget is the parameter for the parent window/frame while option is a placeholder that
can have various values like the font of a button, background color, image, width, and height, etc.
Example:
1. label=tk.Label(text="Hello, Tkinter")
Python [BBA (CA) - Sem. V] 5.17 GUI Programming
bg The normal background color displayed behind the label and indicator.
bitmap Set this option equal to a bitmap or image object and the label will display that
graphic.
cursor If you set this option to a cursor name (arrow, dot etc.), the mouse cursor will change
to that pattern when it is over the checkbutton.
font If you are displaying text in this label (with the text or textvariable option, the font
option specifies in what font that text will be displayed.
fg If you are displaying text or a bitmap in this label, this option specifies the color of
the text. If you are displaying a bitmap, this is the color that will appear at the
position of the 1-bits in the bitmap.
justify Specifies how multiple lines of text will be aligned with respect to each other: LEFT
for flush left, CENTER for centered (the default), or RIGHT for right-justified.
padx Extra space added to the left and right of the text within the widget. Default is 1.
pady Extra space added above and below the text within the widget. Default is 1.
relief Specifies the appearance of a decorative border around the label. The default is
FLAT; for other values.
Python [BBA (CA) - Sem. V] 5.18 GUI Programming
text To display one or more lines of text in a label widget, set this option to a string
containing the text. Internal newlines ("\n") will force a line break.
textvariable To slave the text displayed in a label widget to a control variable of class StringVar,
set this option to that variable.
underline You can display an underline (_) below the nth letter of the text, counting from 0, by
setting this option to n. The default is underline=1, which means no underlining.
width Width of the label in characters (not pixels!). If this option is not set, the label will be
sized to fit its contents.
wraplength You can limit the number of characters in each line by setting this option to the
desired number. The default value, 0, means that lines will be broken only at
newlines.
Program 5.14: Create a GUI which can capture the events that have been fired from the mouse. The mouse
has right click, left click and middle click. So whenever the user will click the mouse button it will capture
the event and write it on the GUI main window.
import tkinter
# Let's create the Tkinter window
window = tkinter.Tk()
Python [BBA (CA) - Sem. V] 5.19 GUI Programming
window.title("Mouse clicking
events")
#You will create three different functions for three different
events def left_click(event): tkinter.Label(window, text =
"Left Click!").pack()
def middle_click(event):
tkinter.Label(window, text = "Middle Click!").pack()
Python [BBA (CA) - Sem. V] 5.20 GUI Programming
def right_click(event):
tkinter.Label(window, text = "Right
Click!").pack() window.bind("<Button-1>",
left_click) window.bind("<Button-2>", middle_click)
window.bind("<Button-3>", right_click)
window.mainloop()
Output:
When we pressed on Button 1, the msg "Left Clicked" is displayed.
Output:
5.7 ENTRY
• The Entry widget is a simple, single-line text input field. It is typically used for input fields in form-like
dialogs and anywhere else you need the user to type a value into a field of a larger display. Entry also
supports advanced concepts such as scrolling, key bindings for editing, and text selections.
• Syntax:
entry_widget = tk.Entry(widget, option=placeholder)
Where, widget is the parameter for the parent window/frame while option is a placeholder that can have
various values like border-width, background color, width & height etc.
• When you need to get a little bit of text from a user, like a name or an email address, use an Entry
widget. They display a small text box that the user can type some text into it. Creating and styling an
Entry widget works like Label and Button widgets.
• For example, the following line creates a widget with a blue background, some yellow text, and a width
of 50 text units:
entry=tk.Entry(fg="yellow",bg="blue",width=50)
• Entry widgets is not for how to style, but, it is for how to use them to get input from a user. There are
three main operations that you can perform with Entry widgets:
1. Retrieving text with .get()
2. Deleting text with .delete()
3. Inserting text with .insert()
• The following example shows how to create Entry widgets and interact with it. First, import tkinter and
create a new window on python shell.
>>>import tkinter *
>>>window=tk.Tk()
• Now create a Label and an Entry widget:
>>>label=tk.Label(text="Name")
>>>entry=tk.Entry()
• The Label describes what sort of text should go in the Entry widget. It doesn’t enforce any sort of
requirements on the Entry, but it tells the user what your program expects them to put there. You need to
.pack() the widgets into the window so that they’re visible:
Python [BBA (CA) - Sem. V] 5.22 GUI Programming
>>>label.pack()
>>>entry.pack()
Python [BBA (CA) - Sem. V] 5.23 GUI Programming
•
Here’s what that looks like:
• Notice that Tkinter automatically centers the Label above the Entry widget in the window. Click inside
the Entry widget with your mouse and type "Real Python":
• Now you’ve got some text entered into the Entry widget, but that text hasn’t been sent to your program
yet. You can use .get() to retrieve the text and assign it to a variable called name:
>>>name=entry.get()
>>>name
'Real Python'
• You can .delete() text as well. This method takes an integer argument that tells Python which
character to remove. For example, the code block below shows how .delete(0) deletes the first
character from the Entry:
>>>entry.delete(0)
• The text remaining in the widget is now "eal Python":
• Note that, just like Python string objects, text in an Entry widget is indexed starting with 0.
• If you need to remove several characters from an Entry, then pass a second integer argument to
.delete() indicating the index of the character where deletion should stop. For example, the
following code deletes the first four letters in the Entry:
>>>entry.delete(0,4)
The remaining text now reads "Python":
Python [BBA (CA) - Sem. V] 5.24 GUI Programming
• entry.delete() works just like string slicing. The first argument determines the starting index,
and the deletion continues up to but not including the index passed as the second argument. Use the
special constant tk.END for the second argument of .delete() to remove all text in an Entry:
>>>entry.delete(0,tk.END)
• You’ll now see a blank text box:
• On the opposite end of the spectrum, you can also .insert() text into an Entry widget:
>>>entry.insert(0,"Python")
• The window now looks like this:
• The first argument tells .insert() where to insert the text. If there is no text in the Entry, then the
new text will always be inserted at the beginning of the widget, no matter what value you pass as the
first argument. For example, calling .insert() with 100 as the first argument instead of 0, as you
did above, would have generated the same output.
• If an Entry already contains some text, then .insert() will insert the new text at the specified position
and shift all existing text to the right:
>>>entry.insert(0,"Real ")
The widget text now reads "Real Python":
Python [BBA (CA) - Sem. V] 5.25 GUI Programming
• Entry widgets are great for capturing small amounts of text from a user, but because they’re only
displayed on a single line, they’re not ideal for gathering large amounts of text.
Program 5.19
from tkinter import * root = Tk() labelfont = ('times', 20,
'bold') # family, size, style widget = Label(root,
text='Hello config world') widget.config(bg='black',
fg='yellow') # yellow text on black label
widget.config(font=labelfont) # use a larger font
widget.config(height=3, width=20) # initial size: lines,chars
widget.pack(expand=YES, fill=BOTH)
root.mainloop()
Output:
Python [BBA (CA) - Sem. V] 5.27 GUI Programming
Additional Programs
1. Multiple windows
• The two Toplevel windows on the right are full-fledged windows; they can be independently iconified,
maximized, and so on. Toplevels are typically used to implement multiple-window displays and pop-up
modal and nonmodal dialogs.
# You will define the size of the window in width and height, using
the geometry method window.geometry("312x324")
# Prevent the window from getting resized you will call 'resizable'
method on the window.
window.resizable(0, 0)
expression = ""
# In order to get the instance of the input field 'StringVar()' is
used input_text = StringVar()
# Once all the functions are defined then comes the main section
where you will start defining the structure of the calculator inside
the GUI.
# Then you will create an input field inside the 'Frame' that was
created in the previous step. Here the digits or the output will be
displayed as 'right' aligned
input_field = Entry(input_frame, font = ('arial', 18, 'bold'),
textvariable = input_text, width = 50, bg = "#eee", bd = 0, justify
= RIGHT) input_field.grid(row = 0, column = 0)
input_field.pack(ipady = 10) # 'ipady' is an internal padding to
increase the height of input field
# Once you have the input field defined then you need a separate
frame which will incorporate all the buttons inside it below the
'input field' btns_frame = Frame(window, width = 312, height =
272.5, bg = "grey") btns_frame.pack()
# The first row will comprise of the buttons 'Clear (C)' and 'Divide
(/)' clear = Button(btns_frame, text = "C", fg = "black", width =
32, height = 3, bd = 0, bg = "#eee", cursor = "hand2", command =
lambda: btn_clear()).grid(row = 0, column = 0, columnspan = 3, padx
= 1, pady = 1) divide = Button(btns_frame, text = "/", fg = "black",
width = 10, height = 3, bd = 0, bg = "#eee", cursor = "hand2",
command = lambda:
btn_click("/")).grid(row = 0, column = 3, padx = 1, pady = 1)
# The second row will comprise of the buttons '7', '8', '9' and
'Multiply (*)' seven = Button(btns_frame, text = "7", fg = "black",
width = 10, height = 3, bd = 0, bg = "#fff", cursor = "hand2",
command = lambda: btn_click(7)).grid(row = 1, column = 0, padx = 1,
pady = 1) eight = Button(btns_frame, text = "8", fg = "black", width
= 10, height = 3, bd = 0, bg = "#fff", cursor = "hand2", command =
lambda: btn_click(8)).grid(row = 1, column = 1, padx = 1, pady = 1)
nine = Button(btns_frame, text = "9", fg = "black", width = 10,
height = 3, bd = 0, bg = "#fff", cursor = "hand2", command = lambda:
btn_click(9)).grid(row = 1, column = 2, padx = 1, pady = 1) multiply
= Button(btns_frame, text = "*", fg = "black", width = 10, height =
3, bd = 0, bg = "#eee", cursor = "hand2", command = lambda:
btn_click("*")).grid(row = 1, column = 3, padx = 1, pady = 1)
# The third row will comprise of the buttons '4', '5', '6' and
'Subtract
(-)' four = Button(btns_frame, text = "4", fg = "black", width = 10,
height = 3, bd = 0, bg = "#fff", cursor = "hand2", command = lambda:
btn_click(4)).grid(row = 2, column = 0, padx = 1, pady = 1) five =
Button(btns_frame, text = "5", fg = "black", width = 10, height = 3,
bd = 0, bg = "#fff", cursor = "hand2", command = lambda:
btn_click(5)).grid(row
= 2, column = 1, padx = 1, pady = 1) six = Button(btns_frame, text =
"6", fg = "black", width = 10, height = 3, bd = 0, bg = "#fff",
Python [BBA (CA) - Sem. V] 5.30 GUI Programming
# The fourth row will comprise of the buttons '1', '2', '3' and
'Addition (+)' one = Button(btns_frame, text = "1", fg = "black",
width = 10, height = 3, bd = 0, bg = "#fff", cursor = "hand2",
command = lambda: btn_click(1)).grid(row = 3, column = 0, padx = 1,
pady = 1) two = Button(btns_frame, text = "2", fg = "black", width =
10, height = 3, bd = 0, bg = "#fff", cursor = "hand2", command =
lambda: btn_click(2)).grid(row = 3, column = 1, padx = 1, pady = 1)
three = Button(btns_frame, text = "3", fg = "black", width = 10,
height = 3, bd = 0, bg = "#fff", cursor = "hand2", command = lambda:
btn_click(3)).grid(row = 3, column = 2, padx = 1, pady = 1) plus =
Button(btns_frame, text = "+", fg = "black", width = 10, height = 3,
bd = 0, bg = "#eee", cursor = "hand2", command = lambda:
btn_click("+")).grid(row = 3, column = 3, padx = 1, pady = 1)
# Finally, the fifth row will comprise of the buttons '0', 'Decimal
(.)', and 'Equal To (=)' zero = Button(btns_frame, text = "0", fg =
"black", width = 21, height = 3, bd = 0, bg = "#fff", cursor =
"hand2", command = lambda: btn_click(0)).grid(row = 4, column = 0,
columnspan = 2, padx = 1, pady = 1) point = Button(btns_frame, text
= ".", fg = "black", width = 10, height = 3, bd = 0, bg = "#eee",
cursor = "hand2", command = lambda: btn_click(".")).grid(row = 4,
column = 2, padx = 1, pady = 1) equals = Button(btns_frame, text =
"=", fg = "black", width = 10, height = 3, bd = 0, bg = "#eee",
cursor = "hand2", command = lambda:
btn_equal()).grid(row = 4, column = 3, padx = 1, pady = 1)
window.mainloop()
Python [BBA (CA) - Sem. V] 5.31 GUI Programming
Output:
3. Bind method
4. grid()
5. pack()
6…
Python Libraries
Learning Objectives …
▣ To understand Statistical Analysis- NumPy, SciPy, Pandas, StatsModels.
▣ To learn Data Visualization- Matplotlib, Seaborn, Plotly.
▣ To know about Data Modelling and Machine Learning- Scikit-learn, XGBoost, Eli5.
▣ To study Deep Learning- TensorFlow, Pytorch, Keras.
▣ To understand Natural Language Processing (NLP)- NLTK, SpaCy, Gensim.
6.1.1 NumPy
• It is a Python library for scientific computing in Python.
• It contains a collection of tools and techniques that can be used to solve on a computer mathematical
models of problems in Science and Engineering.
• One of these tools is a high-performance multidimensional array object that is a powerful data structure
for efficient computation of arrays and matrices. To work with these arrays, there’s a huge amount of
high-level mathematical functions operate on these matrices and arrays.
• NumPy is a general-purpose array-processing package.
• NumPy is the core library for scientific computing in Python.
• In 2005, Travis Oliphant created NumPy package by incorporating the features of Numarray into
Numeric package.
(6.1)
• It is an extension module for Python, mostly written in C which makes sure that the precompiled
mathematical and numerical functions and functionalities of NumPy guarantee great execution speed.
Python [BBA (CA) - Sem. V] 6.2 Python Libraries
• Though python has a list, we need NumPy, because we cannot perform operations on all the elements
of two lists directly. For example, we cannot multiply two lists directly we will have to do it element
wise. This is where the role of NumPy comes into play.
Example: Python program to demonstrate a need of NumPy.
list1 = [1, 2, 3, 4 ,5, 6]
list2 = [10, 9, 8, 7, 6, 5]
# Multiplying both lists directly would give an
error. print(list1*list2) Output:
TypeError: can't multiply sequence by non-int of type 'list'
Where as this can easily be done with NumPy arrays.
Example: Python program to demonstrate the use of NumPy arrays.
import NumPy as np list1 = [1,
2, 3, 4, 5, 6] list2 = [12, 9,
4, 7, 6, 5] # Convert list1
into a NumPy array a1 =
np.array(list1)
# Convert list2 into a NumPy
array a2 = np.array(list2)
print(a1*a2) Output: array([12, 18,
12, 28, 30, 30]) Features of NumPy:
1. A powerful N-dimensional array object, multi-dimensional arrays and matrices.
2. A large library of high-level mathematical functions to operate on these matrices and arrays.
3. Sophisticated (broadcasting) functions; new multi-iterator object created for easy handling in C of
broadcasting.
4. Tools for integrating C/C++ and Fortran code.
5. Useful linear algebra, Fourier transform, and random number capabilities.
6. Used as an efficient multi-dimensional container of generic data.
7. Arbitrary data-types can be defined using NumPy which allows NumPy to seamlessly and
speedily integrate with a wide variety of databases.
8. Arrays can be more easily read from text files and created from buffers and iterators.
9. Arrays can be quickly written to files in text and/or binary mode.
10. Fancy indexing can be done on arrays using integer sequences and Boolean masks.
11. NumPy is often used along with packages like SciPy (Scientific Python) and Matplotlib (plotting
library). This combination is widely used as a replacement for MatLab, a popular platform for
technical computing.
Advantages of using NumPy with Python:
1. It is open source and free.
2. It supports array oriented computing.
3. It is efficiently implemented for multi-dimensional arrays and designed for scientific computation.
Python [BBA (CA) - Sem. V] 6.3 Python Libraries
4. It is an extension on Python, embedding code from other languages like C, C++ and FORTRAN is
very simple.
5. NumPy is extremely fast as compared to core Python.
6. Many advanced Python libraries, such as Scikit-Learn, Scipy, and Keras, make extensive use of
the NumPy library. Therefore, to pursue a career in data science or machine learning, NumPy is a
very good tool to master.
7. NumPy comes with a variety of built-in functionalities, which in core Python would take a fair bit
of custom code.
Table 6.1: Difference between Python lists and NumPy array
Factors Python lists NumPy arrays
Library The Python core library provided NumPy is the core library for scientific
Lists. computing in Python.
Definition A list is the Python equivalent of an A NumPy array is a grid of values, all of
array, but is resizeable and can contain the same type, and is indexed by a tuple
elements of different types. of nonnegative integers.
Memory Pythons list requires more memory. NumPy arrays requires smaller memory
consumption and have better runtime
behavior.
Speed Python list operation takes more time and NumPy is faster and more convenient
less convenient. than a list.
Slicing Slices of python lists are shallow copies. All arrays generated by NumPy basic
slicing are always views of the original
array.
Python [BBA (CA) - Sem. V] 6.4 Python Libraries
6.1.2 SciPy
• SciPy, pronounced as Sigh Pi, is a scientific python open source, distributed under the
Berkeley Software Distribution (BSD) licensed library to perform Mathematical, Scientific and
Engineering Computations.
• It adds substantial capabilities to NumPy. The SciPy package contains various toolboxes dedicated to
common issues in scientific computing.
• Its different submodules correspond to different applications, such as interpolation, integration,
optimization, image processing, statistics, special functions, etc.
• SciPy is open-source software for mathematics, science, and engineering. SciPy is a collection of
mathematical algorithms and convenience functions built on the NumPy extension of Python. It adds
significant power to the interactive Python session by providing the user with high-level commands
and classes for manipulating and visualizing data.
• With SciPy an interactive Python session becomes a data-processing and systemprototyping
environment rivaling systems such as MATLAB, IDL, Octave, R-Lab, and SciLab. It includes modules
for statistics, optimization, integration, linear algebra, Fourier transforms, signal and image processing
and more.
• The main reason for building the SciPy library is that, it should work with NumPy arrays. It provides
many user-friendly and efficient numerical practices such as routines for numerical integration and
optimization. Together, they run on all popular operating systems, are quick to install, and are free of
charge. NumPy and SciPy are easy to use, but powerful enough to be depended upon by some of the
world's leading scientists and engineers.
• The additional benefit of basing SciPy on Python is that this also makes a powerful programming
language available for use in developing sophisticated programs and specialized applications.
Scientific applications using SciPy benefit from the development of additional modules in numerous
niches of the software landscape by developers across the world. Everything like web programming,
database subroutines and classes has been made available to the Python programmer. All of this power
is available in addition to the mathematical libraries in SciPy.
Advantages and Features of SciPy:
• SciPy contains varieties of sub packages which help to solve the most common issue related to
Scientific Computation.
• SciPy package in Python is the most used Scientific library only second to GNU Scientific Library for
C/C++ or Matlab’s.
• Easy to use and understand as well as fast computational power.
• It can operate on an array of NumPy library.
SciPy Organization:
• SciPy is organized into sub-packages covering different scientific computing domains. These are
summarized in the following table:
Table 6.2
Scipy Packages Package Domain
scipy.cluster Vector quantization / Kmeans.
scipy.constants Physical and mathematical constants.
scipy.fftpack Fourier transform.
Python [BBA (CA) - Sem. V] 6.5 Python Libraries
6.1.3 Pandas
• It is one of the most widely used python libraries in data science.
• It provides high-performance, easy to use structures and data analysis tools. Unlike NumPy library
which provides objects for multi-dimensional arrays.
• Pandas provides in-memory 2-D table object called Dataframe. It is like a spreadsheet with column
names and row labels.
• Pandas is an open source, providing high-performance, easy-to-use data structures and data analysis
tools for the Python programming language.
• The panda’s library has emerged into a power house of data manipulation tasks in python since it was
developed in 2008. With its intuitive syntax and flexible data structure, it's easy to learn and enables
faster data computation.
• The development of NumPy and pandas libraries has extended python's multipurpose nature to solve
machine learning problems as well. The acceptance of python language in machine learning has been
phenomenal since then.
• Python has long been great for data munging and preparation, but less so for data analysis and
modeling. Pandas, enabling you to carry out your entire data analysis workflow in Python without
having to switch to a more domain specific language like R. Python excels in performance,
productivity, and the ability to collaborate by Combining with the excellent IPython toolkit and other
libraries.
Features of Pandas:
1. A fast and efficient DataFrame object for data manipulation with integrated indexing.
2. Tools for reading and writing data between in-memory data structures and different formats: CSV
and text files, Microsoft Excel, SQL databases, and the fast HDF5 format.
Python [BBA (CA) - Sem. V] 6.6 Python Libraries
3. Intelligent data alignment and integrated handling of missing data: Gain automatic label-based
alignment in computations and easily manipulate messy data into an orderly form.
4. Flexible reshaping and pivoting of data sets.
5. Intelligent label-based slicing, fancy indexing, and subsetting of large data sets.
6. Columns can be inserted and deleted from data structures for size mutability.
7. Aggregating or transforming data with a powerful group by engine allowing splitapply-combine
operations on data sets.
8. High performance merging and joining of data sets.
9. Hierarchical axis indexing provides an intuitive way of working with highdimensional data in a
lower-dimensional data structure.
10. Time series-functionality: Date range generation and frequency conversion, moving window
statistics, moving window linear regressions, date shifting and lagging. Even create domain-
specific time offsets and join time series without losing data.
11. Highly optimized for performance, with critical code paths written in Cython (C extension for
python) or C.
12. Python with pandas is in use in a wide variety of academic and commercial domains, including
Finance, Neuroscience, Economics, Statistics, Advertising, Web Analytics, and more. Advantages
of Pandas
1. An Extensive set of features.
2. Less writing, more work done.
3. Excellent data representation.
4. Make the data flexible and customizable.
6.1.4 Installing NumPy, Scipy and Pandas
• You can download Python from https://www.python.org/download/.
• Installing via pip:
• Goto start and run cmd command , we get the command prompt. Then do the following steps.
Python [BBA (CA) - Sem. V] 6.7 Python Libraries
• It also uses Pandas for data handling and Patsy for R-like formula interface. It takes its graphics
functions from matplotlib. It is known to provide statistical background for other python packages.
Install StatsModels:
• Before getting StatsModels on your machine, StatsModels assumes the following functioning properly
on your machine: o Python 2.6 or later o NumPy 1.6 or later o Scipy 0.11 or later o Pandas 0.12 or
later
• Once you have these you can begin with installation.
• To install using pip, open your terminal and type the following command:
py –m pip install statsmodels
• Once you are done with the installation, you can use StatsModels easily in your Python code by
importing it: import statsmodels
6.2 DATA VISUALIZATION- MATPLOTLIB, SEABORN, PLOTLY
• Data visualization is a generic term used to describe any attempt to help understanding of data by
providing visual representation.
• Visualization of data makes it much easier to analyse and understand the textual and numeric data.
Apart from saving time, increased used of data for decision making further adds to the importance and
need of data visualization.
• Data visualization is a very important part of data analysis. You can use it to explore your data. If you
understand your data well, you’ll have a better chance to find some insights. Finally, when you find
any insights, you can use visualizations again to be able to share your findings with other people.
• Following are visualization packages in Python:
1. Matplotlib
2. Seaborn
3. Plotly
6.2.1 Matplotlib
• Matplotlib is an amazing visualization library in Python for 2D plots of arrays.
• Matplotlib is a multiplatform data visualization library built on NumPy arrays and designed to work
with the broader SciPy stack. It was introduced by John Hunter in the year 2002.
• Matplotlib has a module named pyplot which makes things easy for plotting by providing feature to
control line styles, font properties, formatting axes etc. It supports a very wide variety of graphs and
plots namely - histogram, bar charts, power spectra, error charts etc.
Python [BBA (CA) - Sem. V] 6.9 Python Libraries
• It is used along with NumPy to provide an environment that is an effective open source alternative for
MatLab. It can also be used with graphics toolkits like PyQt and wxPython.
• Matplotlib is an excellent 2D and 3D graphics library for generating scientific figures. Advantages of
Matplotlib library:
1. Easy to get started.
2. Matplotlib is free and open source code. It is also object-oriented and can be used in an object
oriented way.
3. It could be used on any operating system via its array of backend.
4. It has a familiar interface similar to MATLAB and had a coherent vision to do 2D graphics, and do
them well.
5. Support for \(\LaTeX\) formatted labels and texts.
6. Great control of every element in a figure, including figure size and DPI (Dots Per Inch).
7. High-quality output in many formats, including PNG, PDF, SVG, EPS.
8. GUI for interactively exploring figures and support for headless generation of figure files (useful
for batch jobs).
9. Another characteristic of Matplotlib is its steep learning curve, which means that users usually
make rapid progress after having started.
# frequencies ages =
[2,5,70,40,30,45,50,45,43,40,44,60,7,13,57,18,90,77,32,21,20,40]
# setting the ranges and no. of intervals range = (0, 100)
bins = 10
# plotting a histogram
plt.hist(ages, bins, range, color = 'green', histtype = 'bar',
rwidth =
0.8)
# x-axis label
plt.xlabel('age') #
frequency label
plt.ylabel('No. of
people')
# plot title
plt.title('My
histogram')
# function to show the plot
Python [BBA (CA) - Sem. V] 6.10 Python Libraries
plt.show()
Output:
6.2.2 Seaborn
• Seaborn is a data visualization library built on top of Matplotlib and closely integrated with
pandas data structures in Python.
• Seaborn offers the following functionalities:
1. Dataset oriented API to determine the relationship between variables.
2. Automatic estimation and plotting of linear regression plots.
3. It supports high-level abstractions for multi-plot grids.
4. Visualizing univariate and bivariate distribution.
• Using Seaborn we can plot wide varieties of plots like:
1. Distribution Plots
2. Pie Chart and Bar Chart
3. Scatter Plots
4. Pair Plots
5. Heat maps
6.2.3 Plotly
• Python Plotly Library is an open-source library that can be used for data visualization and
understanding data simply and easily. Plotly supports various types of plots like line charts, scatter
plots, histograms, cox plots, etc.
• Plotly allows users to import, copy and paste, or stream data to be analyzed and visualized. For
analysis and styling graphs, Plotly offers a Python sandbox (NumPy supported), datagrid,
and GUI. Python scripts can be saved, shared, and collaboratively edited
in Plotly.
Advantages Plotly over other visualization tools:
1. Plotly has hover tool capabilities that allow us to detect any outliers or anomalies in a large
number of data points.
2. It is visually attractive that can be accepted by a wide range of audiences.
3. It allows us for the endless customization of our graphs that makes our plot more meaningful and
understandable for others.
• The library is built upon the SciPy (Scientific Python) that must be installed before you can use Scikit-
learn. This stack that includes: o NumPy: Base n-dimensional array package.
o SciPy: Fundamental library for scientific computing.
o Matplotlib: Comprehensive 2D/3D plotting. o IPython: Enhanced interactive console.
o Sympy: Symbolic mathematics.
o Pandas: Data structures and analysis.
• Extensions or modules for SciPy care conventionally named SciKits. Such as, the module provides
learning algorithms and is named Scikit-learn.
• The vision for the library is a level of robustness and support required for use in production systems.
This means a deep focus on concerns such as ease of use, code quality, collaboration, documentation
and performance.
• Although the interface is Python, c-libraries are leverage for performance such as NumPy for arrays
and matrix operations, LAPACK, LibSVM and the careful use of cython.
• Every machine learning algorithm in Scikit-Learn is implemented via the Estimator API, which
provides a consistent interface for a wide range of machine learning applications.
Features of Scikit-Learn:
1. Simple and efficient tools for data mining and data analysis. It features various classification,
regression and clustering algorithms including support vector machines, random forests, gradient
boosting, k-means, etc.
2. Accessible to everybody and reusable in various contexts.
3. Built on the top of NumPy, SciPy and Matplotlib.
4. Open source, commercially usable – BSD license.
5. The library is focused on modeling data. It is not focused on loading, manipulating and
summarizing data.
Some popular groups of models provided by Scikit-learn include:
1. Clustering: For grouping unlabeled data such as K-Means.
2. Cross Validation: For estimating the performance of supervised models on unseen data.
3. Datasets: For test datasets and for generating datasets with specific properties for investigating
model behavior.
4. Dimensionality Reduction: For reducing the number of attributes in data for summarization,
visualization and feature selection such as principal component analysis.
5. Ensemble Methods: For combining the predictions of multiple supervised models.
6. Feature Extraction: For defining attributes in image and text data.
7. Feature Selection: For identifying meaningful attributes from which to create supervised models.
8. Parameter Tuning: For getting the most out of supervised models.
9. Manifold Learning: For summarizing and depicting complex multi-dimensional data.
10. Supervised Models: A vast array not limited to generalize linear models, discriminate analysis,
naive bayes, lazy methods, neural networks, support vector machines and decision trees.
The Scikit-Learn API is designed with the following guiding principles:
1. Consistency: All objects share a common interface drawn from a limited set of methods, with
consistent documentation.
Python [BBA (CA) - Sem. V] 6.14 Python Libraries
6.3.2 XGBoost
• XGBoost stands for “Extreme Gradient Boost”.
• XGBoost is used for supervised learning problems, where we use the training data (with multiple
features) xi to predict a target variable yi.
• It implements machine learning algorithms under the Gradient Boosting framework. XGBoost
provides a parallel tree boosting that solve many data science problems in a fast and accurate way.
• In supervised learning, Boosting takes a more iterative approach. In this technique many models are
combined together to perform the final one, but takes a more clever approach.
• Rather than training all of the models in isolation of one another, boosting trains models in succession,
with each new model being trained to correct the errors made by the previous ones. Models are added
sequentially until no further improvements can be made.
• The advantage of this iterative approach is that the new models being added are focused on correcting
the mistakes which were caused by other models. In a standard ensemble method where models are
trained in isolation, all of the models might simply end up making the same mistakes!
• Gradient Boosting specifically is an approach where new models are trained to predict the residuals
(i.e. errors) of prior models.
• The following figure shows the boosting process.
MLModel
Calculate
Errors
Train Model
Add Model
Predicting
to Ensemble
Errors
6.3.3 ELI5
• ELI5 is a python package which helps to debut machine learning classifiers and explain their
predictions.
Why ELI5?
• Debugging is an important step when working with machine learning models. For example, we have to
check if we have any noise in our features, when we are working with text that affects the predictions
such as unwanted symbols or numbers. ELI5 is a library which can help us debug machine learning
models.
• ELI5 can handle not only simples cases, but even for simple cases having a unified API for inspection
has as value: o We can get a nicely formatted result immediately by calling ready-made function from
ELI5.
o Formatting code can be reused between machine learning frameworks. o The
code like feature filtering or text highlighting can be reused.
6.4.1 TensorFlow
• TensorFlow is a Python library for fast numerical computing created and released by Google.
• It is a foundation library that can be used to create Deep Learning models directly or by using wrapper
libraries that simplify the process built on top of TensorFlow.
Python [BBA (CA) - Sem. V] 6.16 Python Libraries
•
TensorFlow is an end-to-end open source platform for machine learning. It has a comprehensive,
flexible ecosystem of tools, libraries and community resources that lets researchers push the state-of-
the-art in ML and developers easily build and deploy ML powered applications.
Why Tensorflow?
• Tensorflow bundles together on machine learning and deep learning models and algorithms and make
them useful by way of common betterment.
• Google use machine learning in all of its products to improve our search engine the translation image
captioning or recommendations. For example, Google users can experience a faster and more refined
search with artificial intelligence. If the user types of keyword in search bar, Google provides the
recommendation what could be the next one.
• Tensorflow used by a lot of companies in industries to name a few, start with Airbnb the leading global
online marketplace and hospitality service. The Airbnb ingenious and data science team applied
machine learning using Tensorflow to classify the images and detect object as key in helping to
improve the guest experience.
• The healthcare industry using Tensorflow, GE healthcare is training a neural network to identify
specific anatomic during the brain MRI exam to help improve speed and reliability.
• PayPal is using Tensorflow to stay at the cutting edge of fraud detection.
• Using Tensorflow, PayPal has been able to recognize complex fraud patterns to increase decline
accuracy while improving the experience of legitimate users through increased precision in
identification.
6.4.2 PyTorch
• PyTorch is an optimized tensor library primarily used for Deep Learning applications using
GPUs and CPUs. It is an open-source machine learning library for Python, mainly developed by the
Facebook AI Research team.
• PyTorch is the premier open-source deep learning framework developed and maintained by Facebook.
At its core, PyTorch is a mathematical library that allows you to perform efficient computation and
automatic differentiation on graph-based models.
• Tensorflow is much better for production models and scalability. It was built to be production ready.
Whereas, PyTorch is easier to learn and lighter to work with, and hence, is relatively better for passion
projects and building rapid prototypes.
• PyTorch is used for computer vision and Natural Language Processing (NLP) applications. Google
Colab was developed by Google to help the masses access powerful GPU resources to run deep
learning experiments. It offers GPU (Graphics Processing Units) support and integration with Google
Drive for storage.
PyTorch defines a class called Tensor (torch.Tensor) to store and operate on homogeneous
multidimensional rectangular arrays of numbers.
PyTorch provides two high-level features:
• Tensor computing (like NumPy) with strong acceleration via Graphics Processing Units (GPU).
Python [BBA (CA) - Sem. V] 6.17 Python Libraries
•
• Deep neural networks built on a type-based automatic differentiation system. Keras
6.4.3 • One of the most powerful and easy-to-use Python libraries for developing and evaluating deep
learning models is Keras; It wraps the efficient numerical computation libraries Theano and
TensorFlow. The advantage of this is mainly that you can get started with neural networks in an easy
and fun way.
• Keras is a deep learning API written in Python, running on top of the machine learning platform
TensorFlow. It was developed with a focus on enabling fast experimentation and doing good research.
Features of Keras:
1. Simple: But not simplistic. Keras reduces developer cognitive load to free you to focus on the
parts of the problem that really matter.
2. Flexible: Keras adopts the principle of progressive disclosure of complexity. Simple workflows
should be quick and easy, while arbitrarily advanced workflows should be possible via a clear path
that builds upon what you've already learned. 3. Powerful: Keras provides industry-strength
performance and scalability. It is used by organizations and companies including NASA,
YouTube, or Waymo. Keras was developed and maintained by François Chollet, a Google
engineer using four guiding principles:
1. Modularity: A model can be understood as a sequence or a graph alone. All the concerns of a deep
learning model are discrete components that can be combined in arbitrary ways.
2. Minimalism: The library provides just enough to achieve an outcome, no frills and maximizing
readability.
3. Extensibility: New components are intentionally easy to add and use within the framework,
intended for researchers to trial and explore new ideas.
4. Python: No separate model files with custom file formats. Everything is native Python.
Advantages:
1. The most well-known and full NPL library.
2. Many third-party extensions.
3. Plenty of approaches to each NLP task.
4. Fast sentence tokenization.
5. Supports the largest number of langauges compared to other libraries.
Disadvantages:
1. Complicated to learn and use.
2. Quite slow.
3. In sentence tokenization, NLTK only splits text by sentences, without analyzing the semantic
structure.
4. Processes strings which is not very typical for object-oriented language python.
5. Does not provide neural network models.
6. No integrated word vectors. SpaCy
6.5.2 • This is a completely optimized and highly accurate library widely used in deep learning.
• SpaCy is an open-source software library for advanced natural language processing, written in
the programming languages Python and Cython. The library is developed by Matthew Honnibal and
Ines Montani, the founders of the software company Explosion.
• SpaCy focuses on providing software for production usage rather than teaching and research.
Features:
1. Non-destructive tokenization.
2. Named entity recognition.
3. Support for 61+ languages.
4. 46 statistical models for 16 languages.
5. Pre-Trained word vectors
6. State-of-the-art speed.
7. Easy deep learning integration.
8. Labeled dependency parsing.
9. Syntax-driven sentence segmentation.
10. Export to NumPy data arrays. 11. Efficient binary serialization.
12. Easy model packaging and deployment.
13. Robust, rigorously evaluated accuracy.
Advantages:
1. The fastest NLP framework.
2. Easy to learn and use because it has one single highly optimized tool for each task.
3. Processes objects; more object-oriented, comparing to other libs.
4. Uses neural networks for training some models.
5. Provides built-in word vectors. 6. Active support and development. Disadvantages:
1. Lacks flexibility, comparing to NLTK.
2. Sentence tokenization is slower than in NLTK.
Python [BBA (CA) - Sem. V] 6.20 Python Libraries
3. Does not support many languages. There are models only for 7 languages and "multi-language"
models.
6.5.3 Gensim
• Genism is a robust open source NLP library support in Python. This library is highly efficient
and scalable.
• Gensim is a Python library for representing documents as semantic vectors, as efficiently (computer-
wise) and painlessly (human-wise) as possible.
• Gensim is designed to process raw, unstructured digital texts (“plain text”) using unsupervised machine
learning algorithms.
• We built Gensim from scratch for: o Practicality: As industry experts, we focus on proven, battle-
hardened algorithms to solve real industry problems. More focus on engineering, less on academia.
o Memory independence: There is no need for the whole training corpus to reside fully in RAM at
any one time. Can process large, web-scale corpora using data streaming.
o Performance: Highly optimized implementations of popular vector space algorithms using C,
BLAS and memory-mapping.
Advantages:
1. Works with large datasets and processes data streams.
2. Provides tf-idf vectorization, word2vec, document2vec, latent semantic analysis, latent Dirichlet
allocation.
3. Support deep learning.
Disadvantages:
1. Designed primarily for unsupervised text modeling.
2. Does not have enough tools to provide full NLP pipeline, so should be used with some other
library (SpaCy or NLTK). Sample Programs:
Program 6.4: Write a Python program to draw a line with suitable label in the x axis, y axis and a title.
import matplotlib.pyplot as plt
X = range(1, 50)
Y = [value * 3 for value in X]
print("Values of X:")
print(*range(1,50))
print("Values of Y (thrice of
X):") print(Y)
# Plot lines and/or markers to the Axes.
plt.plot(X, Y)
# Set the x axis label of the current axis.
plt.xlabel('x - axis')
Python [BBA (CA) - Sem. V] 6.21 Python Libraries
Program 6.5: Write a Python program to plot two or more lines with legends, different widths and colors.
import matplotlib.pyplot as plt
# line 1
points x1
=[10,20,30] y1
=[20,40,10] #
line 2 points
x2 =[10,20,30]
y2 =[40,10,30]
# Set the x axis label of the current axis.
plt.xlabel('x - axis')
# Set the y axis label of the current axis.
plt.ylabel('y - axis')
# Set a title
plt.title('Two or more lines with different widths and colors with
suitable legends ')
# Display the figure.
plt.plot(x1,y1, color='blue', linewidth =3, label ='line1-width-3')
plt.plot(x2,y2, color='red', linewidth =5, label ='line2-width-5')
# show a legend on the plot
plt.legend()
Python [BBA (CA) - Sem. V] 6.22 Python Libraries
plt.show()
Output:
Program 6.6: Write a Python program to plot quantities which have an x and y position.
import NumPy as np
import pylab as pl #
Make an array of x
values x1 =[2,3,5,6,8]
# Make an array of y values for each x
value y1 =[1,5,10,18,20] # Make an array
of x values x2 =[3,4,6,7,9]
# Make an array of y values for each x
value y2 =[2,6,11,20,22] # set new axes
limits pl.axis([0,10,0,30])
# use pylab to plot x and y as red
circles pl.plot(x1, y1,'b*', x2,
y2,'ro') # show the plot on the screen
pl.show() :
Output:
Python [BBA (CA) - Sem. V] 6.23 Python Libraries
Program 6.7: Write a Python program to plot two or more lines with different styles.
import matplotlib.pyplot as plt
# line 1
points x1
=[10,20,30] y1
=[20,40,10] #
line 2 points
x2 =[10,20,30]
y2 =[40,10,30]
# Set the x axis label of the current axis.
plt.xlabel('x - axis')
# Set the y axis label of the current axis.
plt.ylabel('y - axis')
# Plot lines and/or markers to the Axes.
plt.plot(x1,y1, color='blue', linewidth =3,
label ='line1-dotted',linestyle='dotted')
plt.plot(x2,y2, color='red', linewidth =5,
label ='line2-dashed', linestyle='dashed')
# Set a title plt.title("Plot with two or more lines
with different styles")
# show a legend on the plot
plt.legend()
# function to show the plot
plt.show()
Python [BBA (CA) - Sem. V] 6.24 Python Libraries
Output:
Program 6.9: Write a Python program to create bar plot from a DataFrame. Sample Data Frame:
Python [BBA (CA) - Sem. V] 6.25 Python Libraries
a b c d e
24,8,5,7,6
42,3,4,2,6
64,7,4,7,8
82,6,4,8,6
102,4,3,3,2
from pandas import DataFrame
import matplotlib.pyplot as plt
import NumPy as np
a=np.array([[4,8,5,7,6],[2,3,4,2,6],[4,7,4,7,8],[2,6,4,8,6],
[2,4,3,3,2]]) df=DataFrame(a, columns=['a','b','c','d','e'],
index=[2,4,6,8,10])
df.plot(kind='bar')
# Turn on the grid
plt.minorticks_on()
plt.grid(which='major', linestyle='-', linewidth='0.5',
color='green') plt.grid(which='minor', linestyle=':',
linewidth='0.5', color='black') plt.show()
:
Output:
Program 6.10: Write a Python program to draw a scatter plot comparing two subject marks of Mathematics
and Science. Use marks of 10 students. Test Data:
math_marks = [88, 92, 80, 89, 100, 80, 60, 100, 80,
34] science_marks = [35, 79, 79, 48, 100, 88, 32,
45, 20, 30] marks_range = [10, 20, 30, 40, 50, 60,
70, 80, 90, 100] import matplotlib.pyplot as plt
import pandas as pd
math_marks =[88,92,80,89,100,80,60,100,80,34]
science_marks =[35,79,79,48,100,88,32,45,20,30]
marks_range =[10,20,30,40,50,60,70,80,90,100]
Python [BBA (CA) - Sem. V] 6.26 Python Libraries
Practice Questions
Q.I Answer the following Questions in short.
1. What is Scikit-learn?
2. What are the features of Scikit learn?
3. What are the guiding principles behind Scikit-learn API?
4. What are the basic steps in using the Scikit-Learn estimator API?
5. What are the advantages of using Matplotlib library?
6. What are the different output formats supported by Matplotlib library? Q.II Answer the
following Questions.
1. What are the advantages and disadvantage of Gensim?
2. What are the advantages and disadvantage of SpaCy?
3. What are the advantages and disadvantage of NLTK?
4. Compare NLTK and SpaCy.
5. Compare Keras, Tensorflow and Pytorch
6. Write the four principal of keras.
7. State the guiding principles for designing Scikit-Learn API.
8. State the features of Scikit-learn.
9. What are the Advantages of Plotly over other visualization tools?
10. State the advantages of Matplotlib.
11. What is Seaborn?
12. What is Scikit-learn?
13. List out the plots that can plot with Seaborn.
14. State the use of Keras.
15. State the use of Pytorch.
16. State the uses of Tensorflow. Q.III Define the terms.
1. Seaborn
2. Data Visualization
3. Data Modelling
4. XGBoost
5. SpaCy