PYTHON Textbook
PYTHON Textbook
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 College 119, Budhwar Peth, Jogeshwari Mandir Lane
Pune 411041, Maharashtra Pune 411002, Maharashtra
Tel : (020) 24690204; Mobile : 9657703143 Tel : (020) 2445 2044; Mobile : 9657703145
Email : bookorder@pragationline.com Email : niralilocal@pragationline.com
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 : niralimumbai@pragationline.com
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 : delhi@niralibooks.com Email : bengaluru@niralibooks.com Email : nagpur@niralibooks.com
marketing@pragationline.com | www.pragationline.com
Also find us on www.facebook.com/niralibooks
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 …
1.1 INTRODUCTION
• 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
Interpreter
Byte Virtual
Compiler
code machine
Running code
Source code
Library
modules
8. GUI Programming and Databases: Python supports GUI applications that can be
created and ported to many libraries and windows systems, such as Windows
Microsoft Foundation Classes (MFC), Macintosh, and the X Window system of Unix
Python also provides interlaces to all major commercial databases.
9. Broad Standard Library: Python's library is portable and cross platform
compatible on UNIX, Linux, Windows and Macintosh. This helps in the support
and development of a wide range of applications from simple text processing to
browsers and complex games.
10. Free and Open Source: Python programming language is developed under an OSI
approved open source license making it freely available at official web address.
The source code is also available for use. The Python software can be freely
distributed and any one can use and read its source code make
changes/modifications to it and use the pieces in new free programs.
1.1.3 Setting-up Path
• Before starting working with Python, a specific path is to set.
• Your Python program and executable code can reside in any directory of your system,
therefore Operating System provides a specific search path that index the directories
Operating System should search for executable code.
• The Path is set in the Environment Variable of My Computer properties.
• Steps are as follows:
1. First install the python. Then go to this pc (My Computer) and Right click on My
Computer and click on properties. This should open up the System Properties
window. Go to the Advanced tab and click the Environment Variables button:
Fig. 1.2
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
Python [BBA (CA) - Sem. V] 1.6 Introduction to Python
5. Click on Ok button:
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:
1.1.4 Working with Python Interpreter
• An interpreter is a kind of program that executes other programs. When you write
Python programs, it converts source code written by the developer into intermediate
language which is again translated into the native language / machine language that
is executed.
Starting Python in different Modes:
1. Starting Python Command Line:
• A Python script can be executed at command line also. This can be done by invoking
the interpreter on the application.
• In command line mode, we type the Python programming program on the Python
shell and the interpreter prints the result. The steps are given below:
Python [BBA (CA) - Sem. V] 1.7 Introduction to Python
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.
Python [BBA (CA) - Sem. V] 1.8 Introduction to Python
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.13
• Write Python program in script mode, (See Fig. 1.14).
Fig. 1.14
• Save the above code with filename. By default, python interpreter will save it using
the filename.py. Here, we save the script with file name test.py.
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.
Fig. 1.17
Python [BBA (CA) - Sem. V] 1.10 Introduction to Python
Import Statement
Subprogram Section
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)).
• 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
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.
• 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 [BBA (CA) - Sem. V] 1.20 Introduction to Python
• 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:
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.
Python [BBA (CA) - Sem. V] 1.22 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.
• 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.25 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 x is not True
same object)
Program 1.6: For Identity operators.
x1 = 5
y1 = 5
x2 = 'Hello'
y2 = 'Hello'
x3 = [1,2,3]
y3 = [1,2,3]
print(x1 is not y1)
# Output: False
print(x2 is y2)
# Output: True
print(x3 is y3)
# Output: False
Python [BBA (CA) - Sem. V] 1.26 Introduction to Python
• 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
Program 1.6: For Membership operators.
x = 'Hello world'
y = {1:'a',2:'b'}
print('H' in x)
# Output: True
print('hello' not in x)
# Output: True
print(1 in y)
# Output: True
print('a' in y)
# Output: False
• 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.
Syntax:
if expression:
sequence of statements-1
elif condition-n:
sequence of statements-n
else:
default sequence of statements
Program 1.10: Program for IF...ELIF...ELSE Statements.
a = 4
b = 4
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
Output:
a and b are equal
(iv) Nested IF-Else Statement:
• A nested if is an if statement that is the target of another if statement. Nested if
statement means an if statement within another if statement.
Syntax:
if (<condition1>):
statement(s)
if (<condition2>):
statement(s)
else
else:
if (<condition3>):
statement(s)
else
Statement(s)
Program 1.11: Program for Nested if-else Statements.
a = -10
if a > 0:
print("Positive Number")
Python [BBA (CA) - Sem. V] 1.29 Introduction to Python
else:
print("Negative Number")
#nested if
if -10 <= a:
print("Two digit Negative Number")
Output:
Negative Number
Two digit Negative Number
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
Program 1.13: Example for “for” statement.
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
for letter in 'Python':
print(letter)
print("Good bye!")
Output:
apple
banana
cherry
P
Good bye!
y
Good bye!
t
Good bye!
h
Good bye!
o
Good bye!
n
Good bye!
Python [BBA (CA) - Sem. V] 1.31 Introduction to Python
Output:
1
a
b
c
2
a
b
c
3
a
b
c
Output:
Current variable value: 10
Current variable value: 9
Current variable value: 8
Out loop
2. continue Statement:
• 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
Program 1.18: Example for continue statement.
for letter in 'Sybca':
if letter == 'b':
continue
print('Current Letter:', letter)
Output:
Current Letter: S
Current Letter: y
Current Letter: c
Current Letter: a
Program 1.19: Example for continue statement.
var = 5
while var > 0:
var = var -1
if var == 3:
continue
print('Current variable value:', var)
print('In loop')
Output:
Current variable value: 4
In loop
Current variable value: 2
In loop
Current variable value: 1
In loop
Current variable value: 0
In loop
Python [BBA (CA) - Sem. V] 1.34 Introduction to Python
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
Program 1.20: Example for pass statement.
for letter in 'Sybca':
if letter == 'b':
pass
print('This is pass block')
print('Current Letter:', letter)
Output:
This is pass block
Current Letter: S
This is pass block
Current Letter: y
This is pass block
Current Letter: b
This is pass block
Current Letter: c
This is pass block
Current Letter: a
my_string = "Hello"
print(my_string)
my_string = '''Hello'''
print(my_string)
Python [BBA (CA) - Sem. V] 1.35 Introduction to Python
0 1 2 3 4 5
str P Y T H O N Backward
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].
1.6.1 Accessing String
• Python does not support a character type; these are treated as strings of length one,
thus also considered a substring. Square brackets can be used to access elements of
the string.
• We can access individual characters using indexing and a range of characters using
slicing. Index starts from 0. Trying to access a character out of index range will raise
an IndexError. The index must be an integer. We can't use floats or other types, this
will result into TypeError.
• 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.
Python [BBA (CA) - Sem. V] 1.36 Introduction to Python
• As an alternative, Python uses negative numbers to give easy access to the chars at
the end of the string: s[-1] is the last char 'o', s[-2] is 'l' the next-to-last char, and so on.
• Example: Suppose we have s = "Hello"
s[1:4] is 'ell' -- chars starting at index 1 and extending up to but not including index 4
s[1:] is 'ello' -- omitting either index defaults to the start or end of the string
s[:] is 'Hello' -- omitting both always gives us a copy of the whole thing (this is the
pythonic way to copy a sequence like a string or list)
st
s[-1] is 'o' -- last char (1 from the end)
th
s[-4] is 'e' -- 4 from the end
Program 1.23: Program for array slicing.
msg1 = 'Python'
print("msg1[1:5] = ", msg1[1:5])
Output:
msg1[1:5] = ytho
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:
Enter string: Hello world
Newly formed string is: Held
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$
Python [BBA (CA) - Sem. V] 1.40 Introduction to Python
Example:
list1 = ["apple", "banana", "cherry"]
print(list1)
Output:
["apple", "banana", "cherry"]
Advantages of Tuple:
1. Processing of Tuples are faster than Lists.
2. It makes the data safe because tuples are immutable and hence cannot be
changed.
3. Generally tuples are used for heterogeneous (different) datatypes and list for
homogeneous (similar) datatypes.
4. Tuples are used for String formatting.
Difference between Tuples and Lists:
1. The syntax of tuples is shown by parenthesis() whereas the syntax of lists is shown
by square brackets[ ].
2. List has variable length, tuple has fixed length.
3. List has mustable nature, tuple has immutable nature.
4. List has more functionality than the tuple.
5. Typles are heterogeneous while lists are homogeneous. One has to deal
individually with the items.
6. Tuples show structure whereas lists show order.
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.
Program 1.29: Python program for creating Tuples.
# empty tuple
my_tuple = ()
print(my_tuple)
# nested tuple
my_tuple = ("Hello", [8, 4, 6], (1, 2, 3))
print(my_tuple)
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.
l_range=int(input("Enter the lower range:"))
u_range=int(input("Enter the upper range:"))
a=[(x,x**2) for x in range(l_range,u_range+1)]
print(a)
Output:
Enter the lower range:1
Enter the upper range:4
[(1, 1), (2, 4), (3, 9), (4, 16)]
Examples:
Program 1.33: Write a Python program to add an item in a tuple.
#create a tuple
tuplex = (4, 6, 2, 8, 3, 1)
print(tuplex)
#tuples are immutable, so you can not add new elements
#using merge of tuples with the + operator you can add an element and it
will create a new tuple
tuplex = tuplex + (9,)
print(tuplex)
#adding items in a specific index
Python [BBA (CA) - Sem. V] 1.52 Introduction to Python
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
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'})
# add item
dict1['address'] = 'pune'
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.
Python [BBA (CA) - Sem. V] 1.59 Introduction to Python
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'
1.9.4 Function and Methods
Python includes the following dictionary functions:
1. cmp(dict1, dict2): Compares elements of both dict.
2. len(dict): Gives the total length of the dictionary. This would be equal to the
number of items in the dictionary.
3. str(dict): Produces a printable string representation of a dictionary.
4. type(variable): Returns the type of the passed variable. If passed variable is
dictionary, then it would return a dictionary type.
Example:
dict = {'Name': 'abc', 'Age':20};
#usage of len() method
print "Length: %d" % len (dict) #Output:Length: 2
# usage of type() method
Python [BBA (CA) - Sem. V] 1.60 Introduction to Python
# clear() method.
print("Start Len: %d" % len(dict))
dict.clear()
print("End Len: %d" % len(dict))
Python [BBA (CA) - Sem. V] 1.61 Introduction to Python
Output:
Value: dict_items([('Name', 'abc'), ('Age', 20)])
Value: {'Name': 'abc', 'Age': 20, 'Sex': 'female'}
Value: dict_keys(['Name', 'Age', 'Sex'])
Value: dict_values(['abc', 20, 'female'])
New Dictionary: {'Name': 'abc', 'Age': 20, 'Sex': 'female'}
Start Len: 3
End Len: 0
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}
Program 1.45: Write a Python script to add a key to a dictionary.
Sample Dictionary : {0: 10, 1: 20} Expected Result : {0: 10, 1: 20, 2: 30}.
d = {0:10, 1:20}
print(d)
d.update({2:30})
print(d)
Write a Python script to concatenate following dictionaries to create a new
one.
Sample Dictionary:
dic1={1:10, 2:20}
dic2={3:30, 4:40}
dic3={5:50,6:60}
Expected Result: {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
dic1={1:10, 2:20}
dic2={3:30, 4:40}
dic3={5:50,6:60}
dic4 = {}
for d in (dic1, dic2, dic3): dic4.update(d)
print(dic4)
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}
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}
Python [BBA (CA) - Sem. V] 1.63 Introduction to Python
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))
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)
Python [BBA (CA) - Sem. V] 1.64 Introduction to Python
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.
x = {'key1': 1, 'key2': 3, 'key3': 2}
y = {'key1': 1, 'key2': 2}
for (key, value) in set(x.items()) & set(y.items()):
print('%s: %s is present in both x and y' % (key, value))
• 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():
print("Hello from a function")
# A string as input parameter and prints it on standard screen.
def fun( str ):
"This prints a passed string into this function"
print str
return
1.10.2 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. If
there is a return value defined, the function would return the value, else the function
would return None.
• To call a function, use the function name followed by parenthesis, if you need to pass
parameters/arguments to the function, you write them inside the parentheses.
Syntax: function_name(arg1, arg2)
Example:
1. Call a function that performs a task and has no return value.
def my_function():
print("Hello from a function")
my_function()
Output: 'Hello from a function'
Python [BBA (CA) - Sem. V] 1.66 Introduction to Python
Example:
# Function definition is here
def mydata( name, age ):
"This prints a passed info into this function"
print "Name: ", name
print "Age: ", age
return;
# calling the function
mydata( age=50, name="manisha" )
Output:
Name: manisha
Age: 50
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.70 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 non-
keyword 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;
Python [BBA (CA) - Sem. V] 1.71 Introduction to Python
Example:
#Function Definition
square=lambda x1: x1*x1
#Calling square as a function
print "Square of number is",square(10)
Output:
>>>
Square of number is 100
>>>
Example: Program To Display Powers of 2 Using Anonymous Function.
terms = int(input("How many terms? "))
# use anonymous function
result = list(map(lambda x: 2 ** x, range(terms)))
# display the result
print("The total terms is:",terms)
for i in range(terms):
print("2 raised to power",i,"is",result[i])
Output:
The total terms is: 10
2 raised to power 0 is 1
2 raised to power 1 is 2
2 raised to power 2 is 4
2 raised to power 3 is 8
2 raised to power 4 is 16
2 raised to power 5 is 32
2 raised to power 6 is 64
2 raised to power 7 is 128
2 raised to power 8 is 256
2 raised to power 9 is 512
1.10.6 Global and Local Variable, Examples
• A variable’s scope tells us where in the program it is visible. A variable may have local
or global scope. A variable that’s declared inside a function has a local scope. When
you declare a variable outside python functions, or anything else, it has global scope.
• A variable’s lifetime is the period of time for which it resides in the memory. A
variable that’s declared inside python functions is destroyed after the function stops
executing. So the next time the function is called, it does not remember the previous
value of that variable.
Python [BBA (CA) - Sem. V] 1.73 Introduction to Python
• All variables in a program may not be accessible at all locations in that program. This
depends on where you have declared a variable.
• There are two basic scopes of variables in Python:
o Local variables: Variables declared inside a function body is known as Local
Variable.
o Global variables: Variable defined outside the function is called Global Variable.
Global Vs. Local Variables:
• 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.74 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]
Additional Programs
Program 1.66: Program to find the square root of a number.
x=int(input("Enter an integer number:"))
ans=x**0.5
print("Square root= ", ans)
Output:
Enter an integer number: 144
Square root= 12.0
Program 1.67: Program to find the area of Rectangle.
l=float(input("Enter length of the rectangle: "))
b=float(input("Enter breadth of the rectangle: "))
area=l*b
print("Area of Rectangle= ",area)
Output:
Enter length of the rectangle: 5
Enter breadth of the rectangle: 6
Area of Rectangle= 30.0
Program 1.68: Write a program to display following pattern.
Code:
1 2 3 4
1 2 3
1 2
1
a=[1,2,3,4]
for i in range(4+1):
for j in range(4-i):
print(a[j],end=" ")
print(" ")
Python [BBA (CA) - Sem. V] 1.78 Introduction to Python
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
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.
Python [BBA (CA) - Sem. V] 1.82 Introduction to Python
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?
Python [BBA (CA) - Sem. V] 1.84 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)
Python [BBA (CA) - Sem. V] 2.2 Modules and Packages
• 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.
• 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.
2.2.1 Creating Module
• Writing a module means simply creating a file which can contains python definitions
and statements. The file name is the module name with the extension .py. To include
module in a file, use import statement.
• Follow the following steps to create modules:
1. Create a first file as a python program with extension as .py. This is your module
file where we can write a function which performs some task.
2. Create a second file in the same directory called main file where we can import
the module to the top of the file and call the function.
• Second file needs to be in the same directory so that Python knows where to find the
module since it’s not a built-in module.
Python [BBA (CA) - Sem. V] 2.3 Modules and Packages
Program 2.1: For creating a module. Type the following code and save it as p1.py.
def add(a, b):
"This function adds two numbers and return the result"
result = a + b
return result
def sub(a, b):
"This function subtract two numbers and return the result"
result = a - b
return result
def mul(a, b):
"This function multiply two numbers and return the result"
result = a * b
return result
def div(a, b):
"This function divide two numbers and return the result"
result = a / b
return result
Import the definitions inside a module:
import p1
print("Addition=" , p1.add(10,20))
print("Subtraction=" ,p1.sub(10,20))
print("Multiplication=" ,p1.mul(10,20))
print("division=" ,p1.div(10,20))
Output:
Addition= 30
Subtraction= -10
Multiplication= 200
division= 0.5
>>> log(c,2)
(1.5000000000000002+1.1330900354567985j)
>>> sqrt(c)
(1.5537739740300374+0.6435942529055826j)
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.
Example: For decimal module.
>>> from decimal import Decimal
>>> Decimal(121)
Decimal('121')
>>> Decimal(0.05)
Decimal('0.05000000000000000277555756156289135105907917022705078125')
>>> Decimal('0.15')
Decimal('0.15')
>>> Decimal('0.012')+Decimal('0.2')
Decimal('0.212')
>>> Decimal(72)/Decimal(7)
Decimal('10.28571428571428571428571429')
>>> Decimal(2).sqrt()
Decimal('1.414213562373095048801688724')
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.
• Example: For fractions module.
>>> import fractions
>>> for num, decimal in [(3, 2), (2, 5), (30, 4)]:
fract = fractions.Fraction(num, decimal)
print(fract)
3/2
2/5
15/2
• 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)
Python [BBA (CA) - Sem. V] 2.8 Modules and Packages
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).
Example: For statistics module.
>>> import statistics
>>> statistics.mean([2,5,6,9]) # average
5.5
>>> import statistics
>>> statistics.median([1,2,3,8,9]) # central value
3
>>> statistics.median([1,2,3,7,8,9])
5.0
>>> import statistics
>>> statistics.mode([2,5,3,2,8,3,9,4,2,5,6]) # repeated value
2
>>> import statistics
>>> statistics.stdev([1,1.5,2,2.5,3,3.5,4,4.5,5])
1.3693063937629153
5. Time Module:
• There is a popular time module available in Python which provides functions for
working with times and for converting between representations.
• Python has a module named time to handle time-related tasks. To use functions
defined in the module, we need to import the module first like import time.
• Python “time” module has following functions:
(i) time(): This function returns the current time instant, a floating-point number
of seconds since the epoch. Example. The function time() returns the current
system time in ticks since 00:00:00 hrs January 1, 1970 (epoch).
import time; # This is required to include time module.
ticks = time.time()
print "Number of ticks since 12:00am, January 1, 1970:", ticks
#Output Number of ticks since 12:00am, January 1, 1970: 7186862.73399
(ii) gmtime(sec): This function returns a structure with 9 values each representing
a time attribute in sequence. It converts seconds into time attributes(days,
years, months etc.) till specified seconds from epoch. If no seconds are
mentioned, time is calculated till present.
Python [BBA (CA) - Sem. V] 2.9 Modules and Packages
Output:
Example:
# Python code to display the calendar of the given year.
# importing calendar module
import calendar
# prints calendar of 2018
print ("The calendar of year 2021 is: ")
print (calendar.calendar(2021, 2, 1, 6))
Output:
Python [BBA (CA) - Sem. V] 2.12 Modules and Packages
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.
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.
Python [BBA (CA) - Sem. V] 2.13 Modules and Packages
Example:
import random
print “ uniform no(1,100):”, random.uniform(1,100)
# uniform no(1,100) 9.38500684602
4. random(): This generates the random numbers from 0 to 1.
Example:
>>> from random import random
>>> random() # 0.8407436368337916
>>> random() # 0.3069951291690556
>>> random() # 0.4887997856049814
>>> random() # 0.35343343245685684
Each time random generates the different number.
5. randint(): random.randint(a,b) here a is lower and b is upper bound.
Example:
import random
print random.randint(0,5) #output either 1,2,3,4 or 5
6. choice(): random.choice(sequence)
Example:
import random
MyChoice = random.choice[('1-Swimming', '2-Badminton', '3-Cricket',
'4-Basketball', '5-Hockey'])
print 'My choice is:', MyChoice #returns: My choice is: 4-Basketball
2.3 USER DEFINED FUNCTIONS
• A function is a set of statements that take inputs, do some specific computation and
produce output. The idea is to put some commonly or repeatedly done tasks together
and make a function so that instead of writing the same code again and again for
different inputs, we can call the function.
• Functions that readily comes with Python are called built-in functions. Python
provides built-in functions like print(), etc. but we can also create your own functions.
These functions are known as user defines functions.
• 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
.
.
Python [BBA (CA) - Sem. V] 2.15 Modules and Packages
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
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).
2.4.1 Creating and Importing Packages
• Creating a package is quite easy, since it makes use of the operating system’s inherent
hierarchical file structure as shown in Fig. 2.1.
• Here, there is a directory named mypack that contains two modules, p1.py and p2.py.
The contents of the modules are:
p1.py
def m1():
print("first module")
p2.py
def m2():
print("second module")
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
>>> mypack.p1.m1()
first module
>>> p1.m1()
Python [BBA (CA) - Sem. V] 2.17 Modules and Packages
• 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.
>>> import math
>>> math.pi
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.
>>> import math
>>> math.e
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.
• There are various plots which can be created using python matplotlib like bar graph,
histogram, scatter plot, area plot, pie plot.
Python [BBA (CA) - Sem. V] 2.19 Modules and Packages
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.
2.4.3 User Defined Packages
• We organize a large number of files in different folders and subfolders based on some
criteria, so that we can find and manage them easily. In the same way, a package in
Python takes the concept of the modular approach to next logical level.
• As we know, a module can contain multiple objects, such as classes, functions, etc. A
package can contain one or more relevant modules.
• Physically, a package is actually a folder containing one or more module files. Let's
create a package named Mypack, using the following steps:
Step 1: Create a folder Mypack on
C:\Users\AppData\Local\Programs\Python\Python3.9.6\”.
Create modules Message.py and Mathematics.py with following code:
Message.py
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.
Python [BBA (CA) - Sem. V] 2.20 Modules and Packages
Step 3: Create P1.py file in Mypack folder and write following code:
from Mypack import Mathematics
from Mypack import Message
greet.SayHello("Meenakshi")
x=functions.power(3,2)
print("power(3,2): ", x)
Output:
Hello Meenakshi
power(3,2): 9
Using _ _init_ _.py File:
• The _ _init_ _.py file is normally kept empty. However, it can also be used to choose
specific functions from modules in the package folder and make them available for
import. Modify _ _init_ _.py as below:
_ _init_ _.py
from .Mathematics import average, power
from .Message import SayHello
• The specified functions can now be imported in the interpreter session or another
executable script.
Create test.py in the Mypack folder and write following code:
test.py
from Mypack import power, average, SayHello
SayHello()
x=power(3,2)
print("power(3,2): ", x)
• Note that functions power() and SayHello() are imported from the package and not
from their respective modules, as done earlier. The output of above script is:
Hello world
power(3,2): 9
2.4.4 Package Examples
• We have included a _ _init_ _.py, file inside a directory to tell Python that the current
directory is a package.
• Whenever we want to create a package, then we have to include _ _init_ _.py file in the
directory. We can write code inside it.
• Let's create a simple package that has the following structure:
Package (university)
o __init__.py
o student.py
o faculty.py
Python [BBA (CA) - Sem. V] 2.21 Modules and Packages
# student.py
class Student:
def __init__(self, student):
self.name = student['name']
self.gender = student['gender']
self.year = 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
Python [BBA (CA) - Sem. V] 2.22 Modules and Packages
• 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
...
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
Program 2.3: For NumPy with array object.
>>> import numpy as np
>>> a=np.array([1,2,3]) # one dimensional array
>>> print(a)
[1 2 3]
>>> arr=np.array([[1,2,3],[4,5,6]]) # two dimensional array
>>> print(arr)
[[1 2 3]
[4 5 6]]
>>> type(arr)
<class 'numpy.ndarray'>
>>> print("No. of dimension: ", arr.ndim)
Python [BBA (CA) - Sem. V] 2.23 Modules and Packages
No. of dimension: 2
>>> print("Shape of array: ", arr.shape)
Shape of array: (2, 3)
>> >print("size of array: ", arr.size)
size of array: 6
>>> print("Type of elements in array: ", arr.dtype)
Type of elements in array: int32
>>> print("No of bytes:", arr.nbytes)
No of bytes: 24
Program 2.4: Using linalg sub package of SciPy.
>>> import numpy as np
>>> from scipy import linalg
>>> a = np.array([[1., 2.], [3., 4.]])
>>> linalg.inv(a) # find inverse of array
array([[-2. , 1. ],
[ 1.5, -0.5]])
>>>
Program 2.5: Using linalg sub package of SciPy.
>>> import numpy as np
>>> from scipy import linalg
>>> a = np.array([[1,2,3], [4,5,6], [7,8,9]])
>>> linalg.det(a) # find determinant of array
0.0
>>>
Program 2.6: For line plot.
>>> from matplotlib import pyplot as plt
>>> x=[2,4,8,10]
>>> y=[2,8,8,2]
>>> plt.plot(x,y)
[<matplotlib.lines.Line2D object at 0x02E69B70>]
>>> plt.show()
Output:
Python [BBA (CA) - Sem. V] 2.24 Modules and Packages
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):
print("employee name: ",name)
print("salary: ",sal)
show_emp("nikhil")
Output:
employee name: nikhil
salary: 9000
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
Python [BBA (CA) - Sem. V] 2.27 Modules and Packages
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:
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.
Python [BBA (CA) - Sem. V] 2.28 Modules and Packages
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 sub-
subpackages 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.
Check Your Understanding
1. Which of these definitions correctly describes a module?
(a) Denoted by triple quotes for providing the specification of certain program
elements
(b) Design and implementation of specific functionality to be incorporated into a
program
(c) Defines the specification of how it is to be used
(d) Any program that reuses code
2. Which of the following is not an advantage of using modules?
(a) Provides a means of reuse of program code
(b) Provides a means of dividing up tasks
(c) Provides a means of reducing the size of the program
(d) Provides a means of testing individual parts of the program
3. Program code making use of a given module is called a ______ of the module.
(a) Client (b) Docstring
(c) Interface (d) Modularity
4. ______ is a string literal denoted by triple quotes for providing the specifications
of certain program elements.
(a) Interface (b) Modularity
(c) Client (d) Docstring
Python [BBA (CA) - Sem. V] 2.29 Modules and Packages
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?
3. Name any five built-in modules in python.
4. What is the use of math module?
5. Write any three function of Math module.
6. Which module is used in python to find mean and mode?
7. State any five functions of time module.
Python [BBA (CA) - Sem. V] 2.30 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.
• You can also provide the values for the attributes at runtime. This is done by defining
the attributes inside the init method.
• To create instances of a class, you call the class using class name and pass in whatever
arguments its __init__ method accepts.
• Use the __init__() function to assign values to object properties, or other operations
that are necessary to do when the object is being created.
Program 3.1: Create a class named Person, use the __init__() function to assign values
for name and age.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("Omkar", 26)
print(p1.name)
print(p1.age)
Output:
Omkar
26
Step 2 : Inside classes, you can define functions or methods that are part of this
class.
def method1 (self):
print "Nirali Prakashan"
def method2 (self,someString):
print "Software Testing:" + SomeString
o Here we have defined method1 that prints "Nirali Prakashan."
o Another method we have defined is method2 that prints "Software
Testing"+ SomeString. SomeString is the variable supplied by the
calling method
Step 3 : Everything in a class is indented, just like the code in the function, loop, if
statement, etc.
Note: About using "self" in Python
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
Program 3.2: Program for class and object creation.
class myClass():
def method1(self):
print("Nirali prakashan")
def method2(self,someString):
print("Software Testing:" + someString)
def main():
# exercise the class methods
c = myClass ()
Python [BBA (CA) - Sem. V] 3.5 Classes, Objects and Inheritance
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:
Program 3.3: Program for accessing members.
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.
• Syntax:
class ClassName(object):
self.instance_variable = value #value specific to instance
class_variable = value #value shared across all class instances
#accessing instance variable
class_instance = ClassName()
class_instance.instance_variable
#accessing class variable
ClassName.class_variable
• For example, let a computer science student be represented by class CSStudent. The
class may have a static variable whose value is "cse" for all objects. And class may also
have non-static members like name and roll.
• The Python approach is simple, it doesn't require a static keyword. All variables which
are assigned a value in class declaration are class variables. And variables which are
assigned values inside class methods are instance variables.
Program 3.5: Python program to accessing the class variables.
# Class for Computer Science Student
class CSStudent:
stream = 'cse' # Class Variable
def __init__(self,name,roll):
self.name = name # Instance Variable
self.roll = roll # Instance Variable
# Objects of CSStudent class
a = CSStudent('Geek', 1)
b = CSStudent('Nerd', 2)
print(a.stream) # prints "cse"
print(b.stream) # prints "cse"
print(a.name) # prints "Geek"
print(b.name) # prints "Nerd"
print(a.roll) # prints "1"
print(b.roll) # prints "2"
# Class variables can be accessed using class
# name also
print(CSStudent.stream) # prints "cse"
Output:
cse
cse
Geek
Nerd
1
2
cse
Python [BBA (CA) - Sem. V] 3.8 Classes, Objects and Inheritance
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
>>> 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.
Python [BBA (CA) - Sem. V] 3.10 Classes, Objects and Inheritance
Child
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
Enter Name:Omkar
Enter Course Name:Python
Enter Marks:80
Result
Roll Number: 20
Name: Omkar
Course: Python
Total Marks: 80
3.2.2 Multiple Inheritance
• It is possible to inherit from more than one parent class. Such type of inheritance is
called multiple inheritance. In this case all the attributes and methods of both the
parent class will be available in the child class after inheritance. Fig. 3.2 illustrates
multiple inheritance.
A B
• Here A and B are the parent classes and C is the child class. The attributes and
methods of both classes A and B are now available in C after inheritance.
• Similar way, you can derive a class from multiple parent classes as follows.
• Syntax:
class A: # define your class A
.....
class Second(object):
def __init__(self):
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.
Python [BBA (CA) - Sem. V] 3.13 Classes, Objects and Inheritance
studl.getMarks(m)
studl.getSportsMarks(s)
studl.displayStudent()
studl.displayMarks()
studl.displaySportsMarks()
studl.calculateGrade()
Output:
Enter Roll Number:10
Enter Name:Bob
Enter Course Name:MS
Enter Marks:190
Enter Sports marks:200
Result
Roll Number: 10
Name: Bob
Course: MS
Total Marks: 190
Sports Marks: 200
Result: First Class
3.2.3 Multilevel Inheritance
• We can inherit a derived class from another derived class, this process is known as
multilevel inheritance.
Base Class
Derived Class 1
Derived Class 2
# Driver's code
object = Student3()
object.func1()
object.func2()
Output:
This function is in school.
This function is in student 1.
Python [BBA (CA) - Sem. V] 3.16 Classes, Objects and Inheritance
B C D
• The member of one class inside a class can be access using two concepts:
o By Composition(Has-A Relation)
o By Inheritance(Is-A Relation)
IS-A Relationship:
• In object oriented programming, the concept of IS-A is a totally based on Inheritance,
which can be of two types Class Inheritance or Interface Inheritance. It is just like
saying "A is a B type of thing". For example, Apple is a Fruit, Car is a Vehicle etc.
Inheritance is unidirectional. For example, House is a Building. But Building is not a
House.
HAS-A Relationship:
• Composition (HAS-A) simply mean the use of instance variables that are references to
other objects. For example, Maruti has Engine, or House has Bathroom.
class college:
# college specific functionality
'''
'''
'''
class Teacher:
ob = college()
ob.method1()
ob.method2()
'''
'''
• In above example, class Teacher HAS-A College class reference. Here inside class
Teacher also we can create different variables and methods. Using object reference of
College class inside Teacher class we can easily access each and every member of
College class inside Teacher class.
• IS-A relationship based on Inheritance, which can be of two types Class Inheritance or
Interface Inheritance.
• Has-a relationship is composition relationship which is a productive way of code
reuse.
Program 3.13: Accessing the members of the class using instance of the class inside
another class.
class Employee:
# constructor for initialization
def __init__(self, name, age):
self.name = name
self.age = age
# instance method
Python [BBA (CA) - Sem. V] 3.18 Classes, Objects and Inheritance
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
# creating object of Employee class
self.emp_obj = emp_obj
# instance method
def display(self):
# calling Employee class emp_data()
# method
self.emp_obj.emp_data()
print('Address of Employee : ', self.address)
print('Salary of Employee : ', self.salary)
# creating Employee class object
emp = Employee('Ronil', 20)
# passing obj. of Emp. class during creation
# of Data class object
data = Data('Indore', 25000, emp)
# call Data class instance method
data.display()
Output:
Name of Employee : Ram
Age of Employee : 20
Address of Employee : Pune
Salary of Employee : 50000
• 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.
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")
Python [BBA (CA) - Sem. V] 3.19 Classes, Objects and Inheritance
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.
ans=" "
ans1=" "
class String1:
def get_string(self):
self.s=raw_input("enter a string")
Python [BBA (CA) - Sem. V] 3.20 Classes, Objects and Inheritance
def print_string(self):
print(self.s.upper())
print(self.s[::-1])
s= String1()
s.get_string()
s.print_string()
Output:
enter a string saranga sharad kulkarni
SARANGA SHARAD KULKARNI
inrakluk darahs agnaras
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.21 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)
Python [BBA (CA) - Sem. V] 3.22 Classes, Objects and Inheritance
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=[]
for i in range(0,n):
x=raw_input("enter object:")
s.append(x)
print(s)
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
Python [BBA (CA) - Sem. V] 3.23 Classes, Objects and Inheritance
Enter marks 56
Enter marks 67
Enter marks 78
('Roll NO:', 15)
('Name:', 'abhi')
('Subject marks:', [56, 67, 78])
('Percentage: ', 67, '%')
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)
Python [BBA (CA) - Sem. V] 3.24 Classes, Objects and Inheritance
Summary
Python is an object oriented programming language.
A class is a code template for creating objects. Objects have member variables and
have behaviour associated with them. In python a class is created by the keyword
class.
An object is also called an instance of a class and the process of creating this
object is called instantiation
The __init__() function is called automatically every time the class is being used to
create a new object.
Inheritance, in object-oriented programming, is the ability of a class to inherit
members of another class as part of its own definition. The inheriting class is
called a subclass (also "derived class" or "child class"), and the class inherited from
is called the superclass (also "base class" or "parent class").
We can inherit a derived class from another derived class, this process is known
as multilevel inheritance.
When a derived class inherits only from syntax, the base class is called single
inheritance. If it has one base class and one derived class it is called single
inheritance.
Multi-Level inheritance is possible in python like other object-oriented languages.
Multi-level inheritance is archived when a derived class inherits another derived
class. There is no limit on the number of levels up to which, the multi-level
inheritance is archived in python.
Multiple inheritance is the concept where a subclass inherits properties from
multiple base classes. If it has two base classes and one derived class it is called
multilevel inheritance.
Python [BBA (CA) - Sem. V] 3.25 Classes, Objects and Inheritance
The issubclass(sub, sup) method is used to check the relationships between the
specified classes. It returns true if the first class is the subclass of the second
class, and false otherwise.
The isinstance() method is used to check the relationship between the objects and
classes. It returns true if the first parameter, i.e., obj is the instance of the second
parameter, i.e., class.
Check Your Understanding
Q.I Multiple Choice Questions.
1. Which of the following keywords mark the beginning of the class definition?
(a) def (b) return
(c) class (d) cls.
2. Which Of The Following Is Required To Create A New Instance Of The Class?
(a) constructor (b) A class
(c) A value-returning method (d) A destructor
3. Which of the following statements can be used to check, whether an object "obj" is
an instance of class a or not?
(a) obj.isinstance(A) (b) A.isinstance(obj)
(c) isinstance(obj, A) (d) isinstance(A, obj)
4. Without which argument static methods are defined?
(a) Def (b) Cls
(c) init (d) Self
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
Python [BBA (CA) - Sem. V] 3.26 Classes, Objects and Inheritance
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
(b) Determines the class identifiers of any value
(c) Determines class description of any built-in type
(d) Determines class description of any user-defined built-in type
16. What will be the output of the following Python code?
class A:
def one(self):
return self.two()
Python [BBA (CA) - Sem. V] 3.28 Classes, Objects and Inheritance
def two(self):
return 'A'
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
(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
Python [BBA (CA) - Sem. V] 3.29 Classes, Objects and Inheritance
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.
• 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.
FloatingPointError Raised when a floating point calculation fails.
ImportError Raised when an import statement fails.
IndexError Raised when an index is not found in a sequence.
contd. …
Python [BBA (CA) - Sem. V] 4.3 Exception Handling
• 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:
If there is Exception2, then execute this block.
......................
else:
If there is no exception then execute this block.
Program 4.1: For try-except-else statement.
n=10
m=0
try:
n/m
except ZeroDivisionError:
print("Divide by zero error")
else:
print (n/m)
Output:
Divide by zero error
• This kind of a try-except statement catches all the exceptions that occur. Using this
kind of try-except statement is not considered a good programming practice though,
because it catches all exceptions but does not make the programmer identify the root
cause of the problem that may occur.
Program 4.2: For try-except statement with no exception.
try:
a=10/0;
except:
print "Arithmetic Exception"
else:
print "Successfully Done"
Output:
Arithmetic Exception
Program 4.3: For try-except statement with no exception.
while True:
try:
a=int(input("Enter an integer: "))
div=10/a
break
except:
print("Error Occurred")
print("Please enter valid value")
print()
print("Division is: ",div)
Output:
Enter an integer: b
Error Occurred
Please enter valid value
Enter an integer: 2.5
Error Occurred
Please enter valid value
Enter an integer: 0
Error Occurred
Please enter valid value
Enter an integer: 5
Division is: 2.0
Python [BBA (CA) - Sem. V] 4.7 Exception Handling
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
try:
fh.write("This is my test file for exception handling!!")
finally:
print ("Going to close the file")
fh.close()
except IOError:
print ("Error: can\'t find file or read data")
• This produces the following result:
Going to close the file:
• When an exception is thrown in the try block, the execution immediately passes to
the finally block. After all the statements in the finally block are executed, the
exception is raised again and is handled in the except statements if present in the
next higher layer of the try-except statement.
• Points to be noted:
o Assertions are the condition or boolean expression which are always supposed to
be true in the code.
o Assert statement takes an expression and optional message.
o Assert statement is used to check types, values of argument and the output of the
function.
o Assert statement is used as debugging tool as it halts the program at the point
where an error occurs.
• In Python, we can use assert statement in two ways as mentioned above.
1. Assert statement has a condition and if the condition is not satisfied the program
will stop and give AssertionError.
2. Assert statement can also have a condition and optional error message. If the
condition is not satisfied assert stops the program and gives AssertionError along
with the error message.
Previous code
mark2 = [55,88,78,90,79]
print("Average of mark2:",avg(mark2))
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!
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"))
Python [BBA (CA) - Sem. V] 4.13 Exception Handling
Output:
bash-4.1$ python brackets.py
Enter the brackets(){}{}
Valid Brackets
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
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
Program 4.14: 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
# __str__ is to print() the value
def __str__(self):
return(repr(self.value))
try:
raise(MyError(3*2))
# Value of Exception is stored in error
except MyError as error:
print('A New Exception occured: ',error.value)
Output:
A New Exception occured: 6
>>>
Python [BBA (CA) - Sem. V] 4.16 Exception Handling
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.
Check Your Understanding
Q.I Multiple Choice Questions:
1. When will the else part of try-except-else be executed?
(a) Always (b) When an exception occurs
(c) When no exception occurs (d) When an execution occurs into except
block
2. Which statement is true for Python exception?
(a) You cannot create custom exception.
(b) You can create a user defined exception deriving a class from error class
(c) You can create a user defined exception deriving a class from Exception class.
(d) None of the above.
3. Which exception Raised in case of failure of the Assert statement.
(a) indexError (b) AssertionError
(c) AbsoluteError (d) keyError
Python [BBA (CA) - Sem. V] 4.17 Exception Handling
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
o Python with tkinter is the fastest and easiest way to create the GUI
applications. Creating a GUI using tkinter is an easy task. We will discuss this
point in detailed in the same unit.
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)
Python [BBA (CA) - Sem. V] 5.3 GUI Programming
w.setWindowTitle("PyQt")
w.show()
sys.exit(app.exec_())
if __name__ =='__main__':
window()
o The above code produces the following output:
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.
Python [BBA (CA) - Sem. V] 5.4 GUI Programming
Initialize the
Import Tkinter Rename the Define the
Window
Module GUI Window Label Widget
Manager
Geometry
Mainloop Management
Method Using Pack
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.
Program 5.1: Program for Tkinter.
import tkinter
top = tkinter.Tk()
# Code to add widgets will go here...
top.mainloop()
Output:
Making Widgets:
• When widgets are constructed in Tkinter, we can specify how they should be
configured.
• The GUI script passes two arguments to the Label class constructor:
(refer Program 5.2).
1. The first is a parent-widget object, which we want the new label to be attached to.
Here, None means "attach the new Label to the default top-level window of this
program." Later, we’ll pass real widgets in this position to attach our labels to
other container objects.
2. The second is a configuration option for the Label, passed as a keyword argument:
the text option specifies a text string to appear as the label’s message. Most widget
constructors accept multiple keyword arguments for specifying a variety of
options (color, size, callback handlers, and so on). Most widget configuration
options have reasonable defaults per platform, though, and this accounts for
much of Tkinter’s simplicity.
3. In example 5.3, The Tkinter mainloop can be called with or without a widget (i.e.,
as a function or method). We didn’t pass Label a parent argument in this version,
either: it simply defaults to None when omitted.
Example 5.3: Program without a widget.
from tkinter import *
Label(text='Hello GUI world!').pack()
mainloop()
Output:
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.4: Program for Resizing window.
from tkinter import *
Label(text='Hello GUI world!').pack(expand=YES, fill=BOTH)
mainloop()
Python [BBA (CA) - Sem. V] 5.10 GUI Programming
Output:
5.4 FRAME
• Frame is used as containers in the Tkinter for grouping and adequately organizing
the widgets.
• Syntax:
frame_widget = tk.Frame(widget, option=placeholder)
Python [BBA (CA) - Sem. V] 5.11 GUI Programming
Where, widget is the parameter for the parent window/frame while option is a
placeholder that can have various values like border-width, height and width of
widget, highlightcolor (color when widget has to be focused).
• To arrange the layout in the window, you will use a Frame widget class. Let's create a
simple program to see how the Frame works.
• We will define two frames - top and bottom with the help of the pack class.
• The Frame class will help in creating a division between the window. Basically, a
single-window will be replicated twice as top and bottom in the form of a Frame.
• Following are the various options used with Tkinter frame widgets:
Table 5.1: Frame Widget Options
Option Description
bg The normal background color displayed behind the label and
indicator.
bd The size of the border around the indicator. Default is 2 pixels.
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.
height The vertical dimension of the new frame.
highlightbackground Color of the focus highlight when the frame does not have
focus.
highlightcolor Color shown in the focus highlight when the frame has the
focus.
highlightthickness Thickness of the focus highlight.
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
width The default width of a checkbutton is determined by the size
of the displayed image or text. You can set this option to a
number of characters and the checkbutton will always have
room for that many characters.
Program 5.6: Diplay the massage after clicking on the button.
importtkinterastk
classApplication(tk.Frame):
def__init__(self,master=None):
super().__init__(master)
self.master=master
self.pack()
self.create_widgets()
Python [BBA (CA) - Sem. V] 5.12 GUI Programming
defcreate_widgets(self):
self.hi_there=tk.Button(self)
self.hi_there["text"]="Hello World\n(click me)"
self.hi_there["command"]=self.say_hi
self.hi_there.pack(side="top")
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)
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.5 BUTTON
• Button widget has a property for switching on/off. When a user clicks the button, an
event is triggered in the Tkinter.
• Syntax: button_widget = tk.Button(widget, option=placeholder)
• Where, Widget is the argument for the parent window/frame while option is a
placeholder that can have various values like foreground and background color, font,
command (for function call), image, height, and width of button.
Python [BBA (CA) - Sem. V] 5.13 GUI Programming
• Button Widget Options: Following are the various options used with Tkinter button
widgets:
Table 5.2: Button Widget Options
Option name Description
activebackground This option indicates the background of the button at the
time when the mouse hovers the button.
bd This option is used to represent the width of the border in
pixels.
bg This option is used to represent the background color of the
button.
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.
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.
Python [BBA (CA) - Sem. V] 5.14 GUI Programming
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",
}
Program 5.8: Python application to create a simple button.
from tkinter import *
top = Tk()
top.geometry("200x100")
b = Button(top, text="Simple")
b.pack()
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")
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
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()
Python [BBA (CA) - Sem. V] 5.17 GUI Programming
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")
2. label=tk.Label(text="Hello, Tkinter",fg="white",bg="black")
Label Widget Options:
• Following are the various options used with Tkinter label widgets:
Table 5.3: Label Widget Options
Option Description
anchor This options controls where the text is positioned if the widget has
more space than the text needs. The default is anchor=CENTER, which
centers the text in the available space.
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.
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.
Python [BBA (CA) - Sem. V] 5.19 GUI Programming
def middle_click(event):
tkinter.Label(window, text = "Middle Click!").pack()
def right_click(event):
tkinter.Label(window, text = "Right Click!").pack()
Python [BBA (CA) - Sem. V] 5.20 GUI Programming
window.bind("<Button-1>", left_click)
window.bind("<Button-2>", middle_click)
window.bind("<Button-3>", right_click)
window.mainloop()
Output:
def middle_click(event):
tkinter.Label(window, text = "Middle Click!").pack()
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()
Python [BBA (CA) - Sem. V] 5.21 GUI Programming
Output:
When we pressed on Button 1, the msg "Left Clicked" is displayed.
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:
>>>label.pack()
>>>entry.pack()
Python [BBA (CA) - Sem. V] 5.23 GUI Programming
• 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)
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 ")
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.17: Program for entry widget.
from tkinter import *
top = Tk()
L1 = Label(top, text="User Name")
L1.pack( side = LEFT)
E1 = Entry(top, bd =5)
E1.pack(side = RIGHT)
top.mainloop()
Output:
Here, we can type any text in the input box, say "python 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.
Program 5.20: Program for multiple windows.
import sys
from tkinter import Toplevel, Button, Label
win1 = Toplevel() # two independent windows
win2 = Toplevel() # but part of same process
Button(win1, text='top', command=sys.exit).pack()
Button(win2, text='right', command=sys.exit).pack()
Label(text='left').pack() # on default Tk() root window
win1.mainloop()
Output:
# 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)
# Let's now define the required functions for the Calculator to function
properly.
Python [BBA (CA) - Sem. V] 5.28 GUI Programming
# 2. Second is the button clear 'btn_clear' function clears the input field
or
# previous calculations using the button "C"
def btn_clear():
global expression
expression = ""
input_text.set("")
# 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:
Python [BBA (CA) - Sem. V] 5.30 GUI Programming
# 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()
Output:
Practice Questions
Q.I Answer the following question in short.
1. Name the different tools Python provides for developing graphical user interfaces
(GUIs).
2. Name the free GUI libraries for Python.
3. What is the purpose of tkinker?
4. Name the different widgets available in Tkinter.
5. List out Geometry Management methods.
Python [BBA (CA) - Sem. V] 5.32 GUI Programming
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.
• 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.
• 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.
Python [BBA (CA) - Sem. V] 6.3 Python Libraries
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 Mat-
plotlib (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.
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
Lists. scientific computing in Python.
Definition A list is the Python equivalent of A NumPy array is a grid of values,
an array, but is resizeable and can all of the same type, and is
contain elements of different indexed by a tuple of nonnegative
types. integers.
Memory Pythons list requires more NumPy arrays requires smaller
memory. memory consumption and have
better runtime behavior.
Speed Python list operation takes more NumPy is faster and more
time and less convenient. convenient than a list.
Slicing Slices of python lists are shallow All arrays generated by NumPy
copies. 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 system-
prototyping 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:
Python [BBA (CA) - Sem. V] 6.5 Python Libraries
Table 6.2
Scipy Packages Package Domain
scipy.cluster Vector quantization / Kmeans.
scipy.constants Physical and mathematical constants.
scipy.fftpack Fourier transform.
scipy.integrate Integration routines.
scipy.interpolate Interpolation.
scipy.io Data input and output.
scipy.linalg Linear algebra routines.
scipy.ndimage n-dimensional image package.
scipy.odr Orthogonal distance regression.
scipy.optimize Optimization.
scipy.signal Signal processing.
scipy.sparse Sparse matrices.
scipy.spatial Spatial data structures and algorithms.
scipy.special Any special mathematical functions.
scipy.stats Statistics.
• The basic data structure used by SciPy is a multidimensional array provided by the
NumPy module. NumPy provides some functions for Linear Algebra, Fourier
Transforms and Random Number Generation, but not with the generality of the
equivalent functions in SciPy.
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 [BBA (CA) - Sem. V] 6.6 Python Libraries
• 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.
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 split-
apply-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 high-
dimensional 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.
Python [BBA (CA) - Sem. V] 6.7 Python Libraries
6.1.5 StatsModels
• StatsModels is built on top of NumPy, SciPy, and matplotlib, but it contains more
advanced functions for statistical testing and modelling.
• It is used to explore data, perform statistical tests and estimate statistical models.
• It includes regression models and linear models such as Linear regression,
Generalized Linear Models (GLMs) and Generalized Estimating Equations (GEE) to
perform all statistical operations.
• 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.
Python [BBA (CA) - Sem. V] 6.9 Python Libraries
• 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.
• 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.
Program 6.1: Program for plotting histogram.
import matplotlib.pyplot as plt
# frequencies
ages = [2,5,70,40,30,45,50,45,43,40,44,60,7,13,57,18,90,77,32,21,20,40]
Python [BBA (CA) - Sem. V] 6.10 Python Libraries
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.
Python [BBA (CA) - Sem. V] 6.12 Python Libraries
• 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.
Program 6.3: Program for plotting the line chart
importplotly.express as px
# using the iris dataset
df =px.data.iris()
# plotting the line chart
fig =px.line(df, x="species", y="petal_width")
# showing the plot
fig.show()
Output:
6.3.1 Scikit-Learn
• There are several Python libraries which provide solid implementations of a range of
machine learning algorithms. One of the best known is Scikit-Learn, a package that
provides efficient versions of a large number of common algorithms.
• Scikit-Learn is characterized by a clean, uniform, and streamlined API, as well as
useful and complete online documentation. A benefit of this is uniformity that once
you understand the basic use and syntax of Scikit-Learn for one type of model,
switching to a new model or algorithm is very straightforward.
• Scikit-Learn was initially developed by David Cournapeau as a Google summer of code
project in 2007. Later Matthieu Brucher joined the project and started to use it as a
part of his thesis work. In 2010, INRIA got involved and the first public release
(v0.1 beta) was published in late January 2010. The project now has more than 30
active contributors and has had paid sponsorship from INRIA, Google, Tinyclues and
the Python Software Foundation.
What is Scikit-Learn?
• Scikit-learn is pronounced as sy-kit learn, sci stands for science.
• Scikit-learn provides a range of supervised and unsupervised learning algorithms via
a consistent interface in Python.
• Scikit-learn is probably the most useful library for machine learning in Python. It is
on NumPy, SciPy and Matplotlib, this library contains a lot of efficient tools for
machine learning and statistical modeling including classification, regression,
clustering and dimensionality reduction. It is used for building the model and should
not be used for reading the data, manipulating and summarizing it.
• 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.
Python [BBA (CA) - Sem. V] 6.14 Python Libraries
ML Model
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.
• In keras, there is usually very less frequent need to debug simple networks. But in
case of Tensorflow, it is quite difficult to perform debugging. Pytorch on the other
hand has better debugging capabilities as compared to the other two.
• Keras has a simple architecture. It is more readable and concise. Tensorflow on the
other hand is not very easy to use even though it provides Keras as a framework that
makes work easier. PyTorch has a complex architecture and the readability is less
when compared to Keras.
• Keras is usually used for small datasets as it is comparatively slower. On the other
hand, TensorFlow and PyTorch are used for high performance models and large
datasets that require fast execution.
• With the increasing demand in the field of Data Science, there has been an enormous
growth of Deep learning technology in the industry. With this, all the three
frameworks have gained quite a lot of popularity. Keras tops the list followed by
TensorFlow and PyTorch. It has gained immense popularity due to its simplicity when
compared to the other two.
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.
6.5.2 SpaCy
• 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.
Python [BBA (CA) - Sem. V] 6.21 Python Libraries
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')
# Set the y axis label of the current axis.
plt.ylabel('y - axis')
# Set a title
plt.title('Draw a line.')
# Display the figure.
plt.show()
Output:
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')
Python [BBA (CA) - Sem. V] 6.23 Python Libraries
# 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()
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()
:
Python [BBA (CA) - Sem. V] 6.24 Python Libraries
Output:
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.25 Python Libraries
Output:
Program 6.9: Write a Python program to create bar plot from a DataFrame.
Sample Data Frame:
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]
Python [BBA (CA) - Sem. V] 6.27 Python Libraries
marks_range =[10,20,30,40,50,60,70,80,90,100]
plt.scatter(marks_range, math_marks, label='Math marks', color='r')
plt.scatter(marks_range, science_marks, label='Science marks', color='g')
plt.title('Scatter Plot')
plt.xlabel('Marks Range')
plt.ylabel('Marks Scored')
plt.legend()
plt.show()
Sample Output:
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