0% found this document useful (0 votes)
4 views201 pages

Python Programming Guide for BCA

The document is a comprehensive guide to programming in Python, covering various topics such as Python basics, control structures, data types, functions, object-oriented programming, and more. It includes detailed sections on file handling, exception handling, sorting and searching algorithms, and network programming. Additionally, it provides insights into GUI programming and database interactions using MySQL, making it a valuable resource for learners and practitioners of Python.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views201 pages

Python Programming Guide for BCA

The document is a comprehensive guide to programming in Python, covering various topics such as Python basics, control structures, data types, functions, object-oriented programming, and more. It includes detailed sections on file handling, exception handling, sorting and searching algorithms, and network programming. Additionally, it provides insights into GUI programming and database interactions using MySQL, making it a valuable resource for learners and practitioners of Python.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

[CS-33] Programming in Python

Paper Code: CS-33 (BCA)

Prepared by:
ANIL MAKWANA
Lt. M. J. Kundaliya Arts & Commerce Mahila College, Rashtriya Shala Campus, Rajkot
[CS-33] Programming in Python

Programming in Python
Programming in Python ............................................................................................................... 2
1. Python Introduction................................................................................................................. 9
1.0. The basic elements of python .............................................................................................. 14
1.1 Branching programs orPython Control Structures orConditionals.......................................... 15
1.3 Strings and Input .................................................................................................................. 16
1.3.0 String ....................................................................................................................................... 16
1.3.1 String Formatting .................................................................................................................... 16
1.3.2 Common String Operators ...................................................................................................... 16
1.3.3 Common String Methods ........................................................................................................ 16
1.3.4 Numbers .................................................................................................................................. 17
1.3.5 Common Number Functions ................................................................................................... 17
1.4 Iteration .............................................................................................................................. 17
1.4.0 The For Loop .......................................................................................................................... 18
1.5. Functions and Functions as Objects ..................................................................................... 18
1.5.0 Function .................................................................................................................................. 18
1.5.1 Variable Scope ........................................................................................................................ 19
1.5.2 Function Specification ............................................................................................................ 21
1.5.3 Function Recursion ............................................................................................................ 22
1.6 Global variables ................................................................................................................... 25
1.6 Modules .......................................................................................................................... 25
1.6.0 What is a Module? .................................................................................................................. 25
1.6.1 Create a Module................................................................................................................. 25
1.6.2 Use a Module ..................................................................................................................... 25
[Link] Files ......................................................................................................................... 25
1.8.0 File Handling .......................................................................................................................... 25
1.8.1 Open a File on the Server........................................................................................................ 26
1.8.2 Read Only Parts of the File ..................................................................................................... 26
1.8.3 Write to an Existing File ......................................................................................................... 26
1.8.4 Create a New File.................................................................................................................... 27
1.8.5 Delete a File ............................................................................................................................ 27
1.8.6 Check if File exist: .................................................................................................................. 27
1.8.7 Delete Folder ........................................................................................................................... 27
1.9 Tuples .................................................................................................................................. 27
1.9.0 Change Tuple Values .............................................................................................................. 28
1.9.1 Python Tuple Methods ............................................................................................................ 28

Page 2 of 201
[CS-33] Programming in Python

1.10 Lists and Mutability ......................................................................................................... 28


1.10.0 Lists ....................................................................................................................................... 28
1.10.1 Common List Functions........................................................................................................ 29
1.10.2 Common List Methods ......................................................................................................... 29
1.10.3 List Comprehensions ............................................................................................................ 29
1.11 Dictionaries ....................................................................................................................... 30
1.11.0 Introduction ........................................................................................................................... 30
1.11.1 Change Values ...................................................................................................................... 30
1.11.2 Loop through a Dictionary .................................................................................................... 30
1.11.3 Python Dictionary Methods .................................................................................................. 30
1.11.4 Common Dictionary Functions ............................................................................................. 31
1.11.5 Accessing Values in Dictionary ............................................................................................ 31
1.11.6 Updating Dictionary.............................................................................................................. 31
1.11.7 Delete Dictionary Elements .................................................................................................. 31
1.12 Hash Table ......................................................................................................................... 32
2.0 Python - Exceptions Handling ............................................................................................... 33
2.0.0 What is Exception? ................................................................................................................. 33
2.0.1 Handling an exception ............................................................................................................ 33
2.0.2 try...finally............................................................................................................................... 34
2.0.3 Python finally Block ............................................................................................................... 34
2.1 Exceptions as a control flow mechanism: ............................................................................. 35
2.1.0 Python try except Block .......................................................................................................... 35
2.1.1 Multiple Exception Block ....................................................................................................... 35
2.1.2 Python Standard Exceptions ................................................................................................... 36
2.3 Abstract Data Types ............................................................................................................. 36
2.3.0 List ADT ................................................................................................................................. 37
2.3.1 Stack ADT .............................................................................................................................. 37
2.3.2 Queue ADT ............................................................................................................................. 38
2.4 Assertion ............................................................................................................................. 38
2.4.0 Assert Keyword in Python ...................................................................................................... 38
2.4.1 Flowchart of Python Assert Statement ................................................................................... 39
2.4.2 Python assert keyword Syntax ................................................................................................ 39
2.4.3 Python assert keyword without error message........................................................................ 39
2.4.4 Python assert keyword with an error message ........................................................................ 40
2.4.5 Assert Inside a Function.......................................................................................................... 40
2.4.6 Assert with boolean Condition................................................................................................ 41
2.4.7 Assert Type of Variable in Python.......................................................................................... 41

Page 3 of 201
[CS-33] Programming in Python

2.4.8 Asserting dictionary values ..................................................................................................... 42


2.4.9 Why Use Python Assert Statement? ....................................................................................... 42
2.5 Python Classes and Objects .................................................................................................. 43
2.5.0 Introduction to OOPs in Python .............................................................................................. 43
2.5.1 What are OOPS Concepts in Python? ..................................................................................... 43
2.5.2 Class and Objects in Python ................................................................................................... 44
2.5.3 How to Define a Class in Python? .......................................................................................... 46
2.5.4 What is an _init_ Method? Or Constructors in Python ........................................................... 47
1. Class Attribute: ................................................................................................................................. 47
2. Instance Attribute: ........................................................................................................................... 48
2.5.5 Creating an Object in Class..................................................................................................... 48
2.5.6 Instance Methods .................................................................................................................... 50
2.5.7 Fundamentals of OOPS in Python .......................................................................................... 51
[Link] Inheritance ............................................................................................................................... 51
[Link] Polymorphism .......................................................................................................................... 53
[Link] Encapsulation ........................................................................................................................... 55
2.5.8 Getters and Setters .................................................................................................................. 56
[Link] Code of getter & setter in Encapsulation ................................................................................ 56
[Link] Access Modifiers ...................................................................................................................... 56
2.5.9 Abstraction .............................................................................................................................. 58
[Link] Key Points of Abstract Classes ................................................................................................. 58
[Link] Syntax of Abstract Class in Python ........................................................................................... 58
2.5.10 Advantages of OOPS in Python ............................................................................................ 59
2.5.11 Important ............................................................................................................................... 60
2.6 Python - Sorting Algorithms ................................................................................................. 60
2.6.0 Bubble Sort ............................................................................................................................. 60
2.6.1 Merge Sort .............................................................................................................................. 61
2.6.2 Selection Sort .......................................................................................................................... 63
2.6.3 Insertion Sort:.......................................................................................................................... 63
2.6.4 Quick Sort ............................................................................................................................... 64
2.6.5 Shell Sort................................................................................................................................. 66
2.7 Searching Algorithms ........................................................................................................... 67
2.7.0 Linear Search .......................................................................................................................... 67
2.7.1 Interpolation Search ................................................................................................................ 67
3.0 Plotting Using PyLab ............................................................................................................ 69
3.0.0 PyLab Module in Python ........................................................................................................ 69

Page 4 of 201
[CS-33] Programming in Python

3.0.1 PyLab Module: Introduction ................................................................................................... 69


3.0.2 PyLab Module: Installation..................................................................................................... 69
3.0.3 Pylab: What Is It, and Should I Use It? .................................................................................. 70
3.0.4 Basic Plotting ..................................................................................................................... 71
3.0.5 Matplotlib - Object-oriented Interface .................................................................................... 73
3.0.6 Matplotlib - Figure Class ........................................................................................................ 74
3.0.7 Matplotlib - Axes Class .......................................................................................................... 75
[Link] Parameter .......................................................................................................................... 75
[Link] Legend ...................................................................................................................................... 75
[Link] [Link]() .......................................................................................................................... 76
[Link] Color codes .............................................................................................................................. 76
[Link] Marker codes .......................................................................................................................... 76
[Link] Line styles ................................................................................................................................. 76
3.0.8 Matplotlib - Multiplots............................................................................................................ 78
3.0.9 Matplotlib - Subplots() Function ............................................................................................ 80
3.0.10 Matplotlib - Subplot2grid() Function ................................................................................ 81
3.0.11 Matplotlib - Grids ................................................................................................................. 82
3.0.12 Matplotlib - Formatting Axes ............................................................................................... 83
3.0.13 Matplotlib - Setting Limits.................................................................................................... 85
3.0.14 Matplotlib - Setting Ticks and Tick Labels .......................................................................... 86
3.0.15 Matplotlib - Twin Axes......................................................................................................... 87
3.0.16 Matplotlib - Bar Plot ............................................................................................................. 88
3.0.17 Matplotlib - Histogram ......................................................................................................... 91
3.0.18 Matplotlib - Pie Chart ........................................................................................................... 92
3.0.19 Matplotlib - Scatter Plot ........................................................................................................ 93
3.0.20 Matplotlib - Contour Plot ...................................................................................................... 94
3.0.21 Matplotlib - Quiver Plot ........................................................................................................ 95
3.0.22 Matplotlib - Box Plot ............................................................................................................ 96
3.0.23 Matplotlib - Violin Plot......................................................................................................... 97
3.0.24 Matplotlib - Three-dimensional Plotting .............................................................................. 98
3.0.25 Matplotlib - 3D Contour Plot .............................................................................................. 100
3.0.26 Matplotlib - 3D Wireframe plot .......................................................................................... 101
3.0.27 Matplotlib - 3D Surface plot ............................................................................................... 102
3.0.28 Matplotlib - Working With Text ......................................................................................... 103
3.0.29 Matplotlib - Mathematical Expressions .............................................................................. 104
3.0.30 Matplotlib - Working with Images ..................................................................................... 105

Page 5 of 201
[CS-33] Programming in Python

3.0.31 Matplotlib - Transforms ...................................................................................................... 106


3.1 Plotting Mortgages, an Extended Example ..................................................................... 108
3.2 Fibonacci Sequences, Revisited: ......................................................................................... 110
3.3 Dynamic Programming and the 0/1 Knapsack Problem: ...................................................... 111
3.3.0 What is Knapsack? ................................................................................................................ 111
3.4 Dynamic Programming and Divide-and-Conquer: ............................................................... 113
3.4.0 Divide-and-conquer ......................................................................................................... 113
3.4.1. What is Dynamic Programming? ......................................................................................... 115
[Link] Basic Concepts: ................................................................................................................ 117
3.4.2 Advanced Concepts: ............................................................................................................. 126
[Link] Bitmasking and Dynamic Programming | Set 1 ..................................................................... 126
[Link] Bitmasking and Dynamic Programming | Set-2 (TSP) ........................................................... 128
[Link] Digit DP | Introduction........................................................................................................... 133
[Link] Sum over Subsets | Dynamic Programming .......................................................................... 134
4.0 Network Programming: ...................................................................................................... 138
4.0.1 What Is a Protocol? ............................................................................................................... 139
4.0.2 Python - Sockets Programming ............................................................................................ 139
[Link] The socket Module ................................................................................................................. 140
[Link] Server Socket Methods .......................................................................................................... 140
[Link] Client Socket Methods ........................................................................................................... 140
[Link] General Socket Methods ....................................................................................................... 140
[Link] A Simple Server ...................................................................................................................... 141
[Link] A Simple Client ....................................................................................................................... 141
[Link] Socket with Public URL........................................................................................................... 142
4.0.3 Knowing IP Address ............................................................................................................. 142
4.0.4 URL ................................................................................................................................. 143
4.0.5 Reading the Source Code of a Web Page: ............................................................................ 144
4.0.6 Reading the HTML file:........................................................................................................ 147
4.0.7 Downloading a Web Page from Internet: ........................................................................ 147
4.0.8 Downloading an Image from Internet: .................................................................................. 148
4.0.9 A TCP/IP Server, A TCP/IP Client: ..................................................................................... 149
4.0.10 A UDP Server, A UDP Client: ........................................................................................... 152
4.0.11 File Server, File Client ........................................................................................................ 154
4.0.12 Two Way Communication between server and client: ....................................................... 156
4.0.13 Send simple email using python ......................................................................................... 157

Page 6 of 201
[CS-33] Programming in Python

4.1 GUI Programming .............................................................................................................. 158


4.1.0 Event-driven programming paradigm: .................................................................................. 159
[Link] Python Module – Asyncio ...................................................................................................... 159
4.1.1 Creating simple GUI ............................................................................................................. 160
[Link] Python Tkinter Module .......................................................................................................... 163
[Link] Tkinter Widgets ...................................................................................................................... 164
5.0 Installing MySQL Connector Package in Python .................................................................. 196
5.1 Verifying the MySQL dB Interface Installation: ................................................................... 196
5.2 Working with MySQL Database ..................................................................................... 196
5.2.0 Creating a Database .............................................................................................................. 197
5.2.1 Creating a Table .................................................................................................................... 197
5.2.2 Retrieving All Rows from a Table in python........................................................................ 197
5.2.3 Inserting Rows into a Table .................................................................................................. 198
5.2.4 Updating Rows in a Table..................................................................................................... 199
5.2.5 Deleting Rows from a Table ................................................................................................. 200
5.2.6 Delete a Table Example ........................................................................................................ 201

Page 7 of 201
CS-33: Programming in Python ch-1 Introduction to Python

Most Popular Coding Language worldwide in 2023

MJKACC MJKACC

Page 8 of 201
CS-33: Programming in Python ch-1 Introduction to Python

Job in Big Data space

1. Python Introduction
 Python is a widely used general-purpose, high level programming language. It was created by
Guido van Rossum in 1991 and further developed by the Python Software Foundation.
 It was designed with an emphasis on code readability, and its syntax allows programmers to
express their concepts in fewer lines of code.
 Python is a programming language that lets you work quickly and integrate systems more
efficiently.
 There are two major Python versions: Python 2 and Python 3. Both are quite different.
Finding an Interpreter:
 Before start Python programming, we need to have an interpreter to interpret and run our
programs. There are certain online interpreters like [Link] that can be
used to run Python programs without installing an interpreter.
MJKACC

 Windows: There are many interpreters available freely to run Python scripts like IDLE
(Integrated Development Environment) that comes bundled with the Python software
downloaded from [Link]
 Linux: Python comes preinstalled with popular Linux distros such as Ubuntu and Fedora. To
check which version of Python you’re running, type “python” in the terminal emulator. The
interpreter should start and print the version number.
 macOS: Generally, Python 2.7 comes bundled with macOS. You’ll have to manually install
Python 3 from [Link]
Reason for increasing popularity
 Emphasis on code readability, shorter codes, ease of writing
 Programmers can express logical concepts in fewer lines of code in comparison to languages
such as C++ or Java.
 Python supports multiple programming paradigms, like object-oriented, imperative and
functional programming or procedural.
 There exists inbuilt functions for almost all of the frequently used concepts.
 Philosophy is “Simplicity is the best”.

What is Scripting Language?


 A scripting language is a “wrapper” language that integrates OS functions.
 The interpreter is a layer of software logic between your code and the computer hardware on
your machine.
Wiki Says:
 The “program” has an executable form that the computer can use directly to execute the
instructions.

Page 9 of 201
CS-33: Programming in Python ch-1 Introduction to Python

 The same program in its human-readable source code form, from which executable programs
are derived (e.g., compiled)
 Python is scripting language, fast and dynamic.
 Python is called ‘scripting language’ because of it’s scalable interpreter.
What is Python?
 Python is a high-level programming language which is:
 Interpreted: Python is processed at runtime by the interpreter. (Next Slide)
 Interactive: You can use a Python prompt and interact with the interpreter directly to write
your programs.
 Object-Oriented: Python supports Object-Oriented technique of programming.
 Beginner’s Language: Python is a great language for the beginner-level programmers and
supports the development of a wide range of applications.
 Interpreters Versus Compilers
 The first thing that is important to understand about Python is that it is an interpreted
language.
 There are two sorts of programming languages: interpreted ones and compiled ones. A
compiled language is what you are probably used to if you have done any programming in
the past.
 The process for a compiled language is as follows:
 Create source file using text edit
 Use compiler to syntax check and convert source file into binary
 Use linker to turn binary files into executable format
 Run the resulting executable format file in the operating system.
 The biggest difference between interpreted code and compiled code is that an interpreted
application need not be “complete.” MJKACC

 You can test it in bits and pieces until you are satisfied with the results and put them all
together later for the end user to use.
Python Features
 Interpreted
 There are no separate compilation and execution steps like C and C++.
 Directly run the program from the source code.
 Internally, Python converts the source code into an intermediate form called
bytecodes which is then translated into native language of specific computer to run
it.
 No need to worry about linking and loading with libraries, etc.
 Platform Independent
 Python programs can be developed and executed on multiple operating system
platforms.
 Python can be used on Linux, Windows, Macintosh, Solaris and many more.
 Free and Open Source
 Redistributable
 High-level Language
 In Python, no need to take care about low-level details such as managing the
memory used by the program.
 Simple
 Closer to English language, Easy to Learn
 More emphasis on the solution to the problem rather than the syntax
 Embeddable
 Python can be used within C/C++ program to give scripting capabilities for the
program’s users.

Page 10 of 201
CS-33: Programming in Python ch-1 Introduction to Python

 Robust:

Exceptional handling features

Memory management techniques in built
 Rich Library Support
 The Python Standard Library is very vast.
 Known as the “batteries included” philosophy of Python ;It can help do various
things involving regular expressions, documentation generation, unit testing,
threading, databases, web browsers, CGI, email, XML, HTML, WAV files,
cryptography, GUI and many more.
 Besides the standard library, there are various other high-quality libraries such as
the Python Imaging Library which is an amazingly simple image manipulation
library.

More Features:

Easy to read Python scripts have clear syntax, simple structure and very few protocols to remember
before programming.
Easy to Maintain Python code is easily to write and debug. Python's success is that its source code is
fairly easy-to-maintain.
Portable Python can run on a wide variety of Operating systems and platforms and providing
the similar interface on all platforms.
Broad Standard Python comes with many prebuilt libraries apx. 21K
Libraries
High Level Python is intended to make complex programming simpler. Python deals with memory
programming addresses, garbage collection etc internally.
Interactive Python provide an interactive shell to test the things before implementation. It provide
the user the direct interface with Python.
MJKACC

Database Interfaces Python provides interfaces to all major commercial databases. These interfaces are
pretty easy to use.
GUI programming Python supports GUI applications and has framework for Web. Interface to tkinter,
WXPython, DJango in Python make it.
 Python provides interfaces to all major commercial databases.

Why python
 Python supports functional and structured programming methods as well as OOP.
 Python provides very high-level dynamic data types and supports dynamic type checking.
 Python supports GUI applications
 Python supports automatic garbage collection.
 Python can be easily integrated with C, C++, and Java.
History of Python
 Python was conceptualized by Guido Van Rossum in the late 1980s.
 Rossum published the first version of Python code (0.9.0) in February 1991 at the CWI
(Centrum Wiskunde&Informatica) in the Netherlands , Amsterdam.
 Python is derived from ABC programming language, which is a general-purpose
programming language that had been developed at the CWI.
 Rossum chose the name "Python", since he was a big fan of Monty Python's Flying Circus.
 Python is now maintained by a core development team at the institute, although Rossum still
holds a vital role in directing its progress.

Page 11 of 201
CS-33: Programming in Python ch-1 Introduction to Python

Python Versions
Supported versions
Dates shown in italic are scheduled and can be adjusted.

Branch Schedule Status First release End of life Release manager


main PEP 719 feature 2024-10-01 2029-10 Thomas Wouters
3.12 PEP 693 bugfix 2023-10-02 2028-10 Thomas Wouters
3.11 PEP 664 bugfix 2022-10-24 2027-10 Pablo Galindo Salgado
3.10 PEP 619 security 2021-10-04 2026-10 Pablo Galindo Salgado
3.9 PEP 596 security 2020-10-05 2025-10 ŁukaszLanga
3.8 PEP 569 security 2019-10-14 2024-10 ŁukaszLanga
Unsupported versions
Branch Schedule Status First release End of life Release manager
3.7 PEP 537 end-of-life 2018-06-27 2023-06-27 Ned Deily
3.6 PEP 494 end-of-life 2016-12-23 2021-12-23 Ned Deily
3.5 PEP 478 end-of-life 2015-09-13 2020-09-30 Larry Hastings
3.4 PEP 429 end-of-life 2014-03-16 2019-03-18 Larry Hastings
3.3 PEP 398 end-of-life 2012-09-29 2017-09-29 Georg Brandl, Ned Deily (3.3.7+)
3.2 PEP 392 end-of-life 2011-02-20 2016-02-20 Georg Brandl
3.1 PEP 375 end-of-life 2009-06-27 2012-04-09 Benjamin Peterson
3.0 PEP 361 end-of-life 2008-12-03 2009-06-27 Barry Warsaw
2.7 PEP 373 end-of-life 2010-07-03 2020-01-01 Benjamin Peterson
MJKACC

2.6 PEP 361 end-of-life 2008-10-01 2013-10-29 Barry Warsaw

 Release dates for the major and minor versions:


 Python 1.0 - January 1994
 Python 1.5 - December 31, 1997
 Python 1.6 - September 5, 2000
 Python 2.0 - October 16, 2000
 Python 2.1 - April 17, 2001
 Python 2.2 - December 21, 2001
 Python 2.3 - July 29, 2003
 Python 2.4 - November 30, 2004
 Python 2.5 - September 19, 2006
 Python 2.6 - October 1, 2008
 Python 2.7 - July 3, 2010
 Release dates for the major and minor versions:
 Python 3.0 - December 3, 2008
 Python 3.1 - June 27, 2009
 Python 3.2 - February 20, 2011
 Python 3.3 - September 29, 2012
 Python 3.4 - March 16, 2014
 Python 3.5 - September 13, 2015
 Python 3.6 - 23 Dec 2016
 Python 3.7 - 27 Jun 2018
 Python 3.8 - 14 Oct 2019

Page 12 of 201
CS-33: Programming in Python ch-1 Introduction to Python

 Python 3.9 - 05 Oct 2020


 Python 3.10 - 04 Oct 2021
 Python 3.11- 24 Oct 2022
 Python 3.12 - 02 Oct 2023
Key Changes in Python 3.0
 Python 2's print statement has been replaced by the print() function.
 There is only one integer type left, int.
 Some methods such as map() and filter( ) return iterator objects in Python 3 instead of lists in
Python 2.
 In Python 3, a TypeError is raised as warning if we try to compare unorderable types. e.g.
1 < ’ ', 0 > None are no longer valid
 Python 3 provides Unicode (utf-8) strings while Python 2 has ASCII str( ) types and separate
unicode( ).
 A new built-in string formatting method format() replaces the % string formatting operator.

MJKACC

Basic Syntax
 Indentation is used in Python to delimit blocks. The number of spaces is variable, but all
statementswithin the same block must be indented the same amount.
if True:
print (“Answer”)
print (“True”)
else:
print (“Answer”)
print (“False”)
 The header line for compound statements, such as if, while, def, and class should be
terminated with a colon ( : )
 The semicolon ( ; ) is optional at the end of statement.
 Printing to the Screen:
print(“Hello, Python!|)
 Reading Keyboard Input:
Name = input (“Enter Your Name:”)
Comments:
Single line:
#print(“good morning”)
Multiple line:‘’’
Print(“welcome to mjkacc”)
Print(“hello BCA SEM -6”)
‘’'
 Python files have extension .py

Page 13 of 201
CS-33: Programming in Python ch-1 Introduction to Python

1.0. The basic elements of python


1.0.1 Variables
 Python is dynamically typed. You do not need to declare variables!
 The declaration happens automatically when you assign a value to a variable.
counter = 100 # An integer assignment
miles = 1000.0 # A floating point
name = “MJKACC” # A string
z = None # A null value
 Variables can change type, simply by assigning them a new value of a different type.

X = 1
X = “string
value”
 Python allows you to assign a single value to several variables simultaneously.
a=b=c=1

 You can also assign multiple objects to multiple variables.


a, b, c = 1, 2, “MJKACC”

1.0.2Python Reserved Words


 A keyword is one that means something to the language. In other words, you can’t use a
reserved word as the name of a variable, a function, a class, or a module.
 All the Python keywords contain lowercase letters only.
MJKACC

and exec not


assert finally or
break for pass
class from print
continue global raise
def if return
del import try
elif in while
else is with
except lambda yield

Page 14 of 201
CS-33: Programming in Python ch-1 Introduction to Python

1.1 Branching programs orPython Control Structures orConditionals


 In Python, True and False are Boolean objects of class 'bool' and they are immutable.
 Python assumes any non-zero and non-null values as True, otherwise it is False value.
 Python does not provide switch or case statements as in other languages.
 Syntax:
 if Statement

if expression:
statement(s)
 if..else Statement

if expression:
statement(s)
else:
statement(s)
 if..elif..else Statement
if expression1:
statement(s)
elif expression2:
statement(s)
elif expression3:
statement(s)
Example: else:
statement(s)
MJKACC

x=int(input("please enter an integer:"))


if x<0:
x=0
print("negative change to zero")
elif x==0:
print("zero")
elif x==1:
print("single")
else:
print("more")

 Using the conditional expression


 Another type of conditional structure in Python, which is very convenient and easy to read.

a,b=4,5
if a<b:
x="smaller"
else:
x="bigger"
print(x)

Page 15 of 201

x=int(input("please enter an integer:"))


CS-33: Programming in Python ch-1 Introduction to Python

1.3 Strings and Input


1.3.0 String
 Python Strings are
Immutable objects that cannot
change their values.

 You can update an existing string by (re)assigning a variable to another string.


 Python does not support a character type; these are treated as strings of length one.
 Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals.
name1="sample string"
name2="another sample string "
name3=""" a multile line
"""
print(name3)

 String indexes starting at 0 in the beginning of the string and working their way from -1 at the
end.

1.3.1 String Formatting


MJKACC

1.3.2 Common String Operators


 Assume string variable a holds 'Hello' and variable b holds 'Python’
Operator Description Example
+ Concatenation - Adds values on either side of the operator a + b will give
HelloPython
* Repetition - Creates new strings, concatenating multiple copies of a*2 will give HelloHello
the same string
[] Slice - Gives the character from the given index a[1] will give e
a[-1] will give o
[:] Range Slice - Gives the characters from the given range a[1:4] will give ell
In Membership - Returns true if a character exists in the given string ‘H’ in a will give True

1.3.3 Common String Methods


Method Description
[Link](sub,beg= 0,end=len(str)) Counts how many times sub occurs in string or in a substring of string
if starting index beg and ending index end are given.
[Link]() Returns True if string has at least 1 character and all characters are
alphanumeric and False otherwise.
[Link]() Returns True if string contains only digits and False otherwise.

Page 16 of 201
CS-33: Programming in Python ch-1 Introduction to Python

[Link]() Converts all uppercase letters in string to lowercase.


[Link]() Converts lowercase letters in string to uppercase
[Link](old, new) Replaces all occurrences of old in string with new.
[Link](str=‘ ’) Splits string according to delimiter str (space if not provided)
And returns list of substrings.
[Link]() Removes all leading and trailing whitespace of string.
[Link]() Returns "titlecased" version of string.
Common String Functions
 str(x) :to convert x to a string
 len(string):gives the total length of the string

1.3.4 Numbers
 Numbers are Immutable objects in Python that cannot change their values.
 There are three built-in data types for numbers in Python3:
 Integer (int)
 Floating-point numbers (float)
 Complex numbers: <real part> + <imaginary part>j (not used much in Python
programming)
1.3.5 Common Number Functions
Function Description
int(x) to convert x to an integer
float(x) to convert x to a floating-point number
abs(x) The absolute value of x
cmp(x,y) -1 if x < y, 0 if x == y, or 1 if x > y
exp(x) The exponential of x: ex MJKACC

log(x) The natural logarithm of x, for x> 0


pow(x,y) The value of x**y
sqrt(x) The square root of x for x > 0

1.4 Iteration
An iterator is an object that contains a countable number of values.
An iterator is an object that can be iterated upon, meaning that you can traverse through all
the values.
 Technically, in Python, an iterator is an object which implements the iterator protocol, which
consist of the methods __iter__() and __next__().
Example
mytuple = ("apple", "banana", "cherry")
myit = iter(mytuple)
print(next(myit))
print(next(myit))
print(next(myit))
Output
apple
banana
cherry

Page 17 of 201
CS-33: Programming in Python ch-1 Introduction to Python

1.4.0 The For Loop


 A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set,
or a string).
 This is less like the for keyword in other programming language, and works more like an
iterator method as found in other object-orientated programming languages.
 With the for loop we can execute a set of statements, once for each item in a list, tuple, set
etc.
 Example

x=['Anil','Punit','Kumar']
for name in x:
print("current name:",x)
output:
current name: ['Anil', 'Punit', 'Kumar']
current name: ['Anil', 'Punit', 'Kumar']
current name: ['Anil', 'Punit', 'Kumar']

count=0
 The while Loop: while count < 5:
print('The count is:',count)
count = count+1
Output:
The count is: 0
The count is: 1
The count is: 2 MJKACC

The count is: 3


The count is: 4

1.5. Functions and Functions as Objects


1.5.0 Function
 A function is a block of code which only runs when it is called.
 You can pass data, known as parameters, into a function.
 A function can return data as a result.
 Creating a Function
 In Python a function is defined using the def keyword:
Example
def my_function():
print("Hello from a function")
 Calling a Function
 To call a function, use the function name followed by parenthesis:
Exmple
defmy_function():
print("Hello from a function")
my_function()
output:
Hello from a function

Page 18 of 201
CS-33: Programming in Python ch-1 Introduction to Python

Parameters
 Information can be passed to functions as parameter.
 Parameters are specified after the function name, inside the parentheses. You can add as
many parameters as you want, just separate them with a comma.
 The following example has a function with one parameter (fname). When the function is
called, we pass along a first name, which is used inside the function to print the full name:
Example
defmy_function(fname):
print(fname + " mjkacc")
my_function("Bca-1")
my_function("Bca-2")
my_function("Bca-3")
output:
Bca-1 mjkacc
Bca-2 mjkacc
Bca-3 mjkacc

1.5.1 Variable Scope


 Now that you know how to initialize a variable. Let's talk about the scope of these variables.
Not all variables can be accessed from anywhere in a program. The part of a program where a
variable is accessible is called its scope. There are four major types of variable scope and is
the basis for the LEGB rule. LEGB stands for Local -> Enclosing -> Global -> Built-in.
 LEGB Rule :LEGB (Local -> Enclosing -> Global -> Built-in) is the logic followed by a
Python interpreter when it is executing your program.

MJKACC

When we are calling print(x) within inner(), which is a function nested in outer(). Then
Python will first look if "x" was defined locally within inner(). If not, the variable defined
in outer() will be used. This is the enclosing function. If it also wasn't defined there, the
Python interpreter will go up another level - to the global scope. Above that, you will only
find the built-in scope, which contains special variables reserved for Python itself.

Local Scope: Whenever you define a variable within a function, its scope lies ONLY within the
function. It is accessible from the point at which it is defined until the end of the function and exists
for as long as the function is executing (Source). Which means its value cannot be changed or even
accessed from outside the function. Let's take a simple example:
def print_number():
first_num = 1
# Print statement 1
print("The first number defined is: ", first_num)

Page 19 of 201
CS-33: Programming in Python ch-1 Introduction to Python

print_number()
# Print statement 2
print("The first number defined is: ", first_num)
 Following is the out put which shows the printing value of local but not outer
The first number defined is: 1
Traceback (most recent call last):
File "C:/Users/DAK/Downloads/[Link]", line 7, in <module>
print("The first number defined is: ", first_num)
NameError: name 'first_num' is not defined
 Enclosing Scope: if we have a nested function (function defined inside another function)?
How does the scope change? Let's see with the help of an example.
def outer():
first_num = 1
def inner():
second_num = 2
# Print statement 1 - Scope: Inner
print("first_num from outer: ", first_num)
# Print statement 2 - Scope: Inner
print("second_num from inner: ", second_num)
inner()
# Print statement 3 - Scope: Outer
print("second_num from inner: ", second_num)

outer()
 Following is the output: MJKACC

first_num from outer: 1


second_num from inner: 2
Traceback (most recent call last):
File "C:/Users/DAK/Downloads/[Link]", line 12, in <module>
outer()
File "C:/Users/DAK/Downloads/[Link]", line 11, in outer
print("second_num from inner: ", second_num)
NameError: name 'second_num' is not defined
 Got an error? This is because you cannot access second_num from outer() (#Print statement
3). It is not defined within that function. However, you can access first_num from inner() (#
Print statement 1), because the scope of first_num is larger, itis within outer().This is
an enclosing scope. Outer's variables have a larger scope and can be accessed from the
enclosed function inner().
 Global Scope: This is perhaps the easiest scope to understand. Whenever a variable is
defined outside any function, it becomes a global variable, and its scope is anywhere within
the program. Which means it can be used by any function.
greeting = "Hello"
def greeting_world():
world = "World"
print(greeting, world)
def greeting_name(name):
print(greeting, name)
greeting_world()
greeting_name("Dhruvit")

Page 20 of 201
CS-33: Programming in Python ch-1 Introduction to Python

 Following is the output:


Hello World
Hello Dhruvit
 Built-in Scope: This is the widest scope that exists! All the special reserved keywords fall
under this scope. We can call the keywords anywhere within our program without having to
define them before [Link] are simply special reserved words. They are kept for
specific purposes and cannot be used for any other purpose in the program.
These are the keywords in Python:

1.5.2 Function Specification


 One of the the most important aspects of writing a quality Python function is
proper specification. While the term may sound generic, a specification actually has a very
precise definition and implementation for a Python function. In practice, a specification is a
docstring, a “string literal” that occurs as the first statement in a function, module, class or
method, formed by a bracketed set of “””. Here is an example of a simple function I wrote
with a specification:
def radians_to_degrees(theta):
"""
Returns: theta converted to degrees
Value return has type float MJKACC

Parameter theta: the angle in radians


Precondition: theta is a float
"""
return theta * (180.0/3.14159)
 The function specification is everything between the sets of “””. When Python sees this
docstring at the front of a function definition, it automatically is stored as the “__doc__”
associated with the function. With this specification in place, any user that loads this function
can access its __doc__ by typing help(radians_to_degrees), which will print the following to
the terminal:
Help on function radians_to_degrees in module __main__:
radians_to_degrees(theta)
Returns: theta converted to degrees
Value return has type float
Parameter theta: the angle in radians
Precondition: theta is a float

 The help function will print anything in the docstring at the start of a function, but a it is good
practice for the specification to have the following elements:
 A one-line summary of the function at the very beginning, if the function is a “fruitful
function” (meaning it returns something), this line should tell what it returns. In my example
I note that my function returns theta converted to degrees.
 In my example this simply provides the type of the return value.
 A description of the function’s parameter(s)
 Any preconditions that are necessary for the code to run properly

Page 21 of 201
CS-33: Programming in Python ch-1 Introduction to Python

 I should note that officially the Python programming language has a more flexible set of
requirements for function specifications, which can be found here, but the attributes above
are a good starting point for writing clear specifications.
 Properly specifying a Python function will clarify the function’s intended use and provide
instructions for how new users can utilize it. It will also help you document your code for
formal release if you ever publish it. Google any of your favorite Python functions and you’ll
likely be brought to a page that has a fancy looking version of the function’s specification.
These pages can be automatically generated by tools such as Spinx that create them right
from the function’s definition.
 Aside from clarifying and providing instructions for your function, specifications provide a
means of creating a chain of accountability for any problems with your code. This chain of
accountability is created through precondition statements (element four above). A
precondition statement dictates requirements for the function to run properly. Preconditions
may specify the type of parameter input (i.e. x is a float) or a general statement about the
parameter (x < 0).
 For large teams of many developers and users of functions, precondition statements create a
chain of accountability for code problems. If the preconditions are violated and a code
crashes, then it is the responsibility of the user, who did not use the code properly. On the
other hand, if the preconditions were met and the code crashes, it is the responsibility of the
developer, who did not properly specify the code.

1.5.3 Function Recursion


 The term Recursion can be defined as the process of defining something in terms of itself.
In simple words, it is a process in which a function calls itself directly or indirectly.
 Advantages of using recursion
o A complicated function can be split down into smaller sub-problems utilizing
MJKACC

recursion.
o Sequence creation is simpler through recursion than utilizing any nested iteration.
o Recursive functions render the code look simple and effective.
 Disadvantages of using recursion
o A lot of memory and time is taken through recursive calls which makes it expensive
for use.
o Recursive functions are challenging to debug.
o The reasoning behind recursion can sometimes be tough to think through.
Syntax:
def func(): <--
.
. (Recursive call)
.
func() ----

Page 22 of 201
CS-33: Programming in Python ch-1 Introduction to Python

Example 1: A Fibonacci sequence is the integer sequence of 0, 1, 1, 2, 3, 5, 8….


# Program to print the fibonacci series upto n_terms
# Recursive function
def recursive_fibonacci(n):
if n <= 1:
return n
else:
return(recursive_fibonacci(n-1) + recursive_fibonacci(n-2))

n_terms = 10

# check if the number of terms is valid


if n_terms <= 0:
print("Invalid input ! Please input a positive value")
else:
print("Fibonacci series:")
for i in range(n_terms):
print(recursive_fibonacci(i))

Output
Fibonacci series:
0
1
1
2
3 MJKACC

5
8
13
21
34

Example 2: The factorial of 6 is denoted as 6! = 1*2*3*4*5*6 = 720.


# Program to print factorial of a number
# recursively.
# Recursive function
def recursive_factorial(n):
if n == 1:
return n
else:
return n * recursive_factorial(n-1)
# user input
num = 6
# check if the input is valid or not
if num < 0:
print("Invalid input ! Please enter a positive number.")
elif num == 0:
print("Factorial of number 0 is 1")
else:
print("Factorial of number", num, "=", recursive_factorial(num))

Page 23 of 201
CS-33: Programming in Python ch-1 Introduction to Python

Output
Factorial of number 6 = 720

What is Tail-Recursion?
 A unique type of recursion where the last procedure of a function is a recursive call. The
recursion may be automated away by performing the request in the current stack frame
and returning the output instead of generating a new stack frame. The tail-recursion may
be optimized by the compiler which makes it better than non-tail recursive functions.
Is it possible to optimize a program by making use of a tail-recursive function instead of non-tail
recursivefunction?
 Considering the function given below in order to calculate the factorial of n, we can
observe that the function looks like a tail-recursive at first but it is a non-tail-recursive
function. If we observe closely, we can see that the value returned by Recur_facto(n-1) is
used in Recur_facto(n), so the call to Recur_facto(n-1) is not the last thing done by
Recur_facto(n).
# Program to calculate factorial of a number
# using a Non-Tail-Recursive function.

# non-tail recursive function


def Recur_facto(n):

if (n == 0):
return 1
MJKACC

return n * Recur_facto(n-1)

# print the result


print(Recur_facto(6))

Output
720
 We can write the given function Recur_facto as a tail-recursive function. The idea is to use
one more argument and in the second argument, we accommodate the value of the factorial.
When n reaches 0, return the final value of the factorial of the desired number.

# Program to calculate factorial of a number


# using a Tail-Recursive function.

# A tail recursive function


def Recur_facto(n, a = 1):
if (n == 0):
return a
return Recur_facto(n - 1, n * a)
# print the result
print(Recur_facto(6))

Output
720

Page 24 of 201
CS-33: Programming in Python ch-1 Introduction to Python

1.6 Global variables


Declare a global variable inside a function, and use it outside the function:
Example:

def myfunction():#create a function:


global x
x="hello"
myfunction()#execute the function:
#x should now be global, and accessible in the global
scope.
print(x)
output:
hello

1.6 Modules
1.6.0 What is a Module?
 Consider a module to be the same as a code library.
 A file containing a set of functions you want to include in your application.
1.6.1 Create a Module
 To create a module just save the code you want in a file with the file extension .py:
Example
 Save this code in a file named [Link]

def greeting(name):
print("Hello, " + name) MJKACC

1.6.2 Use a Module


 Now we can use the module we just created, by using the import statement:
 Example
 Import the module named mymodule, and call the greeting function:

Import mymodule
[Link]("mjkacc")
1.7 Python Files
 File handling is an important part of any web application.
 Python has several functions for creating, reading, updating, and deleting files.
1.7.0 File Handling
 The key function for working with files in Python is the open() function.
 The open() function takes two parameters; filename, and mode.
 There are four different methods (modes) for opening a file:
o "r" - Read - Default value. Opens a file for reading, error if the file does not exist
o "a" - Append - Opens a file for appending, creates the file if it does not exist
o "w" - Write - Opens a file for writing, creates the file if it does not exist
o "x" - Create - Creates the specified file, returns an error if the file exists
 In addition you can specify if the file should be handled as binary or text mode
o "t" - Text - Default value. Text mode
o "b" - Binary - Binary mode (e.g. images)

Page 25 of 201
CS-33: Programming in Python ch-1 Introduction to Python

Syntax
 To open a file for reading it is enough to specify the name of the file:
 f = open("[Link]")
 The code above is the same as:
 f = open("[Link]", "rt")
 Because "r" for read, and "t" for text are the default values, you do not need to specify
them.
1.7.1 Open a File on the Server
 Assume we have the following file, located in the same folder as Python:
[Link]
Hello! Welcome to [Link]
This file is for testing purposes.
Good Luck!

 To open the file, use the built-in open() function.


 The open() function returns a file object, which has a read() method for reading the content
of the file:
 Example:
f = open("[Link]", "r")
print([Link]())
output:
Hello! Welcome to [Link]
This file is for testing purposes.
Good Luck!
MJKACC

1.7.2 Read Only Parts of the File


 By default the read() method returns the whole text, but you can also specify how many
character you want to return:
 Example
 Return the 5 first characters of the file:
f = open("[Link]", "r")
print([Link](5))
output:Hello

1.7.3 Write to an Existing File


 To write to an existing file, you must add a parameter to the open() function:
 "a" - Append - will append to the end of the file
 "w" - Write - will overwrite any existing content
 Example
 Open the file "[Link]" and append content to the file:
 f = open("[Link]", "a")
[Link]("Now the file has one more line!")

Example
o Open the file "[Link]" and overwrite the content:
o f = open("[Link]", "w")
[Link]("Woops! I have deleted the content!")

Page 26 of 201
CS-33: Programming in Python ch-1 Introduction to Python

1.7.4 Create a New File


 To create a new file in Python, use the open() method, with one of the following
parameters:
 "x" - Create - will create a file, returns an error if the file exist
 "a" - Append - will create a file if the specified file does not exist
 "w" - Write - will create a file if the specified file does not exist
Example
o Create a file called "[Link]":
o f = open("[Link]", "x")
 Result: a new empty file is created!
Example
o Create a new file if it does not exist:
o f = open("[Link]", "w")
1.8.5 Delete a File
 To delete a file, you must import the OS module, and run its [Link]() function:
Example
o Remove the file "[Link]":
o import os
[Link]("[Link]")
1.8.6 Check if File exist:
 To avoid getting an error, you might want to check if the file exist before you try to delete it:
Example
Check if file exist, then delete it:
import os
if [Link]("[Link]"): MJKACC

[Link]("[Link]")
else:
print("The file does not exist")
1.8.7 Delete Folder
 To delete an entire folder, use the [Link]() method:
Example
 Remove the folder "myfolder":
import os
[Link]("myfolder")
1.9 Tuples
 A tuple is a collection which is ordered and unchangeable. In Python tuples are written with
round brackets.
 Python Tuples are Immutable objects that cannot be changed once they have been created.
 A tuple contains items separated by commas and enclosed in parentheses instead of square
brackets.

 You can update an existing tuple by (re)assigning a variable to another tuple.


 Tuples are faster than lists and protect your data against accidental changes to these data.

Page 27 of 201
CS-33: Programming in Python ch-1 Introduction to Python

 The rules for tuple indices are the same as for lists and they have the same operations,
functions as well.
 To write a tuple containing a single value, you have to include a comma, even though there is
only one value. e.g. t = (3, )
Example
 Create a Tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple)
 You can access tuple items by referring to the index number, inside square brackets:
Example
 Return the item in position 1:
thistuple = ("apple", "banana", "cherry")
print(thistuple[1])
1.9.0 Change Tuple Values
 Once a tuple is created, you cannot change its values. Tuples are unchangeable.
Example
 You cannot change values in a tuple:
thistuple = ("apple", "banana", "cherry")
thistuple[1] = "blackcurrant"
# The values will remain the same:
print(thistuple)
1.9.1 Python Tuple Methods
 Python has two built-in methods that you can use on tuples.
Method Description MJKACC

count() Returns the number of times a specified value occurs in a tuple

index() Searches the tuple for a specified value and returns the position of where it was found
1.10 Lists and Mutability
1.10.0 Lists
 A list in Python is an ordered group of items or elements, and these list elements don't have to
be of the same type.
 Python Lists are mutable objects that can change their values.
 A list contains items separated by commas and enclosed within square brackets.
 List indexes like strings starting at 0 in the beginning of the list and working their way from -
1 at the end.
 Similar to strings,Lists operations include slicing ([] and [:]),concatenation (+),repetition (*),
and membership (in).
 This example shows how to access, update and delete list elements:

Page 28 of 201
CS-33: Programming in Python ch-1 Introduction to Python

 Lists can have sub lists as elements and these sub lists may contain other sub lists as well.

1.10.1 Common List Functions


Function Description

cmp(list1, list2) Compares elements of both lists.


len(list) Gives the total length of the list.
max(list) Returns item from the list with max value.
MJKACC

min(list) Returns item from the list with min value.


list(tuple) Converts a tuple into list.
1.10.2 Common List Methods
Method Description
[Link](obj) Appends object obj to list
[Link](index, obj) Inserts object obj into list at offset index
[Link](obj) Returns count of how many times obj occurs in list
[Link](obj) Returns the lowest index in list that obj appears
[Link](obj) Removes object obj from list
[Link]() Reverses objects of list in place
[Link]() Sorts objects of list in place

1.10.3 List Comprehensions


 Each list comprehension consists of an expression followed by a for clause.

Page 29 of 201
CS-33: Programming in Python ch-1 Introduction to Python

1.11 Dictionaries
1.11.0 Introduction
 A dictionary is a collection which is unordered, changeable and indexed. In Python
dictionaries are written with curly brackets, and they have keys and values.
 Python's dictionaries are kind of hash table type which consist of key-value pairs of
unordered elements.
 Keys : must be immutable data types ,usually numbers or strings.
 Values : can be any arbitrary Python object.
 Python Dictionaries are mutable objects that can change their values.
 A dictionary is enclosed by curly braces ({ }), the items are separated by commas, and each
key is separated from its value by a colon (:).
 Dictionary’s values can be assigned and accessed using square braces ([]) with a key to
obtain its value.
 This example shows how to access, update and delete dictionary elements:
1.11.1 Change Values
 You can change the value of a specific item by referring to its key name:
Example
Change the "year" to 2018:
thisdict={
"brand":"Ford",
"model":"Mustang",
"year":1964
}
thisdict["year"] = 2018
output:{'brand': 'Ford', 'model': 'Mustang', 'year': 2018}
MJKACC

1.11.2 Loop through a Dictionary


 You can loop through a dictionary by using a for loop.
 When looping through a dictionary, the return value are the keys of the dictionary, but there
are methods to return the values as well.
 Example:
Print all key names in the dictionary, one by one:
thisdict ={
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in thisdict:
print(x)
output:
brand
model
year

1.11.3 Python Dictionary Methods


Python has a set of built-in methods that you can use on dictionaries.
Methods Discription
[Link]() Returns list of dict's keys
[Link]() Returns list of dict's values
[Link]() Returns a list of dict's (key, value) tuple pairs

Page 30 of 201
CS-33: Programming in Python ch-1 Introduction to Python

[Link](key, default=None) For key, returns value or default if key not in dict
dict.has_key(key) Returns True if key in dict, False otherwise
[Link](dict2) Adds dict2's key-values pairs to dict
[Link]() Removes all elements of dict

1.11.4 Common Dictionary Functions


 cmp(dict1, dict2) : compares elements of both dict.
 len(dict) : gives the total number of (key, value) pairs in the dictionary.
1.11.5 Accessing Values in Dictionary
 To access dictionary elements, you can use the familiar square brackets along with the key to
obtain its value.
 Example
# Declare a dictionary
dict = {'Name': 'SMILY', 'Age': 2, 'Class': 'First'}
# Accessing the dictionary with its key
print ("dict['Name']: ", dict['Name'])
print ("dict['Age']: ", dict['Age'])
 Output: When the above code is executed, it produces the following result −
dict['Name']: SMILY
dict['Age']: 2
1.11.6 Updating Dictionary
 You can update a dictionary by adding a new entry or a key-value pair, modifying an existing
entry, or deleting an existing entry as shown below in the simple example −
 Example
# Declare a dictionary MJKACC

dict = {'Name': 'vd', 'Age': 7, 'Class': 'First'}


dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School"; # Add new entry
print ("dict['Age']: ", dict['Age'])
print ("dict['School']: ", dict['School'])

 Output:When the above code is executed, it produces the following result −


dict['Age']: 8
dict['School']: DPS School
1.11.7 Delete Dictionary Elements
 You can either remove individual dictionary elements or clear the entire contents of a
dictionary. You can also delete entire dictionary in a single [Link] explicitly remove an
entire dictionary, just use the del statement.
 Example
dict = {'Name': 'SMILY', 'Age': 2, 'Class': 'First'}
del dict['Name']; # remove entry with key 'Name'
[Link](); # remove all entries in dict
del dict ; # delete entire dictionary
print ("dict['Age']: ", dict['Age'])
print ("dict['School']: ", dict['School'])

 Output: This produces the following result. Note that an exception is raised because after del
dict dictionary does not exist anymore.
dict['Age']: dict['Age']
dict['School']: dict['School']

Page 31 of 201
CS-33: Programming in Python ch-1 Introduction to Python

1.12 Hash Table


 Hashing is a technique that is used to uniquely identify a specific object from a group of
similar objects.
 Assume that you have an object and you want to assign a key to it to make searching easy.
 To store the key/value pair, you can use a simple array like a data structure where keys
(integers) can be used directly as an index to store values.
 However, in cases where the keys are large and cannot be used directly as an index, you
should use hashing.
 In Python, the Dictionary data types represent the implementation of hash tables. The Keys in
the dictionary satisfy the following requirements.

MJKACC

Page 32 of 201
CS-33: Programming in Python Ch-2 OOP Using Python

2.0 Python - Exceptions Handling


2.0.0 What is Exception?
 An exception is an event, which occurs during the execution of a program that disrupts the
normal flow of the program's instructions. In general, when a Python script encounters a
situation that it cannot cope with, it raises an exception. An exception is a Python object
that represents an error.
 When a Python script raises an exception, it must either handle the exception immediately
otherwise it terminates and quits.
2.0.1 Handling an exception
 If you have some suspicious code that may raise an exception, you can defend your
program by placing the suspicious code in a try: block. After the try: block, include
an except: statement, followed by a block of code which handles the problem as elegantly
as possible.
 This would be covered in this. Here is a list standard Exceptions available in Python:
 When an error occurs, or exception as we call it, Python will normally stop and generate an
error message.
 An exception is an undesirable event which arises during the execution of a program that
disrupts the normal flow of the program’s instructions.
 To handle these errors or exceptions, we use the technique of Exception Handling.
 Exceptions are normally caused due to the following events:
 1. A File that is to be opened but is not found in the memory.
2. Invalid entry of data by the user.
 This is an example of Python error. The benefit with Python is that it provides us well details
error messages. MJKACC

 In the above program, it tells me the error line number and the error line code. Moreover, it
also tells me if I have forgotten anything. Like, in the above program I have missed to
declare variable a and directly printing variable onto the console.
 With the help of Python exception handling technique, we can avoid abrupt termination of a
program and handle interruptions and errors and prevent the program from closing
abruptly.
 While making your program code, if you think that a certain part of your program code may
not work properly, then on execution it may terminate abruptly and your system may crash.
To prevent all of this, you may add an exception block in your code so that if an error occurs,
Python Interpreter will catch that exception and prevent your program from crashing.
 These exceptions can be handled using the try statement:
 The try block lets you test a block of code for errors.
 The except block lets you handle the error.
 The finally block lets you execute code, regardless of the result of the try- and except blocks.
Syntax
Here is simple syntax of try....except...else blocks −
try:
You do your operations here;
......................
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
......................

Page 33 of 201
CS-33: Programming in Python Ch-2 OOP Using Python

else:
If there is no exception then execute this block.
 Here are few important points about the above-mentioned syntax −
 A single try statement can have multiple except statements. This is useful when the try
block contains statements that may throw different types of exceptions.
 You can also provide a generic except clause, which handles any exception.
 After the except clause(s), you can include an else-clause. The code in the else-block
executes if the code in the try: block does not raise an exception.
 The else-block is a good place for code that does not need the try: block's protection.
Example
try:
fh = open("testfile", "w")
[Link]("This is my test file for exception handling!!")
except IOError:
print ("Error: can\'t find file or read data")
else:
print ("Written content in the file successfully")
[Link]()
output:
Written content in the file successfully
2.0.2 try...finally
 The try statement in Python can have an optional finally clause. This clause is executed no
matter what, and is generally used to release external resources.
 For example, we may be connected to a remote data center through the network or
working with a file or working with a Graphical User Interface (GUI).
MJKACC

 In all these circumstances, we must clean up the resource once used, whether it was
successful or not. These actions (closing a file, GUI or disconnecting from network) are
performed in the finally clause to guarantee execution.
2.0.3 Python finally Block
 A finally block is very useful in Python exception handling. A finally clause always gets
executed as soon the control completes the try block. It doesn’t matter whether an
exception has occurred or not.
Syntax:
finally():
statement 1
statement n
Example:

try:
var1=float(raw_input("Enter a Number:\n"))
print("\n")
except:
print("Erorr Executing\n")
finally:
print("We are in finally block")

Page 34 of 201
CS-33: Programming in Python Ch-2 OOP Using Python

2.1 Exceptions as a control flow mechanism:


 There’s one other form of flow control that is common within Python, exception handling.
 You may be familiar with the concept from languages like C++, Java, or JavaScript.
 One thing that differs compared to many other languages is that in Python exceptions are
relatively lightweight. This means they aren’t only meant to be used in the most extreme
circumstances, instead it is not uncommon to use them as a type of control flow.

2.1.0 Python try except Block


 The standard way to handle exceptions is by including a try and except block in your
program code.
 In the try block, you can write a section of code that could probably raise an error.
 The except block is then written so that if your exception comes true, the control of the
program will be passed to the except block and you could thus prevent program from
abnormal termination.
Syntax:
try:
statement 1
statement 2
statement n
except:
statement 1
statement 2
statement n
 Let’s try to access an element that doesn’t exist within a list:
Example MJKACC

my_list = [1, 2, 3]
try:
my_list[99]
except Exception as e:
print(e)

output: list index out of range


2.1.1 Multiple Exception Block
 You can also include multiple exception blocks with single try block which helps the Python
interpreter to specify exactly what the error is.
Example:
try:
var1=float(raw_input("Enter a Number:\n"))
print("\n")
except(SyntaxError):
print("Syntax Error Occured\n")
except(TypeError):
print("Invalid Datatype")
except(ValueError):
print("Invalid Value")

Page 35 of 201
CS-33: Programming in Python Ch-2 OOP Using Python

2.1.2 Python Standard Exceptions


 There are some pre-defined or standard exceptions in the Python library. So, you can use
one of them if your needs are sufficed. These exceptions are as follow:
IOError:
 It is raised when an I/O operation fails to execute such as when an attempt is made to open
a file in read mode that does not exist.

IndexError:
 This error is raised when a sequence is indexed with a number of an element that does not
exist.

KeyError:
 This error is raised when a dictionary key is not found.

NameError:
 It is raised when a name of an identifier such as a variable or a function is not found.
SyntaxError:
 It is raised when a syntax error occurs.

TypeError:
 It is raised when a built-in operation or function is applied to an object of
inappropriate datatype.

ValueError: MJKACC

 It occurs when a built-in operation or a function receives an argument that has the right
type but an inappropriate value.

ZeroDivisionError:
 It is raised when the second argument of a division or modulo operation is zero.

2.3 Abstract Data Types


 Abstract Data type (ADT) is a type (or class) for objects whose behavior is defined by a set of
value and a set of operations.
 The definition of ADT only mentions what operations are to be performed but not how
these operations will be implemented.
 It does not specify how data will be organized in memory and what algorithms will be used
for implementing the operations. It is called “abstract” because it gives an implementation
independent view.
 The process of providing only the essentials and hiding the details is known as abstraction.
The user of data type need not know that data type is implemented, for example, we have
been using int, float, char data types only with the knowledge with values that can take and
operations that can be performed on them without any idea of how these types are
implemented.
 So a user only needs to know what a data type can do but not how it will do it. We can think
of ADT as a black box which hides the inner structure and design of the data type.
 Now we’ll define three ADTs namely List ADT, Stack ADT, Queue ADT.

Page 36 of 201
CS-33: Programming in Python Ch-2 OOP Using Python

2.3.0 List ADT


 A list contains elements of same type arranged in sequential order and following operations
can be performed on the list.
get()
 Return an element from the list at any given position.

insert()
 Insert an element at any position of the list.

remove()
 Remove the first occurrence of any element from a non-empty list.

removeAt()
 Remove the element at a specified location from a non-empty list.

replace()
 Replace an element at any position by another element.

size()
 Return the number of elements in the list.

isEmpty()
 Return true if the list is empty, otherwise return false.
MJKACC

isFull()
 Return true if the list is full, otherwise return false.

2.3.1 Stack ADT


 A Stack contains elements of same type arranged in sequential order. All operations takes
place at a single end that is top of the stack and following operations can be performed:
push()
 Insert an element at one end of the stack called top.

pop()
 Remove and return the element at the top of the stack, if it is not empty.

peek()
 Return the element at the top of the stack without removing it, if the stack is not empty.

size()
 Return the number of elements in the stack.

isEmpty()
 Return true if the stack is empty, otherwise return false.

isFull()
 Return true if the stack is full, otherwise return false.

Page 37 of 201
CS-33: Programming in Python Ch-2 OOP Using Python

2.3.2 Queue ADT


 A Queue contains elements of same type arranged in sequential order. Operations takes
place at both ends, insertion is done at end and deletion is done at front. Following
operations can be performed:

enqueue()
 Insert an element at the end of the queue.

dequeue()
 Remove and return the first element of queue, if the queue is not empty.

peek()
 Return the element of the queue without removing it, if the queue is not empty.

size()
 Return the number of elements in the queue.

isEmpty()
 Return true if the queue is empty, otherwise return false.

isFull()
 Return true if the queue is full, otherwise return false.

 From these definitions, we can clearly see that the definitions do not specify how these
MJKACC

ADTs will be represented and how the operations will be carried out.
 There can be different ways to implement an ADT, for example, the List ADT can be
implemented using arrays, or singly linked list or doubly linked list. Similarly, stack ADT and
Queue ADT can be implemented using arrays or linked lists.
2.4 Assertion
 Python Assertions in any programming language are the debugging tools that help in the
smooth flow of code. Assertions are mainly assumptions that a programmer knows or
always wants to be true and hence puts them in code so that failure of these doesn’t allow
the code to execute further.
2.4.0 Assert Keyword in Python
 We can say that assertion is the boolean expression that checks if the statement is True or
False. If the statement is true then it does nothing and continues the execution, but if the
statement is False then it stops the execution of the program and throws an error.

Page 38 of 201
CS-33: Programming in Python Ch-2 OOP Using Python

2.4.1 Flowchart of Python Assert Statement

Flowchart of Python Assert Statement

2.4.2 Python assert keyword Syntax


 In Python, the assert keyword helps in achieving this task. This statement takes as input a
boolean condition, which when returns true doesn’t do anything and continues the normal
flow of execution, but if it is computed to be false, then it raises an AssertionError along
with the optional message provided.

Syntax: assert condition, error_message(optional)

Parameters:
 condition: The boolean condition returning true or false.
 error_message : The optional argument to be printed in console in case of AssertionError
MJKACC

Returns: Returns AssertionError, in case the condition evaluates to false along with the error
message which when provided.

2.4.3 Python assert keyword without error message


 This code is trying to demonstrate the use of assert in Python by checking whether the
value of b is 0 before performing a division operation. a is initialized to the value 4, and b is
initialized to the value 0. The program prints the message “The value of a / b is: “.The
assert statement checks whether b is not equal to 0. Since b is 0, the assert statement fails
and raises an AssertionError.
 Since an exception is raised by the failed assert statement, the program terminates and does
not continue to execute the print statement on the next line.
Example
# initializing number
a =4
b =0

# using assert to check for 0


print("The value of a / b is : ")
assert b !=0
print(a /b)

Page 39 of 201
CS-33: Programming in Python Ch-2 OOP Using Python

Output:
The value of a / b is :
---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
Input In [19], in <cell line: 10>()
8 # using assert to check for 0
9 print("The value of a / b is : ")
---> 10 assert b != 0
11 print(a / b)

AssertionError:

2.4.4 Python assert keyword with an error message


 This code is trying to demonstrate the use of assert in Python by checking whether the
value of b is 0 before performing a division operation. a is initialized to the value 4, and b is
initialized to the value 0. The program prints the message “The value of a / b is: “.The
assert statement checks whether b is not equal to 0. Since b is 0, the assert statement fails
and raises an AssertionError with the message “Zero Division Error”.
 Since an exception is raised by the failed assert statement, the program terminates and does
not continue to execute the print statement on the next line.
Example
# Python 3 code to demonstrate
# working of assert

# initializing number
a =4 MJKACC

b =0

# using assert to check for 0


print("The value of a / b is : ")
assert b !=0, "Zero Division Error"
print(a /b)
Output:
AssertionError: Zero Division Error

2.4.5 Assert Inside a Function


 The assert statement is used inside a function in this example to verify that a rectangle’s
length and width are positive before computing its area. The assertion raises an
AssertionError with the message “Length and width must be positive” if it is false.
 If the assertion is true, the function returns the rectangle’s area; if it is false, it exits with an
error. To show how to utilize assert in various situations, the function is called twice, once
with positive inputs and once with negative inputs.
Code:
# Function to calculate the area of a rectangle
def calculate_rectangle_area(length, width):
# Assertion to check that the length and width are positive
assert length > 0 and width > 0, "Length and width"+\"must be positive"
# Calculation of the area
area =length *width

Page 40 of 201
CS-33: Programming in Python Ch-2 OOP Using Python

# Return statement
return area
# Calling the function with positive inputs
area1 =calculate_rectangle_area(5, 6)
print("Area of rectangle with length 5 and width 6 is", area1)

# Calling the function with negative inputs


area2 =calculate_rectangle_area(-5, 6)
print("Area of rectangle with length -5 and width 6 is", area2)
Output:
AssertionError: Length and widthmust be positive
2.4.6 Assert with boolean Condition
 In this example, the assert statement checks whether the boolean condition x < y is true. If
the assertion fails, it raises an AssertionError. If the assertion passes, the program continues
and prints the values of x and y.
Code:
# Initializing variables
x =10
y =20

# Asserting a boolean condition


assert x < y

# Printing the values of x and y


print("x =", x)
MJKACC

print("y =", y)
Output:
x = 10
y = 20
2.4.7 Assert Type of Variable in Python
 In this example, the assert statements check whether the types of the variables a and b are
str and int, respectively. If any of the assertions fail, it raises an AssertionError. If both
assertions pass, the program continues and prints the values of a and b.
Code:
# Initializing variables
a ="hello"
b =42
# Asserting the type of a variable
assert type(a) ==str
assert type(b) ==int
# Printing the values of a and b
print("a =", a)
print("b =", b)
Output:
a = hello
b = 42

Page 41 of 201
CS-33: Programming in Python Ch-2 OOP Using Python

2.4.8 Asserting dictionary values


 In this example, the assert statements check whether the values associated with the keys
“apple”, “banana”, and “cherry” in the dictionary my_dict are 1, 2, and 3, respectively. If
any of the assertions fail, it raises an AssertionError. If all assertions pass, the program
continues and prints the contents of the dictionary.
# Initializing a dictionary
my_dict ={"apple": 1, "banana": 2, "cherry": 3}

# Asserting the contents of the dictionary


assert my_dict["apple"] ==1
assert my_dict["banana"] ==2
assert my_dict["cherry"] ==3

# Printing the dictionary


print("My dictionary contains the following key-value pairs:", my_dict)
Output:
My dictionary contains the following key-value pairs:
{'apple': 1, 'banana': 2, 'cherry': 3}
Practical Application
 This has a much greater utility in the Testing and Quality Assurance roles in any
development domain. Different types of assertions are used depending on the application.
Below is a simpler demonstration of a program that only allows only the batch with all hot
food to be dispatched, else rejects the whole batch.
MJKACC

Code:
# Python 3 code to demonstrate
# working of assert
# Application
# initializing list of foods temperatures
batch =[ 40, 26, 39, 30, 25, 21]

# initializing cut temperature


cut =26

# using assert to check for temperature greater than cut


for i in batch:
assert i >=26, "Batch is Rejected"
print(str(i) +" is O.K")
Output:
40 is O.K
26 is O.K
39 is O.K
30 is O.K
 Runtime Exception:AssertionError: Batch is Rejected
2.4.9 Why Use Python Assert Statement?
In Python, the assert statement is a potent debugging tool that can assist in identifying mistakes
and ensuring that your code is operating as intended. Here are several justifications for using
assert:

Page 42 of 201
CS-33: Programming in Python Ch-2 OOP Using Python

1. Debugging: Assumptions made by your code can be verified with the assert statement. You
may rapidly find mistakes and debug your program by placing assert statements throughout
your code.
2. Documentation: The use of assert statements in your code might act as documentation. Assert
statements make it simpler for others to understand and work with your code since they
explicitly describe the assumptions that your code is making.
3. Testing: In order to ensure that certain requirements are met, assert statements are frequently
used in unit testing. You can make sure that your code is working properly and that any
changes you make don’t damage current functionality by incorporating assert statements in
your tests.
4. Security: You can use assert to check that program inputs comply with requirements and
validate them. By doing so, security flaws like buffer overflows and SQL injection attacks may
be avoided.
2.5 Python Classes and Objects
2.5.0 Introduction to OOPs in Python
 Object-oriented programming (OOP) is a programming pattern based on the concept of
objects.
 Objects consist of data and methods. The object's data are its properties, which define what it
is. And the object's methods, are its functions that define what the object can do. Object-
oriented style of programming is very popular because of its ability to map the virtual world
entities i.e., our code, to real-world objects.
 OOPS concepts are widely used by many popular programming languages due to the several
advantages it provides.
 OOPS concepts in Python are very closely related to our real world, where we write programs
to solve our problems. Solving any problem by creating objects is the most popular approach
MJKACC

in programming.
2.5.1 What are OOPS Concepts in Python?
 OOPS in programming stand for Object Oriented Programming System. It is a
programming paradigm or methodology, to design a program using classes and objects OOPS
treats every entity as an object.
 Object-oriented programming in Python is centered on objects. Any code written using
OOPS is to solve our problem but is represented in the form of Objects. We can create as
many objects as we want, for a given class.
 So what are objects? - Objects are anything that has properties and some behaviors. The
properties of objects are often referred to as variables of the object, and behaviors are referred
to as the functions of the objects. Objects can be real-life or logical.
 Suppose, a Pen is a real-life object. The property of a pen includes its color, and type (gel pen
or ball pen). And, the behavior of the pen may include that, it can write, draw, etc.
 Any file in our system is an example of a logical object. Files have properties
like file_name, file_location, file_size and their behaviors include they can hold data, can be
downloaded, shared, etc.
 Python is an object oriented programming language.
 Almost everything in Python is an object, with its properties and methods.
 A Class is like an object constructor, or a "blueprint" for creating objects.

Some Major Benefits of OOPS Include:


1. They reduce the redundancy of the code by writing clear and reusable codes (using
inheritance).

Page 43 of 201
CS-33: Programming in Python Ch-2 OOP Using Python

2. They are easier to visualize because they completely relate to real-world scenarios. For
example, the concept of objects, inheritance, and abstractions, relate very closely to real-
world scenarios (we will discuss them further in this article).
3. Every object in OO PS represent a different part of the code and has its own logic and data
to communicate with each other. So, there are no complications in the code.

2.5.2 Class and Objects in Python


 To create a class, use the keyword class.
 Suppose we wish to store the number of books we have, we can simply do that by using a
variable. Or, say we want to calculate the sum of 5 numbers and store it in a variable.
 Primitive data structures like numbers, strings, and lists are designed to store simple values in
a variable. Suppose, our name, or square of a number, or count of some marbles.
 But what if we need to store the details of all the Employees in your company?
 For example, you may try to store every employee in a list, we may later be confused about
which index of the list represents what details of the employee(e.g. which is the name field,
or the empID etc.)

Example:

employee1 = [‘Anil Makwana', 0805108, "Developer", "Dept. 1A"]


employee2 = ['Kumar Makwana', 211240, "Database Designer", "Dept. 15B"]
employee3 = ['Punit Makwana', 131124, "Manager", "Dept. 1A"]
 Even if we try to store them in a dictionary, after an extent, the whole codebase will be too
complex to handle. So, in these scenarios, we use Classes in python.
 A class is used to create user-defined data structures in Python. Classes define functions,
MJKACC

which are termed methods, that describe the behaviors and actions that an object created from
a class can perform. OOPS concepts in Python majorly deal with classes and objects.
 Classes make the code more manageable by avoiding complex codebases. It does so, by
creating a blueprint or a design of how anything should be defined. It defines what properties
or functions, any object which is derived from the class should have.

IMPORTANT:
 A class just defines the structure of how anything should look. It does not point to anything or
anyone in particular. For example, say, HUMAN is a class, which has suppose -- name, age,
gender, city. It does not point to any specific HUMAN out there, but yes, it explains the
properties and functions any HUMAN should or any object of class HUMAN should have.
 An instance of a class is called the object. It is the implementation of the class and exists in
real.
 An object is a collection of data (variables) and methods (functions) that access the data. It is
the real implementation of a class.
 Example:Consider this example, here Human is a class - It is just a blueprint that defines
how Human should be, and not a real implementation. You may say that "Human" class just
exists logically.
 However, "Shriyansh" is an object of the Human class (please refer to the image given above
for understanding). That means, Shiryansh is created by using the blueprint of
the Human class, and it contains the real data. "Shriyansh" exists physically,
unlike "Human" (which just exists logically). He exists in real, and implements all
the properties of the class Human, such as, Shriyansh have a name, he is 3 years old, he is a
male, and lives in Rajkot. Also, Shriyansh implements all the methods of Human class,
suppose, Shriyansh can walk, speak, eat, and sleep.

Page 44 of 201
CS-33: Programming in Python Ch-2 OOP Using Python

 And many humans can be created using the blueprint of class Human. Such as, we may create
1000s of more humans by referring to the blueprint of the class Human, using objects.
Quick Overview:
 class = blueprint(suppose an architectural drawing). The Object is an actual thing that is built
based on the ‘blueprint’ (suppose a house). An instance is a virtual copy (but not a real copy)
of the object.
 A class is a blueprint for the object.
 We can think of class as an sketch of a parrot with labels. It contains all the details about the
name, colors, size etc. Based on these descriptions, we can study about the parrot. Here,
parrot is an object.
 The example for class of parrot can be :
Example: Class Parrot:
Pass
Here, we use class keyword to define an empty class Parrot. From class, we construct instances. An
instance is a specific object created from a particular class.
 When a class is defined, only the blueprint of the object is created, and no memory is
allocated to the class. Memory allocation occurs only when the object or instance is
created. The object or instance contains real data or information.
 Python is a multi-paradigm programming language. Meaning, it supports different
programming approach.
 One of the popular approach to solve a programming problem is by creating objects. This is
known as Object-Oriented Programming (OOP).
 An object has two characteristics:
o Attributes
o Behavior MJKACC

 Let's take an example:


o Parrot is an object,
o name, age, color are attributes
o singing, dancing are behavior
 The concept of OOP in Python focuses on creating reusable code. This concept is also known
as DRY (Don't Repeat Yourself).
 In Python, the concept of OOP follows some basic principles:
Inheritance A process of using details from a new class without modifying existing class.
Encapsulation Hiding the private details of a class from other objects.
Polymorphism A concept of using common operation in different ways for different data input.
Object
 An object (instance) is an instantiation of a class. When class is defined, only the description
for the object is defined. Therefore, no memory or storage is allocated.
 The example for object of parrot class can be:
o Example: Obj=Parrot()
 Here, obj is object of class Parrot.
 Suppose we have details of parrot. Now, we are going to show how to build the class and
objects of parrot.
 Python is an object oriented programming language. Unlike procedure oriented
programming, where the main emphasis is on functions, object oriented programming stress
on objects.
 Object is simply a collection of data (variables) and methods (functions) that act on those
data. And, class is a blueprint for the object.

Page 45 of 201
CS-33: Programming in Python Ch-2 OOP Using Python

 We can think of class as a sketch (prototype) of a house. It contains all the details about the
floors, doors, windows etc. Based on these descriptions we build the house. House is the
object.
 As, many houses can be made from a description, we can create many objects from a class.
An object is also called an instance of a class and the process of creating this object is
called instantiation
Methods
 Methods are functions defined inside the body of a class. They are used to define the
behaviors of an object.
2.5.3 How to Define a Class in Python?
 Classes in Python can be defined by the keyword class, which is followed by the name of the
class and a colon.
 Syntax:
class Human:
pass

 Indented code below the class definition is considered part of the class body.
 'pass' is commonly used as a placeholder, in the place of code whose implementation we
may skip for the time being. "pass" allows us to run the code without throwing an error in
Python.
 Like function definitions begin with the keyword def, in Python, we define a class using the
keyword class.
 The first string is called docstring and has a brief description about the class. Although not
mandatory, this is recommended.
 Here is a simple class definition. MJKACC

Example:
Class mynewclass:

‘’’ I have a created a new


class’’’

pass

 A class creates a new local namespace where all its attributes are defined. Attributes may be
data or functions.
 There are also special attributes in it that begins with double underscores (__). For example,
__doc__ gives us the docstring of that class.
 As soon as we define a class, a new class object is created with the same name. This class
object allows us to access the different attributes as well as to instantiate new objects of that
class.

Example:
class MyClass:
"This is my second class"
a = 10
def func(self):
print('Hello')
print(MyClass.a)
print(MyClass.__doc__)

Page 46 of 201
CS-33: Programming in Python Ch-2 OOP Using Python

output:10
This is my second class

2.5.4 What is an _init_ Method? Or Constructors in Python


 Class functions that begins with double underscore (__) are called special functions as they
have special meaning.
 Of one particular interest is the __init__() function. This special function gets called
whenever a new object of that class is instantiated.
 This type of function is also called constructors in Object Oriented Programming (OOP). We
normally use it to initialize all the variables.
 The properties that all Human objects must have been defined in a method called init().
Every time a new Human object is created, __init__() sets the initial state of the object by
assigning the values we provide inside the object’s properties. That is, __init__() initializes
each new instance of the class.
 __init__() can take any number of parameters, but the first parameter is always a variable
called self.
 The self parameter is a reference to the current instance of the class. It means,
the self parameter points to the address of the current object of a class, allowing us to access
the data of its(the object's) variables.
 So, even if we have 1000 instances (objects) of a class, we can always get each of their
individual data due to this self because it will point to the address of that particular object and
return the respective value.
Note:
 We can use any name in place of self, but it has to be the first parameter of any function in
the class. see, how to define __init__() in the Human class:
Code:
MJKACC

class Human:
def __init__(self, name, age, gender):
[Link] = name
[Link] = age
[Link] = gender
 In the body of .__init__(), we are using the self variable 3 times, for the following:
o [Link] = 'name' creates an attribute called name and assigns to it the value of the
name parameter.
o [Link] = age attribute is created and assigned to the value of age parameter passed.
o [Link] = gender attribute is created and assigned to the value of gender parameter
passed.

 There are 2 types of attributes in Python:


1. Class Attribute:
 These are the variables that are the same for all instances of the class. They do not have new
values for each new instance created. They are defined just below the class definition.
Code:
class Human:
#class attribute
species = "Homo Sapiens"
 Here, the species will have a fixed value for any object we create.

Page 47 of 201
CS-33: Programming in Python Ch-2 OOP Using Python

2. Instance Attribute:
 Instance attributes are the variables that are defined inside of any function in class. Instance
attributes have different values for every instance of the class. These values depend upon the
value we pass while creating the instance.
Code:
class Human:
#class attribute
species = "Homo Sapiens"
def __init__(self, name, age, gender):
[Link] = name
[Link] = age
[Link] = gender

 Here, name, age, and gender are the instance attributes. They will have different values for
new instances of the class.
 For properties that should have a similar value per instance of a class, use class attributes.
For properties that differ per instance, use instance attributes.

2.5.5 Creating an Object in Class


 When we create a new object from a class, it is called instantiating an object. An object can
be instantiated by the class name followed by the parentheses. We can assign the object of a
class to any variable.
Syntax:
x = ClassName()
 As soon as an object is instantiated, memory is allocated to them. So, if we compare 2
MJKACC

instances of the same class using '==', it will return false(because both will have different
memory assigned).
 We try to create objects of our Human class, then we also need to pass the values for name,
age, and gender.
Code:
class Human:
#class attribute
species = "Homo Sapiens"
def __init__(self, name, age, gender):
[Link] = name
[Link] = age
[Link] = gender
x = Human("Ansh", 15, "Male")
y = Human("Dhingu", 22, "Female")

 Here, we have created 2 objects of the class Human passing all the required arguments.
 Warning: If we do not pass the required arguments, it will throw a TypeError: TypeError:
init() missing 3 required positional arguments: 'name', 'age', and 'gender'.
 Now see, how to access those values using objects of the class. We can access the values of
the instances by using dot notation.
Code:
class Human:
#class attribute
species = "Homo Sapiens"

Page 48 of 201
CS-33: Programming in Python Ch-2 OOP Using Python

def __init__(self, name, age, gender):


[Link] = name
[Link] = age
[Link] = gender

x = Human("Ansh", 15, "Male")


y = Human("Dhingu", 22, "Female")
print([Link])
print([Link])
Output:
Ansh
Dhingu

 So, we find that we can access the instance and class attributes just by using the dot operator.

Code:
class Human:
species = "Homo Sapiens"

def __init__(self, name, age, gender):


[Link] = name
[Link] = age
[Link] = gender
# x and y are instances of class Human
x = Human("Ansh", 1, "male")
y = Human("Dhingu", 7, "female")
MJKACC

print([Link]) # species are class attributes, hence will have same value for all instances
print([Link])
# name, gender and age will have different values per instance, because they are instance
attributes
print(f"Hi! My name is {[Link]}. I am a {[Link]}, and I am {[Link]} years old")
print(f"Hi! My name is {[Link]}. I am a {[Link]}, and I am {[Link]} years old")
Output:
Homo Sapiens
Homo Sapiens
Hi! My name is Ansh. I am a male, and I am 1 years old
Hi! My name is Dhingu. I am a female, and I am 7 years old

 In the above example, we have our class attributes values same "Homo Sapiens", but the
instance attributes values are different as per the value we passed while creating our object.
 However, we can change the value of class attributes, by
[Link] with any new value.
Code:
class Human:
#class attribute
species = "Homo Sapiens"
def __init__(self, name, age, gender):
[Link] = name
[Link] = age
[Link] = gender

Page 49 of 201
CS-33: Programming in Python Ch-2 OOP Using Python

[Link] = "Sapiens"
obj = Human("Dhruvit",8,"Male")
print([Link])
Output:
Sapiens
2.5.6 Instance Methods
 An instance method is a function defined within a class that can be called only from instances
of that class. Like init(), an instance method's first parameter is always self.
 Let's take an example and implement some functions can class Human can perform --
Code:
class Human:
#class attribute
species = "Homo Sapiens"
def __init__(self, name, age, gender):
[Link] = name
[Link] = age
[Link] = gender
#Instance Method
def speak(self):
return f"Hello everyone! I am {[Link]}"
#Instance Method
def eat(self, favouriteDish):
return f"I love to eat {favouriteDish}!!!"
x = Human("AM",37,"Male")
print([Link]()) MJKACC

print([Link]("momos"))

Output:
Hello everyone! I am AM
I love to eat momos!!!

 This Human class has two instance methods:


o speak(): It returns a string displaying the name of the Human.
o eat(): It has one parameter "favouriteDish" and returns a string displaying the favorite
dish of the Human.

 Having gained a thorough knowledge of what Python classes, objects, and methods are, it is
time for us to turn our focus toward the OOP core principles, upon which it is built.

Page 50 of 201
CS-33: Programming in Python Ch-2 OOP Using Python

2.5.7 Fundamentals of OOPS in Python


There are four fundamental concepts of Object-oriented programming –
1. Inheritance
2. Encapsulation
3. Polymorphism
4. Data abstraction

[Link] Inheritance
 People often say to newborn babies that they have got similar facial features to their parents,
or that they have inherited certain features from their parents. It is likely that you too have
noticed that you have inherited some or the other features from your parents.
 Inheritance too is very similar to the real-life scenario. But here, the "child classes" inherit
features from their "parent classes." And the features they inherit here are termed as
"properties" and "methods"!
 Inheritance is the process by which a class can inherit or derive the properties(or data) and
methods(or functions) of another class. Simply, the process of inheriting the properties of a
parent class into a child class is known as inheritance.
 The class whose properties are inherited is the Parent class, and the class that inherits the
properties from the Parent class is the Child class.
 The syntax of inheritance in Python:
Code:
class parent_class:
#body of parent class

class child_class( parent_class): # inherits the parent class


#body of child class
MJKACC

 So, we define a normal class as we were defining in our previous examples. Then, we can
define the child class and mention the parent class name, which it is inheriting in parentheses.
Code:
class Human: #parent class
def __init__(self, name, age, gender):
[Link] = name
[Link] = age
[Link] = gender

def description(self):
print(f"Hey! My name is {[Link]}, I'm a {[Link]} and I'm {[Link]} years old")

class Boy(Human): #child class


def schoolName(self, schoolname):
print(f"I study in {schoolname}")

b = Boy('Chinu', 15, 'male')


[Link]()
[Link]("XYZ School")
Output:
Hey! My name is Chinu, I'm a male and I'm 15 years old
I study in XYZ School

Page 51 of 201
CS-33: Programming in Python Ch-2 OOP Using Python

 In the above example, the child class Boy is inheriting the parent class Human. So, when we
create an object of the Boy class, we can access all the methods and properties of its parent
class, Human, because it is inheriting it.
 Also, we have defined a method in the Boy class, which is schoolName . The
method schoolName cannot be accessed by the parent class object. But, we can obviously
call schoolName method by creating the child class object(Boy).
 Let's see the issue we face if we are trying to call child class's methods using parent class's
object:
Code:
class Human:
def __init__(self,name,age,gender):
[Link] = name
[Link] = age
[Link] = gender
def description(self):
print(f"Hey! My name is {[Link]}, I'm a {[Link]} and I'm {[Link]} years old")

class Girl(Human):
def schoolName(self,schoolName):
print("I study in {schoolName}")

h = Human('Aaru',20,'girl') # h is the object of the parent class - Human


[Link]()
[Link]('ABC Academy') #cannot access child class's method using parent class's
object MJKACC

Output:
Hey! My name is Aaru, I'm a girl and I'm 20 years old

Traceback (most recent call last):


File "<string>", line 16, in <module>
AttributeError: 'Human' object has no attribute 'schoolName'

 So, here we get the AttributeError: 'Human' object has no attribute 'schoolName'. Because the
child classes can access the data and properties of parent class but vice versa is not possible.
[Link].0 Super()
 The super() function in python is a inheritance-related function that refers to the parent class.
We can use it to find the method with a particular name in an object’s superclass. It is a very
useful function. Let us see how it works –
 Syntax: This is the syntax of the super function. We write the super() keyword followed by
the method name we want to refer from our parent class.
super().methodName()
Code:
class Human:
def __init__(self,name,age,gender):
[Link] = name
[Link] = age
[Link] = gender
def description(self):
print(f"Hey! My name is {[Link]}, I'm a {[Link]} and I'm {[Link]} years old")

Page 52 of 201
CS-33: Programming in Python Ch-2 OOP Using Python

def dance(self):
print("I can dance")
class Girl(Human):
def dance(self):
print("I can do classic dance")
def activity(self):
super().dance()
g = Girl('Aaradhya', 20, 'girl')
[Link]()
[Link]()

Output:
Hey! My name is Aaradhya, I'm a girl and I'm 20 years old
I can dance
 Here, we have defined the dance() method in Human and Girl classes. But, both methods
have different implementations as you can see. In Human class, the dance method says "I can
dance", whereas in Girl class, the dance method says "I can do classical dance". So, let us call
the parent class's dance method from the child class.
 We are calling the dance method using super().dance(). This will call the dance method from
the Human class. So, it prints "I can dance". Although, there was already an implementation
for dance() in Girl.
 When we call any method using super(), the method in the superclass will be called even if
there is a method with the same name in the subclass.
[Link] Polymorphism
 Suppose, you are scrolling through your Instagram feeds on your phone. You suddenly felt
MJKACC

like listening to some music as well, so you opened Spotify and started playing your favorite
song. Then, after a while, you got a call, so you paused all the background activities you were
doing, to answer it. It was your friend's call, asking you to text the phone number of some
person. So, you messaged him the number, and resumed your activities.
 Did you notice one thing? You could scroll through feeds, listen to music, attend/make phone
calls, message -- everything just with a single device - your Mobile Phone!
 So, Polymorphism is something similar to that. 'Poly' means multiple and 'morph' means
forms. So, polymorphism altogether means something that has multiple forms. Or, 'some
thing' that can have multiple behaviours depending upon the situation.
 Polymorphism in OOPS refers to the functions having the same names but carrying different
functionalities. Or, having the same function name, but different function
signature(parameters passed to the function).
 A child class inherits all properties from its parent class methods. But sometimes, it wants to
add its own implementation to the methods. There are sample of ways we can
use polymorphism in Python.

Example of Inbuilt Polymorphic Functions


 len() is an example of inbuilt polymorphic function. Because, we can use it to calclate the
length of vaious types like string, list, tuple or dictionary, it will just compute the result and
return.
Code:
print(len('deepa'))
print(len([1,2,5,9]))
print(len({'1':'apple','2':'cherry','3':'banana'}))

Page 53 of 201
CS-33: Programming in Python Ch-2 OOP Using Python

Output:
5
4
3
 Here we have passed a string, list and dictionary to the len function and it computed the
result. So, it is an example of an inbuilt Polymorphic function.
 We also have polymorphism with the '+' addition operator. We can use it to 'add' integers or
floats or any arithmetic addition operation. In the other hand, with String, it performs the
'concatenation' operation.
Code:
x=4+5
y = 'python' + ' programming'
z = 2.5 + 3
print(x)
print(y)
print(z)
Output:
9
python programming
5.5
 So, we can see that a single operator '+' has been used to carry out different operations for
distinct data types.
Polymorphism with Class Methods
 We can perform polymorphism with the class methods. Let's see how:
Code:
MJKACC

class Monkey:
def color(self):
print("The monkey is yellow coloured!")
def eats(self):
print("The monkey eats bananas!")
class Rabbit:
def color(self):
print("The rabbit is white coloured!")
def eats(self):
print("The rabbit eats carrots!")
mon = Monkey()
rab = Rabbit()
for animal in (mon, rab):
[Link]()
[Link]()
Output:
The monkey is yellow coloured!
The monkey eats bananas!
The rabbit is white coloured!
The rabbit eats carrots!

 Here, we can iterate over the objects of Monkey & Rabbit using one variable - animal, and it
can call the instance methods of both of them. So, here one variable animal is used to
represent the behaviour (color() & eats()) of Monkey as well as Rabbit. So, it is following the
rules of Polymorphism!

Page 54 of 201
CS-33: Programming in Python Ch-2 OOP Using Python

[Link].0 Polymorphism with Inheritance


 We can have polymorphism with inheritance as well. It is possible to modify a method in a
child class that it has inherited from the parent class, adding its own implementation to the
method. This process of re-implementing a method in the child class is known as Method
Overriding in Python. Here is an example that shows polymorphism with an inheritance:
Code:
class Shape:
def no_of_sides(self):
pass
def two_dimensional(self):
print("I am a 2D object. I am from shape class")
class Square(Shape):
def no_of_sides(self):
print("I have 4 sides. I am from Square class")
class Triangle(Shape):
def no_of_sides(self):
print("I have 3 sides. I am from Triangle class")
# Create an object of Square class
sq = Square()
# Override the no_of_sides of parent class
sq.no_of_sides()
# Create an object of triangle class
tr = Triangle()
# Override the no_of_sides of parent class
tr.no_of_sides()
Output: MJKACC

I have 4 sides. I am from Square class


I have 3 sides. I am from Triangle class

 Here, the Square and Triangle class has overriden the method of the shape class. So, here the
method no_of_sides has different implementations with respect to different shapes. So, it is in
line with Polymorphism.

[Link] Encapsulation
 You must have seen medicine capsules, where all the medicines remain enclosed inside the
cover of the capsule. Basically, a capsule encapsulates several combinations of medicine.
 Similarly, in programming, the variables and the methods remain enclosed inside a capsule
called the 'class'! Yes, we have learned a lot about classes in Python and we already know
that all the variables and functions we create in OOP remain inside the class.
 The process of binding data and corresponding methods (behavior) together into a single unit
is called encapsulation in Python.
 In other words, encapsulation is a programming technique that binds the class members
(variables and methods) together and prevents them from being accessed by other classes. It
is one of the concepts of OOPS in Python.
 Encapsulation is a way to ensure security. It hides the data from the access of outsiders. An
organization can protect its object/information against unwanted access by clients or any
unauthorized person by encapsulating it.

Page 55 of 201
CS-33: Programming in Python Ch-2 OOP Using Python

2.5.8 Getters and Setters


 We mainly use encapsulation for Data [Link] do so by defining getter and setter
methods for our classes.
 If anyone wants some data, they can only get it by calling the getter method. And, if they
want to set some value to the data, they must use the setter method for that, otherwise, they
won't be able to do the same.
 But internally, how these getter and setter methods are performed remains hidden from the
outside world.
[Link] Code of getter & setter in Encapsulation
class Library:
def __init__(self, id, name):
[Link] = id
[Link] = name

def setBookName(self, newBookName): #setters method to set the book name


[Link] = newBookName

def getBookName(self): #getters method to get the book name


print(f"The name of book is {[Link]}")

book = Library(101,"The Witchers")


[Link]()
[Link]("The Witchers Returns")
[Link]()
Output:
The name of book is The Witchers
MJKACC

The name of book is The Witchers Returns


 In the above example, we defined the getter getBookName() and setter setBookName() to
get and set the names of books respectively. So, now we can only get and set the book names
upon calling the methods, otherwise, we cannot directly get or modify any value. This
promotes high security to our data, because others are not aware at a deep level of how the
following methods are implemented(if their access is restricted).
 We can also promote safety of our data using access modifiers.

[Link] Access Modifiers


 Access modifiers limit access to the variables and methods of a class. Python provides three
types of access modifiers private, public, and protected.
 In Python, we don’t have direct access modifiers like public, private, and protected. We can
achieve this by using single underscore and double underscores.
o Public Member: Accessible anywhere from outside the class.
o Private Member: Accessible only within the class
o Protected Member: Accessible within the class and it's sub-classes
 Single underscore _ represents Protected class. Double underscore __ represents Private
class.
 Suppose we try to make an Employee class:
Code:
class Employee:
def __init__(self, name, employeeId, salary):
[Link] = name #making employee name public
self._empID = employeeId #making employee ID protected

Page 56 of 201
CS-33: Programming in Python Ch-2 OOP Using Python

self.__salary = salary #making salary private

def getSalary(self):
print(f"The salary of Employee is {self.__salary}")

employee1 = Employee("John Gates", 110514, "$1500")


print(f"The Employee's name is {[Link]}")
print(f"The Employee's ID is {employee1._empID}")
print(f"The Employee's salary is {[Link]}") #will throw an error because salary is
defined as private
 Here, we have made the employee's name public, employee's ID protected, and the
employee's salary private. Suppose we try to print all the values. Now, we will be able to
access the employee's name or his ID, but not the salary(because it is private). Look into the
error below:
Output:
The Employee's name is John Gates
The Employee's ID is 110514
Traceback (most recent call last):
File "<string>", line 14, in <module>
AttributeError: 'Employee' object has no attribute 'salary'
 However, we can access the employee's salary by calling that getter method getSalary() we
have created in our Employee class.
Complete code:
class Employee:
def __init__(self, name, employeeId, salary):
[Link] = name #making employee name public
MJKACC

self._empID = employeeId #making employee ID protected


self.__salary = salary #making salary private

def getSalary(self):
print(f"The salary of Employee is {self.__salary}")

employee1 = Employee("John Gates", 110514, "$1500")

print(f"The Employee's name is {[Link]}")


print(f"The Employee's ID is {employee1._empID}")
[Link]() #will be able to access the employee's salary now using the getter
method
Output:
The Employee's name is John Gates
The Employee's ID is 110514
The salary of Employee is $1500

 We can access private members from outside of a class by creating public method to access
private members (As we did above). There is one more method to get access called name
mangling.
 A protected data member is used when inheritance is used and you want the data members to
have access only to the child classes.
 So, encapsulation protects an object from unauthorized access. It allows private and protected
access levels to prevent accidental data modification.

Page 57 of 201
CS-33: Programming in Python Ch-2 OOP Using Python

2.5.9 Abstraction
 It is likely that you are reading this article on your laptop, phone, or tablet. You are also
probably making notes, and highlighting important points, and you may be saving some
points in your internal files while reading it. As you read this, all you see before you is a
'screen' and all this data that is shown to you. As you type, all you see are the keys on the
keyboard and you don't have to worry about the internal details, like how pressing a key may
lead to displaying that word onscreen. Or, how clicking on a button on your screen could
open a new tab!
 So, everything we can see here is at an abstract level. We are not able to see the internal
details, but just the result it is producing(which actually matters to us).
 Abstraction in a similar way just shows us the functionalities anything holds, hiding all the
implementations or inner details.
 The main goal of Abstraction is to hide background details or any unnecessary
implementation about the data so that users only see the required information. It helps in
handling the complexity of the codes.

[Link] Key Points of Abstract Classes


 Abstraction is used for hiding the background details or any unnecessary implementation of
the data, so that users only see the required information.
 In Python, abstraction can be achieved by using abstract classes
 A class that consists of one or more abstract methods is called the "abstract class".
 Abstract methods do not contain any implementation of their own.
 Abstract class can be inherited by any subclass. The subclasses that inherit the abstract
classes provide the implementations for their abstract methods.
 Abstract classes can act like blueprint to other classes, which are useful when we are
MJKACC

designing large functions. And the subclass which inherits them can refer to the abstract
methods for implementing the features.
 Python provides the abc module to use the abstraction

[Link] Syntax of Abstract Class in Python


 To use abstraction, it is mandatory for us to import ABC class from the abc module.
Syntax:
from abc import ABC
class ClassName(ABC):
 ABC stands for Abstract Base class. The abc module provides the base for defining Abstract
Base classes (ABC).
 see the implementation of abstract class:

Page 58 of 201
CS-33: Programming in Python Ch-2 OOP Using Python

Code:
from abc import ABC

class Vehicle(ABC): # inherits abstract class


#abstract method
def no_of_wheels(self):
pass
class Bike(Vehicle):
def no_of_wheels(self): # provide definition for abstract method
print("Bike have 2 wheels")
class Tempo(Vehicle):
def no_of_wheels(self): # provide definition for abstract method
print("Tempo have 3 wheels")
class Truck(Vehicle): # provide definition for abstract method
def no_of_wheels(self):
print("Truck have 4 wheels")

bike = Bike()
bike.no_of_wheels()
tempo = Tempo()
tempo.no_of_wheels()
truck = Truck()
truck.no_of_wheels()

Output:
Bike have 2 wheels MJKACC

Tempo have 3 wheels


Truck have 4 wheels

 Here, we have an abstract class Vehicle. It is abstract because it is inheriting the abstract
class abc. The class Vehicle have an abstract method called no_of_wheels, which do not have
any definition, because abstract methods are not defined(or abstract methods remain empty,
and they expects the classes inheriting the abstract classes to provide the implementation for
the method).
 But, other classes which inherits the Vehicle class, like Bike, Tempo or Truck, defines the
method no_of_wheels, and they provide their own implementation for the abstract method.
Suppose, bike have 2 wheels, so it prints "Bike have 2 wheels" in the inherited abstract
method no_of_wheels. And, similarly, Tempo and Truck classes also provide their own
implementations.

Some notable points on Abstract classes are:


1. Abstract classes cannot be instantiated. In simple words, we cannot create objects for the
abstract classes.
2. An Abstract class can contain the both types of methods -- normal and abstract method. In the
abstract methods, we do not provide any definition or code. But in the normal methods, we
provide the implementation of the code needed for the method.

2.5.10 Advantages of OOPS in Python


 There are numerous advantages of OOPS concepts in Python, making it favorable for writing
serious softwares. Let us look into a few of them --

Page 59 of 201
CS-33: Programming in Python Ch-2 OOP Using Python

1. Effective problem solving because, for each mini-problem, we write a class that does what is
required. And then we can reuse those classes, which makes it even quicker to solve the next
problem.
2. Flexibility of having multiple forms of a single class, through polymorphism
3. Reduced high complexity of code, through abstraction.
4. High security and data privacy through encapsulation.
5. Reuse of code, by the child class inheriting properties of parent class through inheritance.
6. Modularity of code allows us to do easy debugging, instead of looking into hundreds of lines
of code to find a single issue.
2.5.11 Important
1. OOP stands for Object-oriented programming and it deals with objects.
2. POP stands for Procedure Oriented Programming, and it involves a set of procedure to
operate.
3. Class is the blueprint of an object. It is used to declare and create objects. Class is a logical
entity. Example: Car is a class.
4. Object is an instance of class. Object is a physical entity. And we can create as many objects
as we want. Example: Audi, BMW, Maruti, etc are objects of class Car
5. Inheritance is an OOP concept, where existing classes can be modified by a new class. The
existing class is called the base class and the new class is called the derived class.
6. Polymorphism in OOP allows an object to take many forms. Simply, polymorphism allows
us to perform the same action in many different ways.
7. Encapsulation in OOP is the process of wrapping up variables and methods into a single
entity.
8. Abstraction in OOP is a process of hiding the real implementation of the method by only
showing a method signature.
2.6 Python - Sorting Algorithms MJKACC

 Sorting refers to arranging data in a particular format. Sorting algorithm specifies the way to
arrange data in a particular order. Most common orders are in numerical or lexicographical
order.
 The importance of sorting lies in the fact that data searching can be optimized to a very high
level, if data is stored in a sorted manner. Sorting is also used to represent data in more
readable formats. Below we see five such implementations of sorting in python.
 Bubble Sort
 Merge Sort
 Insertion Sort
 Quick sort
 Selection Sort
 Shell sort
2.6.0 Bubble Sort
 It is a comparison-based algorithm in which each pair of adjacent elements is compared and
the elements are swapped if they are not in order.
 Bubble sort is the one usually taught in introductory CS classes since it clearly demonstrates
how sort works while being simple and easy to understand.
 Bubble sort steps through the list and compares adjacent pairs of elements. The elements are
swapped if they are in the wrong order.
 The pass through the unsorted portion of the list is repeated until the list is sorted. Because
Bubble sort repeatedly passes through the unsorted part of the list, it has a worst case
complexity of O(n²).

Page 60 of 201
CS-33: Programming in Python Ch-2 OOP Using Python

Example:
def bubblesort(list):
# Swap the elements to arrange in order
for iter_num in range(len(list)-1,0,-1):
for idx in range(iter_num):
if list[idx]>list[idx+1]:
temp = list[idx]
list[idx] = list[idx+1]
list[idx+1] = temp
list = [19,2,31,45,6,11,121,27]
bubblesort(list)
print(list)
Output:
[2, 6, 11, 19, 27, 31, 45, 121]

2.6.1 Merge Sort


 Merge sort first divides the array into equal halves and then combines them in a sorted
manner.
 Merge Sort is a Divide and Conquer algorithm. It divides input array in two halves, calls itself
for the two halves and then merges the two sorted halves. The merge() function is used for
merging two halves. The merge(arr, l, m, r) is key process that assumes that arr[l..m]
andarr[m+1..r] are sorted and merges the two sorted sub-arrays into one.
 Merge sort is a perfectly elegant example of a Divide and Conquer algorithm. It simple uses
the 2 main steps of such an algorithm:
 Continuously divide the unsorted list until you have N sublists, where each sublist has 1
MJKACC

element that is “unsorted” and N is the number of elements in the original array.
 Repeatedly merge i.e conquer the sublists together 2 at a time to produce new sorted
sublists until all elements have been fully merged into a single sorted array.

Example:
# Python program for implementation of MergeSort
# Merges two subarrays of arr[].
# First subarray is arr[l..m]
# Second subarray is arr[m+1..r]
def merge(arr, l, m, r):
n1 = m - l + 1
n2 = r - m
# create temp arrays
L = [0] * (n1)
R = [0] * (n2)
# Copy data to temp arrays L[] and R[]
for i in range(0, n1):
L[i] = arr[l + i]
for j in range(0, n2):
R[j] = arr[m + 1 + j]
# Merge the temp arrays back into arr[l..r]
i = 0 # Initial index of first subarray
j = 0 # Initial index of second subarray
k = l # Initial index of merged subarray

Page 61 of 201
CS-33: Programming in Python Ch-2 OOP Using Python

while i < n1 and j < n2:


if L[i] <= R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1

# Copy the remaining elements of L[], if there


# are any
while i < n1:
arr[k] = L[i]
i += 1
k += 1
# Copy the remaining elements of R[], if there
# are any
while j < n2:
arr[k] = R[j]
j += 1
k += 1
# l is for left index and r is right index of the
# sub-array of arr to be sorted
def mergeSort(arr, l, r):
if l < r: MJKACC

# Same as (l+r)//2, but avoids overflow for


# large l and h
m = l+(r-l)//2
# Sort first and second halves
mergeSort(arr, l, m)
mergeSort(arr, m+1, r)
merge(arr, l, m, r)
# Driver code to test above
arr = [12, 11, 13, 5, 6, 7]
n = len(arr)
print("Given array is")
for i in range(n):
print("%d" % arr[i],end=" ")
mergeSort(arr, 0, n-1)
print("\n\nSorted array is")
for i in range(n):
print("%d" % arr[i],end=" ")

Output
Given array is
12 11 13 5 6 7
Sorted array is
5 6 7 11 12 13

Page 62 of 201
CS-33: Programming in Python Ch-2 OOP Using Python

2.6.2 Selection Sort


 Selection sort is also quite simple but frequently outperforms bubble sort.
 If you are choosing between the two, it’s best to just default right to selection sort.
 With Selection sort, we divide our input list / array into two parts: the sublist of items already
sorted and the sublist of items remaining to be sorted that make up the rest of the list.
 We first find the smallest element in the unsorted sublist and place it at the end of the sorted
sublist.
 Thus, we are continuously grabbing the smallest unsorted element and placing it in sorted
order in the sorted sublist. This process continues iteratively until the list is fully sorted.
Example:
# Selection sort in Python
# time complexity O(n*n)
#sorting by finding min_index
def selectionSort(array, size):
for ind in range(size):
min_index = ind
for j in range(ind + 1, size):
# select the minimum element in every iteration
if array[j] < array[min_index]:
min_index = j
# swapping the elements to sort the array
(array[ind], array[min_index]) = (array[min_index], array[ind])

arr = [-2, 45, 0, 11, -9,88,-97,-202,747] MJKACC

size = len(arr)
selectionSort(arr, size)
print('The array after sorting in Ascending Order by selection sort is:')
print(arr)
Output
The array after sorting in Ascending Order by selection sort is:
[-202, -97, -9, -2, 0, 11, 45, 88, 747]

2.6.3 Insertion Sort:


 Insertion sort is both faster and well-arguably more simplistic than both bubble sort and
selection sort.
 Funny enough, it’s how many people sort their cards when playing a card game! On each
loop iteration, insertion sort removes one element from the array.
 It then finds the location where that element belongs within another sorted array and
inserts it there. It repeats this process until no input elements remain.
 Insertion sort involves finding the right place for a given element in a sorted list.
 So in beginning we compare the first two elements and sort them by comparing them.
 Then we pick the third element and find its proper position among the previous two sorted
elements.
 This way we gradually go on adding more elements to the already sorted list by putting
them in their proper position.

Page 63 of 201
CS-33: Programming in Python Ch-2 OOP Using Python

Example:
def insertionSort(arr):
n = len(arr) # Get the length of the array

if n <= 1:
return # If the array has 0 or 1 element, it is already sorted, so return

for i in range(1, n): # Iterate over the array starting from the second element
key = arr[i] # Store the current element as the key to be inserted in the right
position
j = i-1
while j >= 0 and key < arr[j]: # Move elements greater than key one position
ahead
arr[j+1] = arr[j] # Shift elements to the right
j -= 1
arr[j+1] = key # Insert the key in the correct position

# Sorting the array [12, 11, 13, 5, 6] using insertionSort


arr = [12, 11, 13, 5, 6]
insertionSort(arr)
print(arr)
Output:
Sorted array is:
[5, 6, 11, 12, 13]

2.6.4 Quick Sort


MJKACC

 We first select an element which we will call the pivot from the array.
 Move all elements that are smaller than the pivot to the left of the pivot; move all elements
that are larger than the pivot to the right of the pivot. This is called the partition operation.
 Recursively apply the above 2 steps separately to each of the sub-arrays of elements with
smaller and bigger values than the last pivot.

Page 64 of 201
CS-33: Programming in Python Ch-2 OOP Using Python

Example:
# Python program for implementation of Quicksort Sort
# This implementation utilizes pivot as the last element in the nums list
# It has a pointer to keep track of the elements smaller than the pivot
# At the very end of partition() function, the pointer is swapped with the pivot
# to come up with a "sorted" nums relative to the pivot
# Function to find the partition position
def partition(array, low, high):
# choose the rightmost element as pivot
pivot = array[high]
# pointer for greater element
i = low - 1
# traverse through all elements
# compare each element with pivot
for j in range(low, high):
if array[j] <= pivot:
# If element smaller than pivot is found
# swap it with the greater element pointed by i
i=i+1
# Swapping element at i with element at j
(array[i], array[j]) = (array[j], array[i])
# Swap the pivot element with the greater element specified by i
(array[i + 1], array[high]) = (array[high], array[i + 1])
# Return the position from where partition is done
MJKACC

return i + 1
# function to perform quicksort
def quickSort(array, low, high):
if low < high:
# Find pivot element such that
# element smaller than pivot are on the left
# element greater than pivot are on the right
pi = partition(array, low, high)
# Recursive call on the left of pivot
quickSort(array, low, pi - 1)
# Recursive call on the right of pivot
quickSort(array, pi + 1, high)
data = [1, 7, 4, 1, 10, 9, -2]
print("Unsorted Array")
print(data)
size = len(data)
quickSort(data, 0, size - 1)
print('Sorted Array in Ascending Order:')
print(data)
Output
Unsorted Array
[1, 7, 4, 1, 10, 9, -2]
Sorted Array in Ascending Order:
[-2, 1, 1, 4, 7, 9, 10]

Page 65 of 201
CS-33: Programming in Python Ch-2 OOP Using Python

2.6.5 Shell Sort


 Shell Sort involves sorting elements which are away from each other.
 We sort a large sub list of a given list and go on reducing the size of the list until all
elements are sorted.
 The below program finds the gap by equating it to half of the length of the list size and
then starts sorting all elements in it. Then we keep resetting the gap until the entire list is
sorted.
Example:
# Python program for implementation of Shell Sort
def shellSort(arr):
# Start with a big gap, then reduce the gap
n = len(arr)
gap = n/2
# Do a gapped insertion sort for this gap size.
# The first gap elements a[0..gap-1] are already in gapped
# order keep adding one more element until the entire array
# is gap sorted
while gap > 0:
for i in range(gap,n):
# add a[i] to the elements that have been gap sorted
# save a[i] in temp and make a hole at position i
temp = arr[i]
# shift earlier gap-sorted elements up until the correct
# location for a[i] is found
MJKACC

j=i
while j >= gap and arr[j-gap] >temp:
arr[j] = arr[j-gap]
j -= gap
# put temp (the original a[i]) in its correct location
arr[j] = temp
gap /= 2
# Driver code to test above
arr = [ 12, 34, 54, 2, 3]
n = len(arr)
print ("Array before sorting:")
for i in range(n):
print(arr[i]),
shellSort(arr)
print ("\nArray after sorting:")
for i in range(n):
print(arr[i]),
Output
Array before sorting:
12 34 54 2 3
Array after sorting:
2 3 12 34 54

Page 66 of 201
CS-33: Programming in Python Ch-2 OOP Using Python

2.7 Searching Algorithms


 Searching is a very basic necessity when we store data in different data structures.
 The simplest approach is to go across every element in the data structure and match it with
the value you are searching for. This is known as Linear search.
 It is inefficient and rarely used, but creating a program for it gives an idea about how we can
implement some advanced search algorithms.
o Linear Search
o Interpolation Search
2.7.0 Linear Search
 A linear search is the most basic kind of search that is performed. So how is it performed? A
linear or sequential search, as the name suggests, is done when we inspect each item in a list
one by one from one end to the other to find a match for what we are searching for. We often
do this in our daily life, say when we are looking through our shopping list to cross out an
item we have picked up.
 In this type of search, a sequential search is made over all items one by one. Every item is
checked and if a match is found then that particular item is returned, otherwise the search
continues till the end of the data structure.
Example:
def linear_search(values, search_for):
search_at = 0
search_res = False
# Match the value with each data element
while search_at < len(values) and search_res is False:
if values[search_at] == search_for:
search_res = TrueMJKACC

else:
search_at = search_at + 1
return search_res
l = [64, 34, 25, 12, 22, 11, 90]
print(linear_search(l, 12))
print(linear_search(l, 91)

Output:When the above code is executed, it produces the following result −


True
False
2.7.1 Interpolation Search
 This search algorithm works on the probing position of the required value.
 For this algorithm to work properly, the data collection should be in a sorted form and
equally distributed. Initially, the examination position is the position of the middle most
item of the collection.
 If a match occurs, then the index of the item is returned. If the middle item is greater than
the item, then the examination position is again calculated in the sub-array to the right of
the middle item.
 Otherwise, the item is searched in the subarray to the left of the middle item. This process
continues on the sub-array as well until the size of subarray reduces to zero.

Page 67 of 201
CS-33: Programming in Python Ch-2 OOP Using Python

There is a specific formula to calculate the middle position which is indicated in the program below.
def intpolsearch(values,x ):
idx0 = 0
idxn = (len(values) - 1)
while idx0 <= idxn and x >= values[idx0] and x <= values[idxn]:

# Find the mid point


mid = idx0 +\int(((float(idxn - idx0)/( values[idxn] - values[idx0]))
* ( x - values[idx0])))

# Compare the value at mid point with search value


if values[mid] == x:
return "Found "+str(x)+" at index "+str(mid)
if values[mid] < x:
idx0 = mid + 1
return "Searched element not in the list"

l = [2, 6, 11, 19, 27, 31, 45, 121]


print(intpolsearch(l, 2))

Output: When the above code is executed, it produces the following result −
Found 2 at index 0

MJKACC

Page 68 of 201
CS-33: Programming in Python Unit-3 Plotting Using PyLab

3.0 Plotting Using PyLab


 PyLab is a Python standard library module that provides many of the facilities of MATLAB,
it is “a high - level technical computing language and interactive environment for algorithm
development, data visualization, data analysis, and numeric computation.”
 While performing some tasks, we have to use graphs like line charts, bar graphs, etc., for
many reasons like to make the task more interactive, to pass the information in a very
interesting way, graphs are easy and self-explanatory, etc. That's why plotting a graph or
chart is a very important and integrated part of many functions.
 Graphs and charts play a very important role in the field of programming, and developers are
always recommended for using graphs in their programs. Therefore, it becomes very
important that we should be aware of how we can plot graphs from a program.
 MATLAB is considered the best to plot graphs and charts, but it is not possible for everyone
to use MATLAB for plotting graphs & charts.
 We have many interactive modules present in Python that allow us to plot graphs and charts
in the output, but here we will talk about the module, which provides us a MATLAB like
namespace by importing functions.
3.0.0 PyLab Module in Python
 PyLab is a Python package that provides us a namespace in Python programming, which is
very similar to MATLAB interface, by importing the functions from Python Numpy and
Matplotlib Module.
 If we talk about these modules' role in the PyLab package, Matplotlib Module provides
functions that help us to create visualizations of data, whereas the Numpy Module provides
efficient numerical vector calculation functions that are based on underlying C and
FORTRAN binary libraries.
3.0.1 PyLab Module: Introduction MJKACC

 PyLab Module is an associated module with the Matplotlib Module of Python, and it gets
installed alongside when we are installing Matplotlib Module in our system. We can also say
that PyLab is a procedural interface of the Matplotlib Module, an object-oriented plotting
library of Python. PyLab in itself is a convincing module for us because its bulky import the
NumPy Module's functions and [Link] package in a single namespace to provide
us a MATLAB-like namespace.
3.0.2 PyLab Module: Installation
 As we have already discussed, the PyLab Module gets installed alongside the installation of
the Matplotlib package. Still, if we want to use this module in a Python program, we should
make sure that Matplotlib Module is present in our system. If Matplotlib is not present in the
system, then we can use the following pip installer command in the command prompt
terminal shell to install Matplotlib Module to get the PyLab Module with it:
1. pip install matplotlib
 Other than this, here PyLab Module also uses the mathematical and vector operation
functions from the Numpy Module. Therefore, we have to make sure that Numpy Module is
also present in our system, and if it is not installed, then we can use the following command
to install the numpy module from the command prompt terminal:

2. pip install numpy


 We have installed all the requisite libraries for the PyLab Module, and now we can use the
PyLab Module in the Python programs to plot graphs and charts from its functions.
 Let’s start with a simple example that uses [Link] to produce two plots.
Executing

Page 69 of 201
CS-33: Programming in Python Unit-3 Plotting Using PyLab

Example:
Import pylab
[Link]()
[Link]([1,2,3,4], [1,7,3,5])
[Link]()

 will cause a window to appear on your computer monitor. Its exact appearance
may depend on the operating system on your machine.

3.0.3 Pylab: What Is It, and Should I Use It?


 Let’s start with a bit of history: John D. Hunter, a neurobiologist, began developing
matplotlib around 2003, originally inspired to emulate commands from Mathworks’
MATLAB software.
 John passed away tragically young at age 44, in 2012, and matplotlib is now a full-fledged
community effort, developed and maintained by a host of others. (John gave a talkabout the
evolution of matplotlib at the 2012 SciPy conference, which is worth a watch.)
 One relevant feature of MATLAB is its global style. The Python concept of importing is not
heavily used in MATLAB, and most of MATLAB’s functions are readily available to the
user at the top level.
 Knowing that matplotlib has its roots in MATLAB helps to explain why pylab exists.
 pylab is a module within the matplotlib library that was built to mimic MATLAB’s global
style. It exists only to bring a number of functions and classes from both NumPy and
matplotlib into the namespace, making for an easy transition for former MATLAB users who
were not used to needing import statements.
 Ex-MATLAB converts liked this functionality, because with from pylab import *, they could
MJKACC

simply call plot() or array() directly, as they would in MATLAB. The issue here may be
apparent to some Python users: using from pylab import * in a session or script is generally
bad practice. Matplotlib now directly advises against this in its own tutorials:
 “[pylab] still exists for historical reasons, but it is highly advised not to use. It pollutes
namespaces with functions that will shadow Python built-ins and can lead to hard-to-track
bugs. To get IPython integration without imports the use of the %matplotlibmagic is
preferred.”
 Internally, there are a ton of potentially conflicting imports being masked within the short
pylab source. In fact, using ipython --pylab (from the terminal/command line)
or %pylab(from IPython/Jupyter tools) simply calls from pylab import * under the hood.
 The bottom line is that matplotlib has abandoned this convenience module and now
explicitly recommends against using pylab, bringing things more in line with one of
Python’s key notions: explicit is better than implicit.
 Without the need for pylab, we can usually get away with just one canonical import:
o >>> import [Link] as plt
 While we’re at it, let’s also import NumPy, which we’ll use for generating data later on, and
call [Link]() to make examples with (pseudo)random data reproducible:
o >>> import numpy as Lt. M. J. Kundaliya Arts & Commerce Mahila College, Rajkot
o >>>[Link](444)
 PyLab is a procedural interface to the Matplotlib object-oriented plotting library. Matplotlib
is the whole package; [Link] is a module in Matplotlib; and PyLab is a module that
gets installed alongside Matplotlib.
 PyLab is a convenience module that bulk imports [Link] (for plotting) and NumPy
(for Mathematics and working with arrays) in a single name space. Although many examples
use PyLab, it is no longer recommended.

Page 70 of 201
CS-33: Programming in Python Unit-3 Plotting Using PyLab

3.0.4 Basic Plotting


 Plotting curves is done with the plot command. It takes a pair of same-length
arrays (or sequences) −
from numpy import *
from pylab import *
x = linspace(-3, 3, 30)
y = x**2
plot(x, y)
show()

 The above line of code generates the following output −

MJKACC

 To plot symbols rather than lines, provide an additional string argument.


symbols - , –, -., , . , , , o , ^ , v , < , > , s , + , x , D , d , 1 , 2 , 3 , 4 , h , H , p , | , _
colors b, g, r, c, m, y, k, w
 Now, consider executing the following code −
from pylab import *
x = linspace(-3, 3, 30)
y = x**2
plot(x, y, 'r.')
show()

Page 71 of 201
CS-33: Programming in Python Unit-3 Plotting Using PyLab

 It plots the red dots as shown below −

 Plots can be overlaid. Just use the multiple plot commands. Use clf() to clear the plot.
from pylab import *
plot(x, sin(x))
plot(x, cos(x), 'r-') MJKACC

plot(x, -sin(x), 'g--')


show()
 The above line of code generates the following output −

Page 72 of 201
CS-33: Programming in Python Unit-3 Plotting Using PyLab

3.0.5 Matplotlib - Object-oriented Interface

 While it is easy to quickly generate plots with the [Link] module, the use of
object-oriented approach is recommended as it gives more control and customization of plots.
Most of the functions are also available in the [Link] class.
 The main idea behind using the more formal object-oriented method is to create figure
objects and then just call methods or attributes off of that object. This approach helps better
in dealing with a canvas that has multiple plots on it.
 In object-oriented interface, Pyplot is used only for a few functions such as figure creation,
and the user explicitly creates and keeps track of the figure and axes objects. At this level, the
user uses Pyplot to create figures, and through those figures, one or more axes objects can be
created. These axes objects are then used for most plotting actions.
 To begin with, we create a figure instance which provides an empty canvas.
o fig = [Link]()

 Now add axes to figure. The add_axes() method requires a list object of 4 elements
corresponding to left, bottom, width and height of the figure. Each number must be between 0
and 1
o ax=fig.add_axes([0,0,1,1])
 Set labels for x and y axis as well as title −

ax.set_title("sine wave")
ax.set_xlabel('angle')
ax.set_ylabel('sine')
MJKACC

 Invoke the plot() method of the axes object.


o [Link](x,y)
 If you are using Jupyter notebook, the %matplotlib inline directive has to be issued; the
otherwistshow() function of pyplot module displays the plot.
 Consider executing the following code:

from matplotlib import pyplot as plt


import numpy as np
import math
x = [Link](0, [Link]*2, 0.05)
y = [Link](x)
fig = [Link]()
ax = fig.add_axes([0,0,1,1])
[Link](x,y)
ax.set_title("sine wave")
ax.set_xlabel('angle')
ax.set_ylabel('sine')
[Link]()

Page 73 of 201
CS-33: Programming in Python Unit-3 Plotting Using PyLab

Output: The above line of code generates the following output −

3.0.6 Matplotlib - Figure Class


MJKACC

 The [Link] module contains the Figure class. It is a top-level container for all plot
elements. The Figure object is instantiated by calling the figure() function from the pyplot
module −

fig = [Link]()

The following table shows the additional parameters −

Figsize (width,height) tuple in inches


Dpi Dots per inches
Facecolor Figure patch facecolor
Edgecolor Figure patch edge color
Linewidth Edge line width

Page 74 of 201
CS-33: Programming in Python Unit-3 Plotting Using PyLab

3.0.7 Matplotlib - Axes Class

 Axes oject is the region of the image with the data space. A given figure can contain many Axes,
but a given Axes object can only be in one Figure. The Axes contains two (or three in the case of
3D) Axis objects. The Axes class and its member functions are the primary entry point to
working with the OO interface.
 Axes object is added to figure by calling the add_axes() method. It returns the axes object and
adds an axes at position rect [left, bottom, width, height] where all quantities are in fractions of
figure width and height.

[Link] Parameter

Following is the parameter for the Axes class −

 rect − A 4-length sequence of [left, bottom, width, height] quantities.


ax=fig.add_axes([0,0,1,1])

The following member functions of axes class add different elements to plot −

[Link] Legend
 The legend() method of axes class adds a legend to the plot figure. It takes three parameters –

[Link](handles, labels, loc)


 Where labels is a sequence of strings and handles a sequence of Line2D or Patch instances. loc
MJKACC

can be a string or an integer specifying the legend location.


Location Location
string code
Best 0
upper right 1
upper left 2
lower left 3
lower right 4
Right 5
Center left 6
Center right 7
lower center 8
upper center 9
Center 10

Page 75 of 201
CS-33: Programming in Python Unit-3 Plotting Using PyLab

[Link] [Link]()
 This is the basic method of axes class that plots values of one array versus another as lines or
markers. The plot() method can have an optional format string argument to specify color, style
and size of line and marker.
[Link] Color codes
Character Color
‘b’ Blue
‘g’ Green
‘r’ Red
‘b’ Blue
‘c’ Cyan
‘m’ Magenta
‘y’ Yellow
‘k’ Black
‘b’ Blue
‘w’ White
[Link] Marker codes
Character Description
MJKACC

‘.’ Point marker


‘o’ Circle marker
‘x’ X marker
‘D’ Diamond marker
‘H’ Hexagon marker
‘s’ Square marker
‘+’ Plus marker
[Link] Line styles
Character Description
‘-‘ Solid line
‘—‘ Dashed line
‘-.’ Dash-dot line
‘:’ Dotted line
‘H’ Hexagon marker

Page 76 of 201
CS-33: Programming in Python Unit-3 Plotting Using PyLab

 Following example shows the advertisement expenses and sales figures of TV and
smartphone in the form of line plots. Line representing TV is a solid line with yellow colour
and square markers whereas smartphone line is a dashed line with green colour and circle
marker.

import [Link] as plt


y = [1, 4, 9, 16, 25,36,49, 64]
x1 = [1, 16, 30, 42,55, 68, 77,88]
x2 = [1,6,12,18,28, 40, 52, 65]
fig = [Link]()
ax = fig.add_axes([0,0,1,1])
l1 = [Link](x1,y,'ys-') # solid line with yellow colour and square marker
l2 = [Link](x2,y,'go--') # dash line with green colour and circle marker
[Link](labels = ('tv', 'Smartphone'), loc = 'lower right') # legend placed at lower right
ax.set_title("Advertisement effect on sales")
ax.set_xlabel('medium')
ax.set_ylabel('sales')
[Link]()

 When the above line of code is executed, it produces the following plot −

MJKACC

Page 77 of 201
CS-33: Programming in Python Unit-3 Plotting Using PyLab

3.0.8 Matplotlib - Multiplots

 In this, we will learn how to create multiple subplots on same canvas.


 The subplot() function returns the axes object at a given grid position. The Call signature of this
function is –
[Link](subplot(nrows, ncols, index)
 In the current figure, the function creates and returns an Axes object, at position index of a grid
of nrows by ncolsaxes. Indexes go from 1 to nrows * ncols, incrementing in row-major
[Link], ncols and index are all less than 10. The indexes can also be given as single,
concatenated, threedigitnumber.
 For example, subplot(2, 3, 3) and subplot(233) both create an Axes at the top right corner of the
current figure, occupying half of the figure height and a third of the figure width.
 Creating a subplot will delete any pre-existing subplot that overlaps with it beyond sharing a
boundary.

import [Link] as plt


# plot a line, implicitly creating a subplot(111)
[Link]([1,2,3])
# now create a subplot which represents the top plot of a grid with 2 rows and 1 column.
#Since this subplot will overlap the first, the plot (and its axes) previously
created, will be removed
[Link](211)
[Link](range(12))
[Link](212, facecolor='y') # creates 2nd subplot with yellow background
[Link](range(12)) MJKACC

The above line of code generates the following output −

Page 78 of 201
CS-33: Programming in Python Unit-3 Plotting Using PyLab

 The add_subplot() function of the figure class will not overwrite the existing plot −

import [Link] as plt


fig = [Link]()
ax1 = fig.add_subplot(111)
[Link]([1,2,3])
ax2 = fig.add_subplot(221, facecolor='y')
[Link]([1,2,3])

 When the above line of code is executed, it generates the following output −

MJKACC

 You can add an insert plot in the same figure by adding another axes object in the same figure
canvas.

import [Link] as plt


import numpy as np
import math
x = [Link](0, [Link]*2, 0.05)
fig=[Link]()
axes1 = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # main axes
axes2 = fig.add_axes([0.55, 0.55, 0.3, 0.3]) # inset axes
y = [Link](x)
[Link](x, y, 'b')
[Link](x,[Link](x),'r')
axes1.set_title('sine')
axes2.set_title("cosine")
[Link]()

Page 79 of 201
CS-33: Programming in Python Unit-3 Plotting Using PyLab

 Upon execution of the above line of code, the following output is generated −

MJKACC

3.0.9 Matplotlib - Subplots() Function

 Matplotlib’spyplot API has a convenience function called subplots() which acts as a utility
wrapper and helps in creating common layouts of subplots, including the enclosing figure object,
in a single call.
[Link](nrows, ncols)
 The two integer arguments to this function specify the number of rows and columns of the
subplot grid. The function returns a figure object and a tuple containing axes objects equal to
nrows*ncols. Each axes object is accessible by its index. Here we create a subplot of 2 rows by 2
columns and display 4 different plots in each subplot.
import [Link] as plt
fig,a = [Link](2,2)
import numpy as np
x = [Link](1,5)
a[0][0].plot(x,x*x)
a[0][0].set_title('square')
a[0][1].plot(x,[Link](x))
a[0][1].set_title('square root')
a[1][0].plot(x,[Link](x))
a[1][0].set_title('exp')
a[1][1].plot(x,np.log10(x))
a[1][1].set_title('log')
[Link]()

Page 80 of 201
CS-33: Programming in Python Unit-3 Plotting Using PyLab

 The above line of code generates the following output −

MJKACC

3.0.10 Matplotlib - Subplot2grid() Function

 This function gives more flexibility in creating an axes object at a specific location of the grid. It
also allows the axes object to be spanned across multiple rows or columns.

Plt.subplot2grid(shape, location, rowspan, colspan)

 In the following example, a 3X3 grid of the figure object is filled with axes objects of varying
sizes in row and column spans, each showing a different plot.

import [Link] as plt


a1 = plt.subplot2grid((3,3),(0,0),colspan = 2)
a2 = plt.subplot2grid((3,3),(0,2), rowspan = 3)
a3 = plt.subplot2grid((3,3),(1,0),rowspan = 2, colspan = 2)
import numpy as np
x = [Link](1,10)
[Link](x, x*x)
a2.set_title('square')
[Link](x, [Link](x))
a1.set_title('exp')
[Link](x, [Link](x))
a3.set_title('log')
plt.tight_layout()
[Link]()

Page 81 of 201
CS-33: Programming in Python Unit-3 Plotting Using PyLab

 Upon execution of the above line code, the following output is generated −

3.0.11 Matplotlib - Grids


MJKACC

 The grid() function of axes object sets visibility of grid inside the figure to on or off. You can
also display major / minor (or both) ticks of the grid. Additionally color, linestyle and linewidth
properties can be set in the grid() function.

import [Link] as plt


import numpy as np
fig, axes = [Link](1,3, figsize = (12,4))
x = [Link](1,11)
axes[0].plot(x, x**3, 'g',lw=2)
axes[0].grid(True)
axes[0].set_title('default grid')
axes[1].plot(x, [Link](x), 'r')
axes[1].grid(color='b', ls = '-.', lw = 0.25)
axes[1].set_title('custom grid')
axes[2].plot(x,x)
axes[2].set_title('no grid')
fig.tight_layout()
[Link]()

Page 82 of 201
CS-33: Programming in Python Unit-3 Plotting Using PyLab

3.0.12 Matplotlib - Formatting Axes

 Sometimes, one or a few points are much larger than the bulk of data. In such a case, the scale of
an axis needs to be set as logarithmic rather than the normal scale. This is the Logarithmic scale.
In Matplotlib, it is possible by setting xscale or vscale property of axes object to ‘log’.
 It is also required sometimes to show some additional distance between axis numbers and axis
label. The labelpad property of either axis (x or y or both) can be set to the desired value.
 Both the above features are demonstrated with the help of the following example. The subplot on
the right has a logarithmic scale and one on left has its x axis having label at more distance.

import [Link] as plt


import numpy as np
fig, axes = [Link](1, 2, figsize=(10,4))
MJKACC

x = [Link](1,5)
axes[0].plot( x, [Link](x))
axes[0].plot(x,x**2)
axes[0].set_title("Normal scale")
axes[1].plot (x, [Link](x))
axes[1].plot(x, x**2)
axes[1].set_yscale("log")
axes[1].set_title("Logarithmic scale (y)")
axes[0].set_xlabel("x axis")
axes[0].set_ylabel("y axis")
axes[0].[Link] = 10
axes[1].set_xlabel("x axis")
axes[1].set_ylabel("y axis")
[Link]()

Page 83 of 201
CS-33: Programming in Python Unit-3 Plotting Using PyLab

 Axis spines are the lines connecting axis tick marks demarcating boundaries of plot area. The
axes object has spines located at top, bottom, left and right.
 Each spine can be formatted by specifying color and width. Any edge can be made invisible if its
color is set to none.
import [Link] as plt
fig = [Link]()
ax = fig.add_axes([0,0,1,1])
[Link]['bottom'].set_color('blue')
[Link]['left'].set_color('red') MJKACC

[Link]['left'].set_linewidth(2)
[Link]['right'].set_color(None)
[Link]['top'].set_color(None)
[Link]([1,2,3,4,5])
[Link]()

Page 84 of 201
CS-33: Programming in Python Unit-3 Plotting Using PyLab

3.0.13 Matplotlib - Setting Limits

 Matplotlib automatically arrives at the minimum and maximum values of variables to be


displayed along x, y (and z axis in case of 3D plot) axes of a plot. However, it is possible to set
the limits explicitly by using set_xlim() and set_ylim() functions.
 In the following plot, the autoscaled limits of x and y axes are shown −

import [Link] as plt


fig = [Link]()
a1 = fig.add_axes([0,0,1,1])
import numpy as np
x = [Link](1,10)
[Link](x, [Link](x))
a1.set_title('exp')
[Link]()

MJKACC

 Now we format the limits on x axis to (0 to 10) and y axis (0 to 10000) −


import [Link] as plt
fig = [Link]()
a1 = fig.add_axes([0,0,1,1])
import numpy as np
x = [Link](1,10)
[Link](x, [Link](x),'r')
a1.set_title('exp')
a1.set_ylim(0,10000)
a1.set_xlim(0,10)
[Link]()

Page 85 of 201
CS-33: Programming in Python Unit-3 Plotting Using PyLab

3.0.14 Matplotlib - Setting Ticks and Tick Labels


MJKACC

 Ticks are the markers denoting data points on axes. Matplotlib has so far - in all our previous
examples - automatically taken over the task of spacing points on the [Link]'s default
tick locators and formatters are designed to be generally sufficient in many common situations.
Position and labels of ticks can be explicitly mentioned to suit specific requirements.
 The xticks() and yticks() function takes a list object as argument. The elements in the list denote
the positions on corresponding action where ticks will be displayed.

ax.set_xticks([2,4,6,8,10])
 This method will mark the data points at the given positions with ticks.
 Similarly, labels corresponding to tick marks can be set by set_xlabels() and set_ylabels()
functions respectively.

ax.set_xlabels([‘two’, ‘four’,’six’, ‘eight’, ‘ten’])


 This will display the text labels below the markers on the x axis.
 Following example demonstrates the use of ticks and labels.
import [Link] as plt
import numpy as np
import math
x = [Link](0, [Link]*2, 0.05)
fig = [Link]()
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # main axes
y = [Link](x)
[Link](x, y)

Page 86 of 201
CS-33: Programming in Python Unit-3 Plotting Using PyLab

ax.set_xlabel(‘angle’)
ax.set_title('sine')
ax.set_xticks([0,2,4,6])
ax.set_xticklabels(['zero','two','four','six'])
ax.set_yticks([-1,0,1])
[Link]()

MJKACC

3.0.15 Matplotlib - Twin Axes

 It is considered useful to have dual x or y axes in a figure. Moreso, when plotting curves with
different units together. Matplotlib supports this with the twinxand twiny functions.
 In the following example, the plot has dual y axes, one showing exp(x) and the other showing
log(x)

import [Link] as plt


import numpy as np
fig = [Link]()
a1 = fig.add_axes([0,0,1,1])
x = [Link](1,11)
[Link](x,[Link](x))
a1.set_ylabel('exp')
a2 = [Link]()
[Link](x, [Link](x),'ro-')
a2.set_ylabel('log')
[Link](labels = ('exp','log'),loc='upper left')
[Link]()

Page 87 of 201
CS-33: Programming in Python Unit-3 Plotting Using PyLab

3.0.16 Matplotlib - Bar Plot

 A bar chart or bar graph is a chart or graph that presents categorical data with rectangular bars
with heights or lengths proportional to the values that they represent. The bars can be plotted
MJKACC

vertically or horizontally.
 A bar graph shows comparisons among discrete categories. One axis of the chart shows the
specific categories being compared, and the other axis represents a measured value.
 Matplotlib API provides the bar() function that can be used in the MATLAB style use as well as
object oriented API. The signature of bar() function to be used with axes object is as follows −

[Link](x, height, width, bottom, align)

 The function makes a bar plot with the bound rectangle of size (x −width = 2; x + width=2;
bottom; bottom + height).
 The parameters to the function are −

sequence of scalars representing the x coordinates of the bars. align


x
controls if x is the bar center (default) or left edge.
height scalar or sequence of scalars representing the height(s) of the bars.
width scalar or array-like, optional. the width(s) of the bars default 0.8
scalar or array-like, optional. the y coordinate(s) of the bars default
bottom
None.
align {‘center’, ‘edge’}, optional, default ‘center’
 The function returns a Matplotlib container object with all bars.

Page 88 of 201
CS-33: Programming in Python Unit-3 Plotting Using PyLab

 Following is a simple example of the Matplotlib bar plot. It shows the number of students
enrolled for various courses offered at an institute.
import [Link] as plt
fig = [Link]()
ax = fig.add_axes([0,0,1,1])
langs = ['C', 'C++', 'Java', 'Python', 'PHP']
students = [23,17,35,29,12]
[Link](langs,students)
[Link]()

MJKACC

 When comparing several quantities and when changing one variable, we might want a bar chart
where we have bars of one color for one quantity value.
 We can plot multiple bar charts by playing with the thickness and the positions of the bars. The
data variable contains three series of four values. The following script will show three bar charts
of four bars. The bars will have a thickness of 0.25 units. Each bar chart will be shifted 0.25 units
from the previous one. The data object is a multidict containing number of students passed in
three branches of an engineering college over the last four years.
import numpy as np
import [Link] as plt
data = [[30, 25, 50, 20],
[40, 23, 51, 17],
[35, 22, 45, 19]]
X = [Link](4)
fig = [Link]()
ax = fig.add_axes([0,0,1,1])
[Link](X + 0.00, data[0], color = 'b', width = 0.25)
[Link](X + 0.25, data[1], color = 'g', width = 0.25)
[Link](X + 0.50, data[2], color = 'r', width = 0.25)

Page 89 of 201
CS-33: Programming in Python Unit-3 Plotting Using PyLab

 The stacked bar chart stacks bars that represent different groups on top of each other. The height
of the resulting bar shows the combined result of the groups.
MJKACC

 The optional bottom parameter of the [Link]() function allows you to specify a starting value
for a bar. Instead of running from zero to a value, it will go from the bottom to the value. The
first call to [Link]() plots the blue bars. The second call to [Link]() plots the red bars, with
the bottom of the blue bars being at the top of the red bars.

import numpy as np
import [Link] as plt
N=5
menMeans = (20, 35, 30, 35, 27)
womenMeans = (25, 32, 34, 20, 25)
ind = [Link](N) # the x locations for the groups
width = 0.35
fig = [Link]()
ax = fig.add_axes([0,0,1,1])
[Link](ind, menMeans, width, color='r')
[Link](ind, womenMeans, width,bottom=menMeans, color='b')
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(ind, ('G1', 'G2', 'G3', 'G4', 'G5'))
ax.set_yticks([Link](0, 81, 10))
[Link](labels=['Men', 'Women'])
[Link]()

Page 90 of 201
CS-33: Programming in Python Unit-3 Plotting Using PyLab

3.0.17 Matplotlib - Histogram

 A histogram is an accurate representation of the distribution of numerical data. It is an estimate


of the probability distribution of a continuous variable. It is a kind of bar graph.
 To construct a histogram, follow these steps –
o Bin the range of values.
o Divide the entire range of values into a series of intervals.
o Count how many values fall into each interval.
 The bins are usually specified as consecutive, non-overlapping intervals of a variable.
MJKACC

 The [Link]() function plots a histogram. It computes and draws the histogram of
x.
Parameters: The following table lists down the parameters for a histogram −
x array or sequence of arrays
bins integer or sequence or ‘auto’, optional
Optional parameters
range The lower and upper range of the bins.
If True, the first element of the return tuple will be the counts normalized to form a
density
probability density
If True, then a histogram is computed where each bin gives the counts in that bin plus
cumulative
all bins for smaller values.
The type of histogram to draw. Default is ‘bar’
 ‘bar’ is a traditional bar-type histogram. If multiple data are given the bars are
arranged side by side.
histtype  ‘barstacked’ is a bar-type histogram where multiple data are stacked on top of
each other.
 ‘step’ generates a lineplot that is by default unfilled.
 ‘stepfilled’ generates a lineplot that is by default filled.

Page 91 of 201
CS-33: Programming in Python Unit-3 Plotting Using PyLab

 Following example plots a histogram of marks obtained by students in a class. Four bins, 0-25,
26-50, 51-75, and 76-100 are defined. The Histogram shows number of students falling in this
range.

from matplotlib import pyplot as plt


import numpy as np
fig,ax = [Link](1,1)
a = [Link]([22,87,5,43,56,73,55,54,11,20,51,5,79,31,27])
[Link](a, bins = [0,25,50,75,100])
ax.set_title("histogram of result")
ax.set_xticks([0,25,50,75,100])
ax.set_xlabel('marks')
ax.set_ylabel('no. of students')
[Link]()

 The plot appears as shown below −

MJKACC

3.0.18 Matplotlib - Pie Chart

 A Pie Chart can only display one series of data. Pie charts show the size of items (called wedge)
in one data series, proportional to the sum of the items. The data points in a pie chart are shown
as a percentage of the whole pie.
 Matplotlib API has a pie() function that generates a pie diagram representing data in an array.
The fractional area of each wedge is given by x/sum(x). If sum(x)< 1, then the values of x give
the fractional area directly and the array will not be normalized. Theresulting pie will have an
empty wedge of size 1 - sum(x).
 The pie chart looks best if the figure and axes are square, or the Axes aspect is equal.

Page 92 of 201
CS-33: Programming in Python Unit-3 Plotting Using PyLab

Parameters: Following table lists down the parameters foe a pie chart −
x array-like. The wedge sizes.
labels list. A sequence of strings providing the labels for each wedge.
A sequence of matplotlibcolorargs through which the pie chart will cycle. If None, will
Colors
use the colors in the currently active cycle.
string, used to label the wedges with their numeric value. The label will be placed inside
Autopct
the wedge. The format string will be fmt%pct.

 Following code uses the pie() function to display the pie chart of the list of students enrolled for
various computer language courses. The proportionate percentage is displayed inside the
respective wedge with the help of autopct parameter which is set to %1.2f%.

from matplotlib import pyplot as plt


import numpy as np
fig = [Link]()
ax = fig.add_axes([0,0,1,1])
[Link]('equal')
langs = ['C', 'C++', 'Java', 'Python', 'PHP']
students = [23,17,35,29,12]
[Link](students, labels = langs,autopct='%1.2f%%')
[Link]()

MJKACC

3.0.19 Matplotlib - Scatter Plot

Page 93 of 201
CS-33: Programming in Python Unit-3 Plotting Using PyLab

 Scatter plots are used to plot data points on horizontal and vertical axis in the attempt to show
how much one variable is affected by another. Each row in the data table is represented by a
marker the position depends on its values in the columns set on the X and Y axes. A third
variable can be set to correspond to the color or size of the markers, thus adding yet another
dimension to the plot.
 The script below plots a scatter diagram of grades range vs grades of boys and girls in two
different colors.

import [Link] as plt


girls_grades = [89, 90, 70, 89, 100, 80, 90, 100, 80, 34]
boys_grades = [30, 29, 49, 48, 100, 48, 38, 45, 20, 30]
grades_range = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
fig=[Link]()
ax=fig.add_axes([0,0,1,1])
[Link](grades_range, girls_grades, color='r')
[Link](grades_range, boys_grades, color='b')
ax.set_xlabel('Grades Range')
ax.set_ylabel('Grades Scored')
ax.set_title('scatter plot')
[Link]()

MJKACC

3.0.20 Matplotlib - Contour Plot

 Contour plots (sometimes called Level Plots) are a way to show a three-dimensional surface on a
two-dimensional plane. It graphs two predictor variables X Y on the y-axis and a response

Page 94 of 201
CS-33: Programming in Python Unit-3 Plotting Using PyLab

variable Z as contours. These contours are sometimes called the z-slices or the iso-response
values.
 A contour plot is appropriate if you want to see how alue Z changes as a function of two inputs X
and Y, such that Z = f(X,Y). A contour line or isoline of a function of two variables is a curve
along which the function has a constant value.
 The independent variables x and y are usually restricted to a regular grid called meshgrid. The
[Link] creates a rectangular grid out of an array of x values and an array of y values.
 Matplotlib API contains contour() and contourf() functions that draw contour lines and filled
contours, respectively. Both functions need three parameters x,y and z.

import numpy as np
import [Link] as plt
xlist = [Link](-3.0, 3.0, 100)
ylist = [Link](-3.0, 3.0, 100)
X, Y = [Link](xlist, ylist)
Z = [Link](X**2 + Y**2)
fig,ax=[Link](1,1)
cp = [Link](X, Y, Z)
[Link](cp) # Add a colorbar to a plot
ax.set_title('Filled Contours Plot')
#ax.set_xlabel('x (cm)')
ax.set_ylabel('y (cm)')
[Link]()

MJKACC

3.0.21 Matplotlib - Quiver Plot

 A quiver plot displays the velocity vectors as arrows with components (u,v) at the points (x,y).
quiver(x,y,u,v)

Page 95 of 201
CS-33: Programming in Python Unit-3 Plotting Using PyLab

 The above command plots vectors as arrows at the coordinates specified in each corresponding
pair of elements in x and y.
Parameters: The following table lists down the different parameters for the Quiver plot −
x 1D or 2D array, sequence. The x coordinates of the arrow locations
y 1D or 2D array, sequence. The y coordinates of the arrow locations
u 1D or 2D array, sequence. The x components of the arrow vectors
v 1D or 2D array, sequence. The y components of the arrow vectors
c 1D or 2D array, sequence. The arrow colors
The following code draws a simple quiver plot −
import [Link] as plt
import numpy as np
x,y = [Link]([Link](-2, 2, .2), [Link](-2, 2, .25))
z = x*[Link](-x**2 - y**2)
v, u = [Link](z, .2, .2)
fig, ax = [Link]()
q = [Link](x,y,u,v)
[Link]()

MJKACC

3.0.22 Matplotlib - Box Plot

 A box plot which is also known as a whisker plot displays a summary of a set of data containing
the minimum, first quartile, median, third quartile, and maximum. In a box plot, we draw a box
from the first quartile to the third quartile. A vertical line goes through the box at the median. The
whiskers go from each quartile to the minimum or maximum.

Page 96 of 201
CS-33: Programming in Python Unit-3 Plotting Using PyLab

 Let’s create the data for the boxplots. We use the [Link]() function to create
the fake data. It takes three arguments, mean and standard deviation of the normal distribution,
and the number of values desired.
[Link](10)
collectn_1 = [Link](100, 10, 200)
collectn_2 = [Link](80, 30, 200)
collectn_3 = [Link](90, 20, 200)
collectn_4 = [Link](70, 25, 200)
 The list of arrays that we created above is the only required input for creating the boxplot. Using
the data_to_plot line of code, we can create the boxplot with the following code −
fig = [Link]()
# Create an axes instance
ax = fig.add_axes([0,0,1,1])
# Create the boxplot
bp = [Link](data_to_plot)
[Link]()
 The above line of code will generate the following output −

MJKACC

3.0.23 Matplotlib - Violin Plot

 Violin plots are similar to box plots, except that they also show the probability density of the data
at different values. These plots include a marker for the median of the data and a box indicating
the interquartile range, as in the standard box plots. Overlaid on this box plot is a kernel density

Page 97 of 201
CS-33: Programming in Python Unit-3 Plotting Using PyLab

estimation. Like box plots, violin plots are used to represent comparison of a variable distribution
(or sample distribution) across different "categories".
 A violin plot is more informative than a plain box plot. In fact while a box plot only shows
summary statistics such as mean/median and interquartile ranges, the violin plot shows the full
distribution of the data.
import [Link] as plt
import numpy as np

[Link](10)
collectn_1 = [Link](100, 10, 200)
collectn_2 = [Link](80, 30, 200)
collectn_3 = [Link](90, 20, 200)
collectn_4 = [Link](70, 25, 200)

## combine these different collections into a list


data_to_plot = [collectn_1, collectn_2, collectn_3, collectn_4]

# Create a figure instance


fig = [Link]()
# Create an axes instance
ax = fig.add_axes([0,0,1,1])
# Create the boxplot
bp = [Link](data_to_plot)
[Link]()

MJKACC

3.0.24 Matplotlib - Three-dimensional Plotting

 Even though Matplotlib was initially designed with only two-dimensional plotting in mind,
some three-dimensional plotting utilities were built on top of Matplotlib's two-dimensional

Page 98 of 201
CS-33: Programming in Python Unit-3 Plotting Using PyLab

display in later versions, to provide a set of tools for three-dimensional data visualization.
Three-dimensional plots are enabled by importing the mplot3d toolkit, included with the
Matplotlib package.
 A three-dimensional axes can be created by passing the keyword projection='3d' to any of the
normal axes creation routines.

from mpl_toolkits import mplot3d


import numpy as np
import [Link] as plt
fig = [Link]()
ax = [Link](projection='3d')
z = [Link](0, 1, 100)
x = z * [Link](20 * z)
y = z * [Link](20 * z)
ax.plot3D(x, y, z, 'gray')
ax.set_title('3D line plot')
[Link]()

 We can now plot a variety of three-dimensional plot types. The most basic three-dimensional plot
is a 3D line plot created from sets of (x, y, z) triples. This can be created using the ax.plot3D
function.

MJKACC

3D scatter plot is generated by using the ax.scatter3D function.

from mpl_toolkits import mplot3d


import numpy as np
import [Link] as plt
fig = [Link]()

Page 99 of 201
CS-33: Programming in Python Unit-3 Plotting Using PyLab

ax = [Link](projection='3d')
z = [Link](0, 1, 100)
x = z * [Link](20 * z)
y = z * [Link](20 * z)
c=x+y
[Link](x, y, z, c=c)
ax.set_title('3d Scatter plot')
[Link]()

MJKACC

3.0.25 Matplotlib - 3D Contour Plot

 The ax.contour3D() function creates three-dimensional contour plot. It requires all the input data
to be in the form of two-dimensional regular grids, with the Z-data evaluated at each point. Here,
we will show a three-dimensional contour diagram of a three-dimensional sinusoidal function.
from mpl_toolkits import mplot3d
import numpy as np
import [Link] as plt
def f(x, y):
return [Link]([Link](x ** 2 + y ** 2))

x = [Link](-6, 6, 30)
y = [Link](-6, 6, 30)

X, Y = [Link](x, y)
Z = f(X, Y)

fig = [Link]()
ax = [Link](projection='3d')

Page 100 of 201


CS-33: Programming in Python Unit-3 Plotting Using PyLab

ax.contour3D(X, Y, Z, 50, cmap='binary')


ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
ax.set_title('3D contour')
[Link]()

MJKACC

3.0.26 Matplotlib - 3D Wireframe plot

 Wireframe plot takes a grid of values and projects it onto the specified three-dimensional surface,
and can make the resulting three-dimensional forms quite easy to visualize.
The plot_wireframe() function is used for the purpose −

from mpl_toolkits import mplot3d


import numpy as np
import [Link] as plt
def f(x, y):
return [Link]([Link](x ** 2 + y ** 2))

x = [Link](-6, 6, 30)
y = [Link](-6, 6, 30)

X, Y = [Link](x, y)
Z = f(X, Y)

fig = [Link]()
ax = [Link](projection='3d')
ax.plot_wireframe(X, Y, Z, color='black')
ax.set_title('wireframe')
[Link]()

Page 101 of 201


CS-33: Programming in Python Unit-3 Plotting Using PyLab

The above line of code will generate the following output −

3.0.27 Matplotlib - 3D Surface plot

 Surface plot shows a functional relationship between a designated dependent variable (Y), and
two independent variables (X and Z). The plot is a companion plot to the contour plot. A surface
plot is like a wireframe plot, but each face of the wireframe is a filled polygon. This can aid
MJKACC

perception of the topology of the surface being visualized. The plot_surface() function x,y and z
as arguments.

from mpl_toolkits import mplot3d


import numpy as np
import [Link] as plt
x = [Link]([Link](-2, 2, 30), [Link](30))
y = [Link]().T # transpose
z = [Link](x ** 2 + y ** 2)

fig = [Link]()
ax = [Link](projection='3d')

ax.plot_surface(x, y, z,cmap='viridis', edgecolor='none')


ax.set_title('Surface plot')
[Link]()

The above line of code will generate the following output −

Page 102 of 201


CS-33: Programming in Python Unit-3 Plotting Using PyLab

3.0.28 Matplotlib - Working With Text

 Matplotlib has extensive text support, including support for mathematical


expressions, TrueType support for raster and vector outputs, newline separated text with
arbitrary rotations, and unicode support. Matplotlib includes its own matplotlib.font_manager
which implements a cross platform, W3C compliant font finding algorithm.
MJKACC

 The user has a great deal of control over text properties (font size, font weight, text location and
color, etc.). Matplotlib implements a large number of TeX math symbols and commands.
 The following list of commands are used to create text in the Pyplot interface −

text Add text at an arbitrary location of the Axes.


Add an annotation, with an optional arrow, at an
annotate
arbitrary location of theAxes.
xlabel Add a label to the Axes’s x-axis.
ylabel Add a label to the Axes’s y-axis.
title Add a title to the Axes.
figtext Add text at an arbitrary location of the Figure.
suptitle Add a title to the Figure.

 All of these functions create and return a [Link]() instance.

Page 103 of 201


CS-33: Programming in Python Unit-3 Plotting Using PyLab

 Following scripts demonstrate the use of some of the above functions −

import [Link] as plt


fig = [Link]()

ax = fig.add_axes([0,0,1,1])

ax.set_title('axes title')
ax.set_xlabel('xlabel')
ax.set_ylabel('ylabel')
[Link](3, 8, 'boxed italics text in data coords', style='italic',
bbox = {'facecolor': 'red'})
[Link](2, 6, r'an equation: $E = mc^2$', fontsize = 15)
[Link](4, 0.05, 'colored text in axes coords',
verticalalignment = 'bottom', color = 'green', fontsize = 15)
[Link]([2], [1], 'o')
[Link]('annotate', xy = (2, 1), xytext = (3, 4),
arrowprops = dict(facecolor = 'black', shrink = 0.05))
[Link]([0, 10, 0, 10])
[Link]()

 The above line of code will generate the following output −

MJKACC

3.0.29 Matplotlib - Mathematical Expressions

Page 104 of 201


CS-33: Programming in Python Unit-3 Plotting Using PyLab

 We can use a subset TeXmarkup in any Matplotlib text string by placing it inside a pair of dollar
signs ($).

# math text
[Link](r'$\alpha > \beta$')

 To make subscripts and superscripts, use the '_' and '^' symbols −

r'$\alpha_i> \beta_i$'

import numpy as np
import [Link] as plt
t = [Link](0.0, 2.0, 0.01)
s = [Link](2*[Link]*t)

[Link](t,s)
[Link](r'$\alpha_i> \beta_i$', fontsize=20)

[Link](0.6, 0.6, r'$\mathcal{A}\mathrm{sin}(2 \omega t)$', fontsize = 20)


[Link](0.1, -0.5, r'$\sqrt{2}$', fontsize=10)
[Link]('time (s)')
[Link]('volts (mV)')
[Link]()

 The above line of code will generate the following output −


MJKACC

3.0.30 Matplotlib - Working with Images

Page 105 of 201


CS-33: Programming in Python Unit-3 Plotting Using PyLab

 The image module in Matplotlib package provides functionalities required for loading, rescaling
and displaying image.
 Loading image data is supported by the Pillow library. Natively, Matplotlib only supports PNG
images. The commands shown below fall back on Pillow if the native read fails.
 The image used in this example is a PNG file, but keep that Pillow requirement in mind for your
own data. The imread() function is used to read image data in an ndarray object of float32
dtype.

import [Link] as plt


import [Link] as mpimg
import numpy as np
img = [Link]('[Link]')

 Assuming that following image named as [Link] is present in the current working
directory.

MJKACC

 Any array containing image data can be saved to a disk file by executing the imsave() function.
Here a vertically flipped version of the original png file is saved by giving origin parameter as
lower.

[Link]("[Link]", img, cmap = 'gray', origin = 'lower')

 The new image appears as below if opened in any image viewer.

 To draw the image on Matplotlib viewer, execute the imshow() function.

imgplot = [Link](img)

3.0.31 Matplotlib - Transforms

Page 106 of 201


CS-33: Programming in Python Unit-3 Plotting Using PyLab

 The matplotlib package is built on top of a transformation framework to easily move between
coordinate systems. Four coordinate systems can be used. The systems are described in brief in
the table given below −

Transformation
Coordinate Description
Object
The user land data coordinate system. controlled by the xlim and
Data [Link]
ylim
The coordinate system of the Axes. (0,0) is bottom left and (1,1) is
Axes [Link]
top right of the axes.
The coordinate system of the Figure. (0,0) is bottom left and (1,1)
Figure [Link]
is top right of the figure
This is the pixel coordinate system of the display. (0,0) is the
bottom left and (width, height) is the top right of display in pixels.
display None
Alternatively, the([Link]()) may
be used instead of None.

 Consider the following example −

[Link](x,y,"my label")

 The text is placed at the theoretical position of a data point (x,y). Thus we would speak of "data
MJKACC

coords".
 Using other transformation objects, placement can be controlled. For example, if the above test is
to be placed in the centre of axes coordinate system, execute the following line of code −

[Link](0.5, 0.5, "middle of graph", transform=[Link])

 These transformations can be used for any kind of Matplotlib objects. The default transformation
for [Link] is [Link] and the default transformation for [Link] is [Link].
 The axes coordinate system is extremely useful when placing text in your axes. You might often
want a text bubble in a fixed location; for example, on the upper left of the axes pane and have
that location remain fixed when you pan or zoom.

Page 107 of 201


CS-33: Programming in Python Unit-3 Plotting Using PyLab

3.1 Plotting Mortgages, an Extended Example


3.1.0 What is Mortgage?
 A mortgage is a loan in which property or real estate is us as collateral.
 The borrowers enters into an agreement with the lender (Usually a bank) wherein the
borrower receives cash upfront then makes payments over a set time span until he pays back
the lender in full.
 A mortgage is often referred to as home loan when it’s used for the purchase of a home.
 Definition: A mortgage is a debt instrument, secured by the guarantee of specified property,
which the borrower is obliged to pay back with a fixed set of payments. In Python, mortgage
follows the same functionality. Means, one class or object will be debt (Mortgage) to get
some functionality for different objects. Logically mortgage is “User Defined Class/
Package/ Module” that is useful to get or set some other functionality.
3.1.1 What are the different types of mortgages?
There are two main types of mortgages:
 Fixed rate: The interest you’re charged stays the same for a number of years, typically
between two to five years.
 Variable rate: The interest you pay can change
Fixed Rate Mortgages
 The interest rate you pay will stay the same throughout the length of the deal no matter what
happens to interest rates.
 You’ll see them advertised as ‘two-year fix’ or ‘five-year fix’, for example, along with the
interest rate charged for that period.
Variable rate mortgages
 The interest rate can change at any time
 Make sure you have some savings set aside so that you can afford an increase in your
MJKACC

payments if rates do rise.


 Variable rate mortgages come in various forms:
Standard Variable rate (SVR)
 This is the normal interest rate your mortgage lender charges homebuyers and it will last as
long as your mortgage or until you take out another mortgage deal.
 Changes in the interest rate might occur after a rise or fall in the base rate set by the Reserve
bank.
Discount mortgages
 This is a discount off the lender’s standard variable rate (SVR) and only applies for a certain
length of time, typically two or three years.
 But it pays to shop around, SVRs differ across lenders, so don’t assume that the biggest the
discount, the lower the interest rate.
Tracker mortgages
 Tracker mortgages move directly in line with another interest rate – normally the Reserve
Bank’s base rate plus a few percent
 So if the base rate goes up by 0.5% our rate will go up by the same amount.
 Usually, they have a short life, typically two to five years, though some lenders offer trackers
which last for the life of our mortgage or until we switch to another deal.
Simple example of Mortgage
“Our program shold be producing plots designed to show how the mortgage behaves over time.”
 Class Mortgage by adding methods that make it convenient to produce such plots.
 The methods plotPayments and plotBalance are simple one-liners, but they do use a form of
[Link] that we have not yet seen. When a figure contains multiple plots, it is useful to
produce a key that identifies what each plot is intendent to represent.

Page 108 of 201


CS-33: Programming in Python Unit-3 Plotting Using PyLab

 Each invocation of [Link] uses the label keyword


 Argument to associate a string with the plot produced by that invocation. (This and other
keyword arguments must follow any format strings.)
 A Key can then be added to the figure by calling the function [Link]
 The nontrivial methods in class Mortgage are plotTotPd and plotNet.
 The method plotTotPd simply plots the cumulative total of the payments made.
 The method plotNet plots an approximation to the total cost of the mortgage over time by
plotting the cash expended minus the equity acquired by paying off part of the loan
import [Link] as plot
class Mortgage(object):
#Abstract class for building different kinds of mortgages
def __init__(self, loan, annRate, months):
#Create a new mortgage”””
[Link] =loan
[Link] = annRate/12.0
[Link] = months
[Link] = [0.0]
[Link] = [loan]
[Link] = findPayment(loan, [Link], months)
[Link] = None #description of mortgage
def makePayment(self):
#Make a payment
[Link]([Link])
reduction = [Link] – [Link][-1]*[Link]
[Link]([Link][-1] – reduction)
def getTotalPaid(self):
MJKACC

#Return the total amount paid so far


return sum([Link])
def __str__(self)”
return [Link]

def plotPayments(self, style):


[Link]([Link], style, label = [Link])
def plotTotPd(self, style):
#plot the cumulative total of the payments made
totPd = [[Link][0]]
for i in range([Link]([Link])):
[Link](totPd[-1] + [Link][i])
[Link](totPd, style, label = [Link])
def plotNet(self, style):
#Plot an approximation to the total cost of the mortgage over time by plotting the cash
exnpended minus the acquired by paying off part of the load
totPd = [[Link][0]]
#Equity acquired through payments is amount of original loan # paid to date, which is
amount of loan minus what is still owed
equityAcquired = [Link]([[Link]]*len([Link])
equityAcquired = equityAcquired – [Link]([Link])
net = [Link](totPd) – equityAcquired
[Link](net, style, label = [Link])
[Link]()

Page 109 of 201


CS-33: Programming in Python Unit-3 Plotting Using PyLab

3.2 Fibonacci Sequences, Revisited:


 Notice that we are computing the same values over and over again.
 For example, fib gets called with 3 three times, and each of these calls provokes four
additional calls of fib. It doesn’t require a genius to think that it might be a good idea to
record the value returned by the first call, and then look it up rather than compute it each time
it is needed.
 This is called memorization, and is the key idea behind dynamic programming. Contains an
implementation of Fibonacci based on this idea. The function fastFib has a parameter, memo
that it uses to keep track of the numbers it has already evaluated.
 The parameter has a default value, the empty dictionary, so that clients of fastFib don’t have
to worry about supplying an initial value for memo. When fastFib is called with an n > 1, it
attempts to look up n in memo. If it is not there (because this is the first time fastFib has been
called with that value), an exception is raised.
 When this happens, fastFib uses the normal Fibonacci recurrence, and then stores the result in
memo.
 In Simple word What is/are Fibonacci numbers / sequence? : It’s a series of numbers in
which each number (Fibonacci number) is the sum of the two preceding nubers.
 The simples is the series, 1,1,2,3,5,8,….etc.
 The mathematical equation describing it is Xn+2 = Xn+1 + Xn
 Here is the python program tgo find the Fibonacci Sereies using recursion. The program takes
the number of terms and determines the Fibonacci series using recursion up to that term. 1
take the number of terms from the user and sore it in a variable.
Problem Solution
1. Take the number of terms from the user and store it in a variable.
MJKACC

2. Pass the number as an argument to a recursive function named Fibonacci.


3. Define the base condition as the number to be lesser than or equal to 1.
4. Otherwise call the function recursively with the argument as the number minus 1 added to the
function called recursively with the argument as the number minus 2.
5. Use a for loop and print the returned value which is the Fibonacci series.
6. Exit.

Example:
def fib(n):
"""Assumes n is an int>= 0
Returns Fibonacci of n"""
if n == 0 or n == 1:
return 1
else:
return fib(n-1) + fib(n-2)
n =int(input (“Enter number of terms:”))
print(“Fibonacci Sequence:”)
for i in range(n):
print(fib(i))
Output:
Enter number of terms:5
Fibonacci Sequence:
1
1
2

Page 110 of 201


CS-33: Programming in Python Unit-3 Plotting Using PyLab

3
5
3.3 Dynamic Programming and the 0/1 Knapsack Problem:
3.3.0 What is Knapsack?
 The knapsack or rucksack problem is a problem in combinatorial optimization: Given a set of
items, each with a weight and a value, determine the number of each item to include in a
collection so that the total weight is less than or equal to a given limit and the total value is as
large as possible.
 Suppose we decide that an approximation is not good enough, i.e., we want the best possible
solution to this problem. Such a solution is called optimal, not surprising since we are solving
an optimization problem. As it happens, this is an instance of a classic optimization problem,
called the 0/1 knapsack problem:
 The 0/1 knapsack problem can be formalized as follows:
1. Each item is represented by a pair,<value, weight>
2. The knapsack can accommodate items with a total weight of no more than w.
3. A vector, L, of length n, is represents the set of available items. Each element of the
vector is an item.
4. A vector, V, of length n, is used to indicate whether or not each item is taken by the
burglar. If V[i] = 1, item L[i] is taken. If V[i]=0, item[i] is note taken.
5. Find a V that maximizes
n=1
Σ V[i] * L[i] value
i=0
subject to the constraint that
n-1
Σ V[i] * L[i].weight <=2
MJKACC

i=0
 Let’s see what happens if we try to implement this formulation of the problem in a
straightforward way:
1. Enumerate all possible combinations of items. That is to say, generate all subsets112
of the set of items. This is called power set.
2. Remove all of the combinations whose weight exceeds the allowed weight.
3. From the remaining combinations choose any one whose value is the largest.
 This approach will certainly find an optimal answer. However, if the original set of items is
large, it will take a very long time to run, because the number of subsets grows exceedingly
quickly with the number of items.
 One of the optimization problems we looked at in the 0/1 knapsack problem.
 Recall that we looked at a greedy algorithm that ran in n log n time, but was not guaranteed to
find an optimal solution.
 We also looked at a brute-force algorithm that was guaranteed to find an optimal solution, but
ran in exponential time.
 Finally, we discussed the fact that the problem is inherently exponential in the size of the
input.
 In the worst case, one cannot find an optimal solution without looking at all possible answers.
 Fortunately, the situation is not as bad as it seems. Dynamic programming provides a
practical method for solving most 0/1 knapsack problems in a reasonable amount of time.
 As a first step in deriving such a solution, we begin with an exponential solution based on
exhaustive enumeration.
 The key idea is to think about exploring the space of possible solutions by constructing a
rooted binary tree that enumerates all states that satisfy the weight constraint.

Page 111 of 201


CS-33: Programming in Python Unit-3 Plotting Using PyLab

 A rooted binary tree is a cyclic directed graph in which there is exactly one node with no
parents.
 This is called the root. Each non-root node has exactly one parent. Each node has at most two
children.
 A childless node is called a leaf. Each node in the search tree for the 0/1 knapsack problem is
labelled with a quadruple that denotes a partial solution to the knapsack problem.
 The elements of the quadruple are: A set of items to be taken, The list of items for which a
decision has not been made, The total value of the items in the set of items to be taken (this is
merely an optimization, since the value could be computed from the set), and The remaining
space in the knapsack. (Again, this is an optimization, since it is merely the difference
between the weight allowed and the weight of all the items taken so far.)
 The tree is built top-down starting with the root. 82 One element is selected from the still-to-
be considered items.
 If there is room for that item in the knapsack, a node is constructed that reflects the
consequence of choosing to take that item. By convention, we draw that node as the left
child.
 The right child shows the consequences of choosing not to take that item.
 The process is then applied recursively until either the knapsack is full or there are no more
items to consider.
 Because each edge represents a decision (to take or not to take an item), such trees are called
decision trees.

Example
#Returns the maximum value that can be stored by the bag
def knapSack(W, wt, val, n): MJKACC

# initial conditions
if n == 0 or W == 0 :
return 0
# If weight is higher than capacity then it is not included
if (wt[n-1] > W):
return knapSack(W, wt, val, n-1)
# return either nth item being included or not
else:
return max(val[n-1] + knapSack(W-wt[n-1], wt, val, n-1),
knapSack(W, wt, val, n-1))
# To test above function
val = [50,100,150,200]
wt = [8,16,32,40]
W = 64
n = len(val)
print (knapSack(W, wt, val, n))

Example: 0/1 knapsack problem using dynamic approach

Page 112 of 201


CS-33: Programming in Python Unit-3 Plotting Using PyLab

# a dynamic approach Returns the maximum value that can be stored by the bag
def knapSack(W, wt, val, n):
K = [[0 for x in range(W + 1)] for x in range(n + 1)]
#Table in bottom up manner
for i in range(n + 1):
for w in range(W + 1):
if i == 0 or w == 0:
K[i][w] = 0
elif wt[i-1] <= w:
K[i][w] = max(val[i-1] + K[i-1][w-wt[i-1]], K[i-1][w])
else:
K[i][w] = K[i-1][w]
return K[n][W]
#Main
val = [50,100,150,200]
wt = [8,16,32,40]
W = 64
n = len(val)
print(knapSack(W, wt, val, n))
3.4 Dynamic Programming and Divide-and-Conquer:
3.4.0 Divide-and-conquer
 Both merge sort and quicksort employ a common algorithmic paradigm based on recursion.
 This paradigm, divide-and-conquer, breaks a problem into subproblems that are similar to the
original problem, recursively solves the subproblems, and finally combines the solutions to the
subproblems to solve the original problem.
 Because divide-and-conquer solves subproblems recursively, each subproblem must be smaller
MJKACC

than the original problem, and there must be a base case for subproblems. You should think of a
divide-and-conquer algorithm as having three parts:
1. Divide the problem into a number of subproblems that are smaller instances of the same
problem.
2. Conquer the subproblems by solving them recursively. If they are small enough, solve
the subproblems as base cases.
3. Combine the solutions to the subproblems into the solution for the original problem.
 Like divide-and-conquer algorithms, dynamic programming is based upon solving
independent subproblems and then combining those solutions. There are, however, some
important differences.
 Divide-and-conquer algorithms are based upon finding subproblems that are substantially
smaller than the original problem.
 For example, merge sort works by dividing the problem size in half at each step.
 In contrast, dynamic programming involves solving problems that are only slightly smaller
than the original problem.
 For example, computing the 19thFibonacci number is not a substantially smaller problem than
computing the 20thFibonacci number.
 Another important distinction is that the efficiency of divide-and-conquer algorithms does not
depend upon structuring the algorithm so that identical problems are solved repeatedly.
 In contrast, dynamic programming is efficient only when the number of distinct subproblems
is significantly smaller than the total number of subproblems.
Divide and Conquer Algorithms:

Page 113 of 201


CS-33: Programming in Python Unit-3 Plotting Using PyLab

 The two sorting algorithms we've seen so far, selection sort and insertion sort, have worst-
case running times of Θ(n2). When the size of the input array is large, these algorithms can
take a long time to run.
 In this tutorial and the next one, we'll see two other sorting algorithms, merge sort and
quicksort, whose running times are better.
 In particular, merge sort runs in Θ(nlgn) time in all cases, and quicksort runs in Θ(nlgn) time
in the best case and on average, though its worst-case running time is Θ(n2). Here's a table of
these four sorting algorithms and their running times.

MJKACC

 Dynamic programming is based upon solving independent subproblems and then combining
those solutions. There are, however, some important differences. Divided-and-conquer
algorithms are based upon finding subproblems that are substantially smaller than the original
problem.
 For example, merge sort works by dividing the problem size in half at each step. In contrast
dynamic programming involves solving problems that are only slightly smaller than the
original problem. The efficiency of divide-and-conquer algorithms does not depend upon
structuring the algorithm so that the same problems are solved repeatedly. In contrast,
dynamic programming is efficient only when the number of distinct subproblems is
significantly smaller than the total number of sub-problems.
 In divide and conquer approach, the problem in hand, is divided into smaller sub-problems
and then each problem is solved independently. When we keep on dividing the subproblems
into even smaller sub-problems, we may eventually reach a stage where no more division is
possible. Thos “atomic” smallest possible sub-problems(fractions) are solved. The solution of
all sub-problems is finally merged in order to obtain the solution of an original problem.
Divide and Conquer uses the Binary Search technique.

Page 114 of 201


CS-33: Programming in Python Unit-3 Plotting Using PyLab

3.5 DYNAMIC PROGRAMMING:


 Dynamic programming was invented by Richard Bellman in the early [Link]’t try to
gather anything about the technique from its name.
 As Bellman described it, the name “dynamic programming” was chosen to hide from
governmental sponsors” the fact that I was really doing mathematics [the phrase dynamic
programming] was something not even a Congressman could object to.”
 Dynamic programming is a method for efficiently solving problems that exhibit the
characteristics of overlapping subproblems and optimal substructure.
 Fortunately, many optimization problems exhibit these characteristics.
 A problem has optimal substructure if a globally optimal solution can be found by combining
MJKACC

optimal solutions to local subproblems.


 We’ve already looked at a number of such problems. Merge sort, for example, exploits the
fact that a list can be sorted by first sorting sub lists and then merging the solutions. A
problem has overlapping subproblems if an optimal solution involves solving the same
problem multiple times. Merge sort does not exhibit this property.
 Even though we are performing a merge many times, we are merging different lists each
time.
 It’s not immediately obvious, but the 0/1 knapsack problem exhibits both of these properties.
Before looking at that, however, we will digress to look at a problem where the optimal
substructure and overlapping subproblems are more.
3.4.1. What is Dynamic Programming?
 Dynamic Programming is mainly an optimization over plain recursion. Wherever we see a
recursive solution that has repeated calls for same inputs, we can optimize it using Dynamic
Programming. The idea is to simply store the results of subproblems, so that we do not have to
re-compute them when needed later. This simple optimization reduces time complexities from
exponential to polynomial.
 For example, if we write simple recursive solution for Fibonacci Numbers, we get exponential
time complexity and if we optimize it by storing solutions of subproblems, time complexity
reduces to linear.

Page 115 of 201


CS-33: Programming in Python Unit-3 Plotting Using PyLab

MJKACC

Page 116 of 201


CS-33: Programming in Python Unit-3 Plotting Using PyLab

Dynamic Programming covers the following concepts:


 Basic Concepts
 Advanced Concepts
 Standard Dynamic Programming problems

[Link] Basic Concepts:


[Link].0 What is memoization?
 The term “Memoization” comes from the Latin word “memorandum” (to remember), which
is commonly shortened to “memo” in American English, and which means “to transform the
results of a function into something to remember.”.
 In computing, memoization is used to speed up computer programs by eliminating the
repetitive computation of results, and by avoiding repeated calls to functions that process the
same input.
1. Why is Memoization used?
 Memoization is a specific form of caching that is used in dynamic programming. The
purpose of caching is to improve the performance of our programs and keep data accessible
that can be used later. It basically stores the previously calculated result of the subproblem
and uses the stored result for the same subproblem. This removes the extra effort to
calculate again and again for the same problem. And we already know that if the same
problem occurs again and again, then that problem is recursive in nature.
2. Where to use Memoization?
 We can use the memoization technique where the use of the previously-calculated
results comes into the picture. This kind of problem is mostly used in the context
of recursion, especially with problems that involve overlapping subproblems.
MJKACC

Example to show where to use memoization:


Let us try to find the factorial of a number.
Below is a recursive method for finding the factorial of a number:
int factorial(unsigned int n)
{
if (n == 0)
return 1;
return n * factorial(n – 1);
}
3. What happens if we use this recursive method?
 If you write the complete code for the above snippet, you will notice that there will be 2
methods in the code:
1. factorial(n)
2. main()
 Now if we have multiple queries to find the factorial, such as finding factorial of 2, 3, 9,
and 5, then we will need to call the factorial() method 4 times:
factorial(2)
factorial(3)
factorial(9)
factorial(5)

Page 117 of 201


CS-33: Programming in Python Unit-3 Plotting Using PyLab

MJKACC

Recursive method to find Factorial


So it is safe to say that for finding factorial of numbers K numbers, the time complexity needed
will be O(N*K)
 O(N) to find the factorial of a particular number, and
 O(K) to call the factorial() method K different times.

4. How Memoization can help with such problems?


If we notice in the above problem, while calculation factorial of 9:
 We are calculating the factorial of 2
 We are also calculating the factorial of 3,
 and We are calculating the factorial of 5 as well
Therefore if we store the result of each individual factorial at the first time of calculation, we can
easily return the factorial of any required number in just O(1) time. This process is known
as Memoization.

5. Solution using Memoization (How does memoization work? ):


 If we find the factorial of 9 first and store the results of individual sub-problems, we can
easily print the factorial of each input in O(1).
 Therefore the time complexity to find factorial numbers using memoization will be O(N)
o O(N) to find the factorial of the largest input
o O(1) to print the factorial of each input.

Page 118 of 201


CS-33: Programming in Python Unit-3 Plotting Using PyLab

[Link].1 Types of Memoization


 The Implementation of memoization depends upon the changing parameters that are
responsible for solving the problem. There are various dimensions of caching that are used
in memoization technique, Below are some of them:
 1D Memoization: The recursive function that has only one argument whose value was not
constant after every function call.
 2D Memoization: The recursive function that has only two arguments whose value was not
constant after every function call.
 3D Memoization: The recursive function that has only three arguments whose values were
not constant after every function call.
[Link].2 How Memoization technique is used in Dynamic Programming?
 Dynamic programming helps to efficiently solve problems that have overlapping
subproblems and optimal substructure properties. The idea behind dynamic programming is
to break the problem into smaller sub-problems and save the result for future use, thus
eliminating the need to compute the result repeatedly.
 There are two approaches to formulate a dynamic programming solution:
o Top-Down Approach: This approach follows the memoization technique. It
consists of recursion and caching. In computation, recursion represents the process
of calling functions repeatedly, whereas cache refers to the process of storing
intermediate results.
o Bottom-Up Approach: This approach uses the tabulation technique to implement
the dynamic programming solution. It addresses the same problems as before, but
without recursion. In this approach, iteration replaces recursion. Hence, there is no
stack overflow error or overhead of recursive procedures.
MJKACC

How Memoization technique is used in Dynamic Programming


[Link].3 How Memoization is different from Tabulation?

Tabulation vs Memoization

Page 119 of 201


CS-33: Programming in Python Unit-3 Plotting Using PyLab

[Link].4 Introduction to Dynamic Programming – Data Structures and Algorithm Tutorials


 Dynamic Programming (DP) is defined as a technique that solves some particular type of
problems in Polynomial Time. Dynamic Programming solutions are faster than the
exponential brute method and can be easily proved their correctness.
Important Topics in Dynamic Programming that we must learn to understand:
 Characteristics of Dynamic Programming Algorithm:
 What is the difference between a Dynamic programming algorithm and recursion?
 Techniques to solve Dynamic Programming Problems:
 Tabulation(Dynamic Programming) vs Memoization:
 How to solve a Dynamic Programming Problem?
 How to solve Dynamic Programming problems through Example?
 Greedy approach vs Dynamic programming
 Some commonly asked problems in Dynamic programming:
 FAQs about Dynamic Programming Algorithm:
 Dynamic Programming is mainly an optimization over plain recursion. Wherever we see a
recursive solution that has repeated calls for the same inputs, we can optimize it using
Dynamic Programming. The idea is to simply store the results of subproblems so that we do
not have to re-compute them when needed later. This simple optimization reduces time
complexities from exponential to polynomial.
[Link].5 Characteristics of Dynamic Programming Algorithm:
 In general, dynamic programming (DP) is one of the most powerful techniques for solving a
certain class of problems.
 There is an elegant way to formulate the approach and a very simple thinking process, and the
coding part is very easy.
 Essentially, it is a simple idea, after solving a problem with a given input, save the result as a
reference for future use, so you won’t have to re-solve it.
MJKACC

 It is a big hint for DP if the given problem can be broken up into smaller sub-problems, and
these smaller subproblems can be divided into still smaller ones, and in this process, we see
some overlapping subproblems.
 Additionally, the optimal solutions to the subproblems contribute to the optimal solution of the
given problem (referred to as the Optimal Substructure Property).
 The solutions to the subproblems are stored in a table or array (memoization) or in a bottom-up
manner (tabulation) to avoid redundant computation.
 The solution to the problem can be constructed from the solutions to the subproblems.
 Dynamic programming can be implemented using a recursive algorithm, where the solutions to
subproblems are found recursively, or using an iterative algorithm, where the solutions are
found by working through the subproblems in a specific order.

Dynamic programming works on following principles:


 Characterize structure of optimal solution, i.e. build a mathematical model of the solution.
 Recursively define the value of the optimal solution.
 Using bottom-up approach, compute the value of the optimal solution for each possible
subproblems.
 Construct optimal solution for the original problem using information computed in the previous
step.

Applications we can built like:


Dynamic programming is used to solve optimization problems. It is used to solve many real-life
problems such as,
(i) Make a change problem
(ii) Knapsack problem

Page 120 of 201


CS-33: Programming in Python Unit-3 Plotting Using PyLab

(iii) Optimal binary search tree


[Link].6 What is the difference between a Dynamic programming algorithm and recursion?
 In dynamic programming, problems are solved by breaking them down into smaller ones to
solve the larger ones, while recursion is when a function is called and executed by itself.
While dynamic programming can function without making use of recursion techniques, since
the purpose of dynamic programming is to optimize and accelerate the process, programmers
usually make use of recursion techniques to accelerate and turn the process efficiently.
 When a function can execute a specific task by calling itself, receive the name of the recursive
function. In order to perform and accomplish the work, this function calls itself when it has to
be executed.
 Using dynamic programming, you can break a problem into smaller parts, called
subproblems, to solve it. Dynamic programming involves solving the problem for the first
time, then using memoization to store the solutions.
 Therefore, the main difference between the two techniques is their intended use; recursion is
used to automate a function, whereas dynamic programming is an optimization technique used
to solve problems.
 Recursive functions recognize when they are needed, execute themselves, then stop working.
When the function identifies the moment it is needed, it calls itself and is executed; this is
called a recursive case. As a result, the function must stop once the task is completed, known as
the base case.
 By establishing states, dynamic programming recognizes the problem and divides it into sub-
problems in order to solve the whole scene. After solving these sub-problems, or variables, the
programmer must establish a mathematical relationship between them. Last but not least, these
solutions and results are stored as algorithms, so they can be accessed in the future without
having to solve the whole problem again.
MJKACC

Below is the implementation for the above approach:


Example

# Python program to Returns the number of arrangements to form 'n'


def solve(n):
# Base case
if(n < 0):
return 0
if(n == 0):
return 1
return solve(n-1)+solve(n-3)+solve(n-5)

 Time Complexity: O(3n), As at every stage we need to take three decisions and the height
of the tree will be of the order of n.
 Auxiliary Space: O(n), The extra space is used due to the recursion call stack.
 The above code seems exponential as it is calculating the same state again and again. So,
we just need to add memoization.

 Adding memoization or tabulation for the state: The simplest portion of a solution based
on dynamic programming is this. Simply storing the state solution will allow us to access it
from memory the next time that state is needed.
 Adding memoization to the below code:

Example

Page 121 of 201


CS-33: Programming in Python Unit-3 Plotting Using PyLab

# Initialize to -1
dp = []

# This function returns the number of


# arrangements to form 'n'
def solve(n):
# base case
if n < 0:
return 0
if n == 0:
return 1

# Checking if already calculated


if dp[n] != -1:
return dp[n]

# Storing the result and returning


dp[n] = solve(n-1) + solve(n-3) + solve(n-5)
return dp[n]

 Time Complexity: O(n), As we just need to make 3n function calls and there will be no
repetitive calculations as we are returning previously calculated results.
 Auxiliary Space: O(n), The extra space is used due to the recursion call stack.

 How to solve Dynamic Programming problems through Example?


 Problem: Let’s find the Fibonacci sequence up to the nth term. A Fibonacci series is the
MJKACC

sequence of numbers in which each number is the sum of the two preceding ones. For
example, 0, 1, 1, 2, 3, and so on. Here, each number is the sum of the two preceding
numbers.
 Naive Approach: The basic way to find the nth Fibonacci number is to use recursion.

Below is the implementation for the above approach:


Example

# Function to find nth fibonacci number


def fib(n):
if (n <= 1):
return n
x = fib(n - 1)
y = fib(n - 2)

return x + y
n = 5;
# Function Call
print(fib(n))

Page 122 of 201


CS-33: Programming in Python Unit-3 Plotting Using PyLab

 Complexity Analysis:
 Time Complexity: O(2n)
 Here, for every n, we are required to make a recursive call to fib(n – 1) and fib(n – 2). For
fib(n – 1), we will again make the recursive call to fib(n – 2) and fib(n – 3). Similarly, for
fib(n – 2), recursive calls are made on fib(n – 3) and fib(n – 4) until we reach the base case.
 During each recursive call, we perform constant work(k) (adding previous outputs to obtain
the current output). We perform 2nK work at every level (where n = 0, 1, 2, …). Since n is
the number of calls needed to reach 1, we are performing 2n-1k at the final level. Total
work can be calculated as:
 If we draw the recursion tree of the Fibonacci recursion then we found the maximum height
of the tree will be n and hence the space complexity of the Fibonacci recursion will be
O(n).
 Efficient approach: As it is a very terrible complexity (Exponential), thus we need to
optimize it with an efficient method. (Memoization)
 Look at the example below for finding the 5th Fibonacci number.

Representation of 5th Fibonacci number


 Observations: MJKACC

 The entire program repeats recursive calls. As in the above figure, for calculating fib(4), we
need the value of fib(3) (first recursive call over fib(3)), and for calculating fib(5), we again
need the value of fib(3)(second similar recursive call over fib(3)).
 Both of these recursive calls are shown above in the outlining circle.
 Similarly, there are many others for which we are repeating the recursive calls.
 Recursion generally involves repeated recursive calls, which increases the program’s time
complexity.
 By storing the output of previously encountered values (preferably in arrays, as these can
be traversed and extracted most efficiently), we can overcome this problem. The next time
we make a recursive call over these values, we will use their already stored outputs instead
of calculating them all over again.
 In this way, we can improve the performance of our code. Memoization is the process of
storing each recursive call’s output for later use, preventing the code from calculating it
again.
 Way to memoize: To achieve this in our example we will simply take an answer array
initialized to -1. As we make a recursive call, we will first check if the value stored in the
answer array corresponding to that position is -1. The value -1 indicates that we haven’t
calculated it yet and have to recursively compute it. The output must be stored in the
answer array so that, next time, if the same value is encountered, it can be directly used
from the answer array.
 Now in this process of memoization, considering the above Fibonacci numbers example, it
can be observed that the total number of unique calls will be at most (n + 1) only.

Page 123 of 201


CS-33: Programming in Python Unit-3 Plotting Using PyLab

 Below is the implementation for the above approach:


Example

# Helper Function
def fibo_helper(n, ans):
# Base case
if (n <= 1):
return n

# To check if output already exists


if (ans[n] is not -1):
return ans[n]

# Calculate output
x = fibo_helper(n - 1, ans)
y = fibo_helper(n - 2, ans)

# Saving the output for future use


ans[n] = x + y

# Returning the final output


return ans[n]

def fibo(n):
ans = [-1]*(n+1) MJKACC

# Initializing with -1
#for (i = 0; i <= n; i++) {
for i in range(0,n+1):
ans[i] = -1
return fibo_helper(n, ans)
# Code
n=5
# Function Call
print(fibo(n))

Complexity analysis:
 Time complexity: O(n)
 Auxiliary Space: O(n)
Optimized approach: Following a bottom-up approach to reach the desired index. This approach
of converting recursion into iteration is known as Dynamic programming(DP).
Observations:
 Finally, what we do is recursively call each response index field and calculate its value using
previously saved outputs.
 Recursive calls terminate via the base case, which means we are already aware of the answers
which should be stored in the base case indexes.
 In the case of Fibonacci numbers, these indices are 0 and 1 as f(ib0) = 0 and f(ib1) = 1. So we
can directly assign these two values into our answer array and then use them to calculate f(ib2),
which is f(ib1) + f(ib0), and so on for each subsequent index.

Page 124 of 201


CS-33: Programming in Python Unit-3 Plotting Using PyLab

 This can easily be done iteratively by running a loop from i = (2 to n). Finally, we get our
answer at the 5th index of the array because we already know that the ith index contains the
answer to the ith value.
 Simply, we first try to find out the dependence of the current value on previous values and then
use them to calculate our new value. Now, we are looking for those values which do not
depend on other values, which means they are independent(base case values, since these, are
the smallest problems
which we are already aware of).
Below is the implementation for the above approach:
Example

# Python3 code for the above approach:


# Function for calculating the nth
# Fibonacci number
def fibo(n):
ans = [None] * (n + 1)

# Storing the independent values in the


# answer array
ans[0] = 0
ans[1] = 1

# Using the bottom-up approach


for i in range(2,n+1):
ans[i] = ans[i - 1] + ans[i - 2]
MJKACC

# Returning the final index


return ans[n]

# Drivers code
n=5
# Function Call
print(fibo(n))

Complexity analysis:
 Time complexity: O(n)
 Auxiliary Space: O(n)
Optimization of above method
 in above code we can see that the current state of any fibonacci number depend only on prev
two number
 so, using this observation, we can conclude that we did not need to store the whole table of size
n but instead of that we can only store the prev two values
 so this way we can optimize the space complexity in the above code O(n) to O(1)
Example

# Python code for the above approach


# Function for calculating the nth Fibonacci number
def fibo(n):
prevPrev, prev, curr = 0, 1, 1
# Using the bottom-up approach

Page 125 of 201


CS-33: Programming in Python Unit-3 Plotting Using PyLab

for i in range(2, n+1):


curr = prev + prevPrev
prevPrev = prev
prev = curr
# Returning the final answer
return curr

# Drivers code
n=5
# Function Call
print(fibo(n))

[Link].7 Greedy approach vs Dynamic programming


Feature Greedy method Dynamic programming
In Dynamic Programming we
In a greedy Algorithm, we make make decision at each step
whatever choice seems best at the considering current problem and
Feasibility
moment in the hope that it will solution to previously solved sub
lead to global optimal solution. problem to calculate optimal
solution.
It is guaranteed that Dynamic
In Greedy Method, sometimes Programming will generate an
Optimality there is no such guarantee of optimal solution as it generally
getting Optimal Solution. considers all possible cases and
MJKACC
then choose the best.
A Dynamic programming is an
A greedy method follows the
algorithmic technique which is
problem-solving heuristic of
Recursion usually based on a recurrent
making the locally optimal choice
formula that uses some previously
at each stage.
calculated states.
It is more efficient in terms of It requires Dynamic Programming
Memoization
memory as it never look back or table for Memoization and it
revise previous choices increases it’s memory complexity.
Greedy methods are generally Dynamic Programming is
Time complexity faster. For example, Dijkstra’s generally slower. For
shortest path algorithm takes example, Bellman Ford
O(ELogV + VLogV) time. algorithm takes O(VE) time.
The greedy method computes its
Dynamic programming computes
solution by making its choices in
its solution bottom up or top
Fashion a serial forward fashion, never
down by synthesizing them from
looking back or revising previous
smaller optimal sub solutions.
choices.
Fractional knapsack .
Example 0/1 knapsack problem

3.4.2 Advanced Concepts:


[Link] Bitmasking and Dynamic Programming | Set 1
 Bitmasking and Dynamic Programming | Set 1 (Count ways to assign unique cap to
every person)
 Consider the below problems statement. There are 100 different types of caps each having a
unique id from 1 to 100. Also, there are ‘n’ persons each having a collection of a variable
number of caps. One day all of these persons decide to go in a party wearing a cap but to

Page 126 of 201


CS-33: Programming in Python Unit-3 Plotting Using PyLab

look unique they decided that none of them will wear the same type of cap. So, count the
total number of arrangements or ways such that none of them is wearing the same type of
cap. Constraints: 1 <= n <= 10 Example:
 The first line contains the value of n, next n lines contain collections of all the n persons.

 What is Bitmasking?
 Suppose we have a collection of elements which are numbered from 1 to N. If we want to
represent a subset of this set then it can be encoded by a sequence of N bits (we usually call
this sequence a “mask”). In our chosen subset the i th element belongs to it if and only if
the i-th bit of the mask is set i.e., it equals to 1. For example, the mask 10000101 means
that the subset of the set [1… 8] consists of elements 1, 3 and 8. We know that for a set of
N elements there are total 2 N subsets thus 2N masks are possible, one representing each
subset. Each mask is, in fact, an integer number written in binary notation.
 Our main methodology is to assign a value to each mask (and, therefore, to each subset)
and thus calculate the values for new masks using values of the already computed masks.
 Usually our main target is to calculate value/solution for the complete set i.e., for mask
11111111. Normally, to find the value for a subset X we remove an element in every
possible way and use values for obtained subsets X’1, X’2…,X’k to compute the
value/solution for X. This means that the values for X’i must have been computed already,
so we need to establish an ordering in which masks will be considered.
 It’s easy to see that the natural ordering will do: go over masks in increasing order of
corresponding numbers. Also, We sometimes, start with the empty subset X and we add
elements in every possible way and use the values of obtained subsets X’1, X’2…,X’k to
compute the value/solution for X. We mostly use the following notations/operations on
masks: bit(i, mask) – the i-th bit of mask count(mask) – the number of non-zero bits in the
mask first(mask) – the number of the lowest non-zero bit in the mask set(i, mask) – set the
MJKACC

ith bit in the mask check(i, mask) – check the ith bit in the mask
 How is this problem solved using Bitmasking + DP? The idea is to use the fact that there
are upto 10 persons. So we can use an integer variable as a bitmask to store which person is
wearing a cap and which is not.

 Let i be the current cap number (caps from 1 to i-1 are already processed). Let integer
variable mask indicates that the persons wearing and not wearing caps. If i'th bit is set in
mask, then
 i'th person is wearing a cap, else not.
// consider the case when ith cap is not included
// in the arrangement
countWays(mask, i) = countWays(mask, i+1) +
// when ith cap is included in the arrangement
// so, assign this cap to all possible persons
// one by one and recur for remaining persons.
? countWays(mask | (1 << j), i+1)
for every person j that can wear cap i
 Note that the expression "mask | (1 << j)" sets j'th bit in mask.
 And a person can wear cap i if it is there in the person's cap list provided as input.
 If we draw the complete recursion tree, we can observe that many subproblems are solved
again and again. So we use Dynamic Programming. A table dp[][] is used such that in every
entry dp[i][j], i is mask and j is cap number. Since we want to access all persons that can
wear a given cap, we use an array of vectors, capList[101]. A value capList[i] indicates the
list of persons that can wear cap i.

Page 127 of 201


CS-33: Programming in Python Unit-3 Plotting Using PyLab

[Link] Bitmasking and Dynamic Programming | Set-2 (TSP)

 Bitmasking and Dynamic Programming | Travelling Salesman Problem


 Here, we will be using our knowledge of dynamic programming and Bitmasking technique
to solve one of the famous NP-hard problem “Traveling Salesman Problem”.
Before solving the problem, we assume that the reader has the knowledge of
 DP and formation of DP transition relation
 Bitmasking in DP
 Traveling Salesman problem
 To understand this concept lets consider the below problem :
Problem Description:
Given a 2D grid of characters representing
a town where '*' represents the
houses, '#' represents the blockage,
'.' represents the vacant street
area. Currently you are (0, 0) position.

Our task is to determine the minimum distance


to be moved to visit all the houses and return
to our initial position at (0, 0). You can
only move to adjacent cells that share exactly
1 edge with the current cell.
 The above problem is the well-known Travelling Salesman Problem.
 The first part is to calculate the minimum distance between the two cells. We can do it by
simply using a BFS as all the distances are unit distance. To optimize our solution we will
MJKACC

be pre-calculating the distances taking the initial location and the location of the houses as
the source point for our BFS.
 Each BFS traversal takes O(size of grid) time. Therefore, it is O(X * size_of_grid) for
overall pre-calculation, where X = number of houses + 1 (initial position) Now let’s think
of a DP state. So we will be needing to track the visited houses and the last visited house to
uniquely identify a state in this problem.
 Therefore, we will be taking dp[index][mask] as our DP state.
 Here,
index : tells us the location of current house
 mask : tells us the houses that are visited ( if ith bit is set in mask then this means that the
ith dirty tile is cleaned).
 Whereas dp[index][mask] will tell us the minimum distance to visit X(number of set bits in
mask) houses corresponding to their order of their occurrence in the mask where the last
visited house is house at location index.
 State transition relation:
 So our initial state will be dp[0][0] this tells that we are currently at initial tile that is our
initial location and mask is 0 that states that no house is visited till now.
 And our final destination state will be dp[any index][LIMIT_MASK], here
LIMIT_MASK = (1<<N) – 1 and N = number of houses. Therefore our DP state transition
can be stated as :
dp(curr_idx)(curr_mask) = min{
for idx : off_bits_in_curr_mask
dp(idx)(cur_mask.set_bit(idx)) + dist[curr_idx][idx]
}

Page 128 of 201


CS-33: Programming in Python Unit-3 Plotting Using PyLab

The above relation can be visualized as the minimum distance to visit all the houses by
standing at curr_idx house and by already visiting cur_mask houses is equal to min of
distance between the curr_idx house and idx house + minimum distance to visit all the
houses by standing at idx house and by already visiting ( cur_mask | (1 <<idx) ) houses.
 So, here we iterate over all possible idx values such that cur_mask has i th bit as 0 that tells
us that ith house is not visited.
 Whenever we have our mask = LIMIT_MASK, this means that we have visited all the
houses in the town. So, we will add the distance from the last visited town (i.e the town at
cur_idx position) to the initial position (0, 0).
 The C++ program for the above implementation is given below:
The given grid :
.....*.
...#...
.*.#.*.
.......
Minimum distance for the given grid : 16
The given grid :
...#...
...#.*.
...#...
.*.#.*.
...#...
Minimum distance for the given grid : not possible
Example

import sys MJKACC

import math
from collections import deque
INF = 99999999
MAXR = 12
MAXC = 12
MAXMASK = 2048
MAXHOUSE = 12
# stores distance taking source
# as every dirty tile
dist = [[[INF for _ in range(MAXHOUSE)]
for _ in range(MAXC)] for _ in range(MAXR)]

# memoization for dp states


dp = [[-1 for _ in range(MAXMASK)] for _ in range(MAXHOUSE)]

# stores coordinates for


# dirty tiles
dirty = []

# Directions
X = [-1, 0, 0, 1]
Y = [0, 1, -1, 0]

arr = [['' for _ in range(21)] for _ in range(21)]

Page 129 of 201


CS-33: Programming in Python Unit-3 Plotting Using PyLab

# len : number of dirty tiles + 1 # limit : 2 ^ len -1


# r, c : number of rows and columns
len, limit, r, c = 0, 0, 0, 0

# Returns true if current position # is safe to visit # else returns false


# Time Complexity : O(1)

def safe(x, y):


if x >= r or y >= c or x < 0 or y < 0:
return False
if arr[x][y] == '#':
return False
return True

# runs BFS traversal at tile idx # calculates distance to every cell # in the grid
# Time Complexity : O(r*c)

def getDist(idx):
# visited array to track visited cells
vis = [[False for _ in range(21)] for _ in range(21)]

# getting current position


cx, cy = dirty[idx]

# initializing queue for bfs MJKACC

pq = deque()
[Link]((cx, cy))

# initializing the dist to max # because some cells cannot be visited


# by taking source cell as idx
for i in range(r+1):
for j in range(c+1):
dist[i][j][idx] = INF

# base conditions
vis[cx][cy] = True
dist[cx][cy][idx] = 0

while pq:
x = [Link]()
for i in range(4):
cx = x[0] + X[i]
cy = x[1] + Y[i]
if safe(cx, cy):
if vis[cx][cy]:
continue
vis[cx][cy] = True
dist[cx][cy][idx] = dist[x[0]][x[1]][idx] + 1
[Link]((cx, cy))

Page 130 of 201


CS-33: Programming in Python Unit-3 Plotting Using PyLab

# Dynamic Programming state transition recursion


# with memoization. Time Complexity: O(n*n*2 ^ n)

def solve(idx, mask):


# goal state
if mask == limit:
return dist[0][0][idx]

# if already visited state


if dp[idx][mask] != -1:
return dp[idx][mask]
ret = float('inf')
# state transition relation
for i in range(len):
if (mask & (1 << i)) == 0:
new_mask = mask | (1 << i)
ret = min(ret, solve(i, new_mask) +
dist[dirty[i][0]][dirty[i][1]][idx])

# adding memoization and returning


dp[idx][mask] = ret
return ret
def init():
global dirty, dirty_count, arr, r, c, LIMIT_MASK
dirty = [] MJKACC

dirty_count = 0 # initialize the variable before using


for i in range(r):
for j in range(c):
if (arr[i][j] == '*'):
[Link]((i, j))
dirty_count += 1
dirty_length = dirty_count
LIMIT_MASK = (1 << dirty_count) - 1

if __name__ == "__main__":
# Test case #1:
# .....*.
# ...#...
# .*.#.*.
# .......

A = [['.', '.', '.', '.', '.', '*', '.'],


['.', '.', '.', '#', '.', '.', '.'],
['.', '*', '.', '#', '.', '*', '.'],
['.', '.', '.', '.', '.', '.', '.']
]

r=4
c=7

Page 131 of 201


CS-33: Programming in Python Unit-3 Plotting Using PyLab

print("The given grid : ")


for i in range(r):
for j in range(c):
print(A[i][j], end=' ')
arr[i][j] = A[i][j]
print()

# - initialization # - precalculations
init()
ans = solve(0, 1)
print("Minimum distance for the given grid : ", end='')
print(ans)

# Test Case #2
# ...#...
# ...#.*.
# ...#...
# .*.#.*.
# ...#...

Arr = [['.', '.', '.', '#', '.', '.', '.'],


['.', '.', '.', '#', '.', '*', '.'],
['.', '.', '.', '#', '.', '.', '.'],
['.', '*', '.', '#', '.', '*', '.'],
['.', '.', '.', '#', '.', '.', '.'] MJKACC

]
r=5
c=7
print("The given grid : ")
for i in range(r):
for j in range(c):
print(Arr[i][j], end=' ')
arr[i][j] = Arr[i][j]
print()

# - initialization # - precalculations
init()
ans = solve(0, 1)
print("Minimum distance for the given grid : ", end='')
if ans >= INF:
print("not possible")
else:
print(ans)

Output:
The given grid :
.....*.
...#...
.*.#.*.
.......

Page 132 of 201


CS-33: Programming in Python Unit-3 Plotting Using PyLab

Minimum distance for the given grid : 16


The given grid :
...#...
...#.*.
...#...
.*.#.*.
...#...
Minimum distance for the given grid : not possible
 Note:We have used the initial state to be dp[0][1] because we have pushed the start
location at the first position in the container of houses. Hence, our Bit Mask will be 1 as the
0th bit is set i.e we have visited the starting location for our trip.
[Link] Digit DP | Introduction
 There are many types of problems that ask to count the number of integers ‘x‘ between two
integers say ‘a‘ and ‘b‘ such that x satisfies a specific property that can be related to its
digits.
 So, if we say G(x) tells the number of such integers between 1 to x (inclusively), then the
number of such integers between a and b can be given by G(b) – G(a-1). This is when
Digit DP (Dynamic Programming) comes into action. All such integer counting problems
that satisfy the above property can be solved by digit DP approach.
Key Concept:
 Let given number x has n digits. The main idea of digit DP is to first represent the digits as an
array of digits t[]. Let’s say a we have tntn-1tn-2 … t2t1 as the decimal representation where ti (0
< i <= n) tells the i-th digit from the right. The leftmost digit tn is the most significant digit.
 Now, after representing the given number this way we generate the numbers less than the given
number and simultaneously calculate using DP, if the number satisfy the given property.
We start generating integers having number of digits = 1 and then till number of digits = n.
MJKACC

Integers having less number of digits than n can be analyzed by setting the leftmost digits to
be zero.
Example Problem :
 Given two integers a and b. Your task is to print the sum of all the digits appearing
in the integers between a and b.
 For example if a = 5 and b = 11, then answer is 38 (5 + 6 + 7 + 8 + 9 + 1 + 0 + 1 +
1)
 Constraints : 1 <= a < b <= 10^18
 Now we see that if we have calculated the answer for state having n-1 digits, i.e., tn-
1 tn-2 … t2 t1 and we need to calculate answer for state having n digits tn tn-1 tn-2 …
t2 t1. So, clearly, we can use the result of the previous state instead of re-calculating
it. Hence, it follows the overlapping property.
 Let’s think for a state for this DP
 Our DP state will be dp(idx, tight, sum)
1) idx
 It tells about the index value from right in the given integer
2) tight
 This will tell if the current digits range is restricted or not. If the current digit’s
range is not restricted then it will span from 0 to 9 (inclusively) else it will span
from 0 to digit[idx] (inclusively).
Example: consider our limiting integer to be 3245 and we need to calculate G(3245)
index : 4 3 2 1
digits : 3 2 4 5

Page 133 of 201


CS-33: Programming in Python Unit-3 Plotting Using PyLab

 Unrestricted range: Now suppose the integer generated till now is: 3 1 * * (* is empty
place, where digits are to be inserted to form the integer).
index: 4 3 2 1
digits : 3 2 4 5
generated integer: 3 1 _ _
 Here, we see that index 2 has unrestricted range. Now index 2 can have digits from range 0
to 9(inclusively).
 For unrestricted range tight = 0
 Restricted range:
Now suppose the integer generated till now is : 3 2 * * ( ‘*’ is an empty place, where digits
are to be inserted to form the integer).
index : 4 3 2 1
digits : 3 2 4 5
generated integer: 3 2 _ _
 Here, we see that index 2 has a restricted range. Now index 2 can only have digits from
range 0 to 4 (inclusively)
For restricted range tight = 1
3) sum
 This parameter will store the sum of digits in the generated integer from msd to idx.
 Max value for this parameter sum can be 9*18 = 162, considering 18 digits in the integer

[Link] Sum over Subsets | Dynamic Programming


1. Prerequisite: Basic Dynamic Programming, Bitmasks
Consider the following problem where we will use Sum over subset Dynamic Programming
to solve it.
Given an array of 2n integers, we need to calculate function F(x) = ?A i such that x&i==i for
MJKACC

all x. i.e, i is a bitwise subset of x. i will be a bitwise subset of mask x, if x&i==i.


Examples:
Input: A[] = {7, 12, 14, 16} , n = 2
Output: 7, 19, 21, 49

Explanation: There will be 4 values of x: 0,1,2,3


So, we need to calculate F(0),F(1),F(2),F(3).
Now, F(0) = A0 = 7

F(1) = A0 + A1 = 19
F(2) = A0 + A2 = 21
F(3) = A0 + A1 + A2 + A3 = 49

Input: A[] = {7, 11, 13, 16} , n = 2


Output: 7, 18, 20, 47
Explanation: There will be 4 values of x: 0,1,2,3
So, we need to calculate F(0),F(1),F(2),F(3).
Now, F(0) = A0 = 7
F(1) = A0 + A1 = 18
F(2) = A0 + A2 = 20
F(3) = A0 + A1 + A2 + A3 = 47

Page 134 of 201


CS-33: Programming in Python Unit-3 Plotting Using PyLab

[Link].0 Brute-Force Approach:


Iterate for all the x from 0 to (2n-1). Calculate the bitwise subsets of all the x and sum it up for every
x.
Time-Complexity: O (4^n)
Below is the implementation of above idea:

Example

# Python 3 program
# for brute force
# approach of SumOverSubsets DP

# function to print the


# sum over subsets value
def SumOverSubsets(a, n):

# array to store
# the SumOverSubsets
sos = [0] * (1 << n)

# iterate for all possible x


for x in range(0,(1 << n)):

# iterate for all


# possible bitwise subsets
for i in range(0,(1 << n)): MJKACC

# if i is a bitwise subset of x
if ((x & i) == i):
sos[x] += a[i]

# printa all the subsets


for i in range(0,(1 << n)):
print(sos[i],end = " ")

# Driver Code
a = [7, 12, 14, 16]
n=2
SumOverSubsets(a, n)

Output:
7 19 21 49
[Link].1 Sub-Optimal Approach:
 The brute-force algorithm can be easily improved by just iterating over bitwise subsets.
Instead of iterating for every i, we can simply iterate for the bitwise subsets only. Iterating
backward for i= (i-1) &x gives us every bitwise subset, where i starts from x and ends at 1. If
the mask x has k set bits, we do 2k iterations. A number of k set bits will have 2k bitwise
subsets. Therefore total number of mask x with k set bits is.

 Therefore the total number of iterations is? 2k = 3n


 Time Complexity: O(3n)

Page 135 of 201


CS-33: Programming in Python Unit-3 Plotting Using PyLab

Below is the implementation of above idea:


Example

# Python program for sub-optimal


# approach of SumOverSubsets DP

# function to print sum over subsets value


def SumOverSubsets(a, n):
sos = [0]*(1 << n)

# iterate for all possible x


for x in range((1 << n)):
sos[x] = a[0]

# iterate for the bitwise subsets only


i=x

while i > 0:
sos[x] += a[i]
i = ((i - 1) & x)

# print all the subsets


for i in range(1<<n):
print(sos[i], end = " ")

# Driver Code MJKACC

if __name__ == '__main__':
a = [7, 12, 14, 16]
n=2
SumOverSubsets(a, n)

Output:
7 19 21 49
Time Complexity: O(n*2n)
Auxiliary Space: O(2n)

Standard problems on Dynamic Programming:


 Easy:
1. Fibonacci numbers
2. nth Catalan Number
3. Bell Numbers (Number of ways to Partition a Set)
4. Binomial Coefficient
5. Coin change problem
6. Subset Sum Problem
7. Compute nCr % p
8. Cutting a Rod
9. Painting Fence Algorithm
10. Longest Common Subsequence
11. Longest Increasing Subsequence
12. Longest subsequence such that difference between adjacents is one
13. Maximum size square sub-matrix with all 1s

Page 136 of 201


CS-33: Programming in Python Unit-3 Plotting Using PyLab

14. Min Cost Path


15. Minimum number of jumps to reach end
16. Longest Common Substring (Space optimized DP solution)
17. Count ways to reach the nth stair using step 1, 2 or 3
18. Count all possible paths from top left to bottom right of a mXn matrix
19. Unique paths in a Grid with Obstacles
 Medium:
1. Floyd Warshall Algorithm
2. Bellman–Ford Algorithm
3. 0-1 Knapsack Problem
4. Printing Items in 0/1 Knapsack
5. Unbounded Knapsack (Repetition of items allowed)
6. Egg Dropping Puzzle
7. Word Break Problem
8. Vertex Cover Problem
9. Tile Stacking Problem
10. Box-Stacking Problem
11. Partition Problem
12. Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
13. Longest Palindromic Subsequence
14. Longest Common Increasing Subsequence (LCS + LIS)
15. Find all distinct subset (or subsequence) sums of an array
16. Weighted job scheduling
17. Count Derangements (Permutation such that no element appears in its original position)
18. Minimum insertions to form a palindrome
19. Wildcard Pattern Matching MJKACC

20. Ways to arrange Balls such that adjacent balls are of different types
 Hard:
1. Palindrome Partitioning
2. Word Wrap Problem
3. The painter’s partition problem
4. Program for Bridge and Torch problem
5. Matrix Chain Multiplication
6. Printing brackets in Matrix Chain Multiplication Problem
7. Maximum sum rectangle in a 2D matrix
8. Maximum profit by buying and selling a share at most k times
9. Minimum cost to sort strings using reversal operations of different costs
10. Count of AP (Arithmetic Progression) Subsequences in an array
11. Introduction to Dynamic Programming on Trees
12. Maximum height of Tree when any Node can be considered as Root
13. Longest repeating and non-overlapping substring

Page 137 of 201


CS-33: Programming in Python Chapter-4 Network Programming and GUI using Python

4.0 Network Programming:


 Python Network Programming is about using python as a programming language to handle
computer networking requirements.
 Python plays an essential role in network programming. The standard library of Python has
full support for network protocols, encoding, and decoding of data and other networking
concepts, and it is simpler to write network programs in Python than that of C++.
 There are two levels of network service access in Python. These are:
o Low-Level Access
o High-Level Access

 In the first case, programmers can use and access the basic socket support for the operating
system using Python's libraries, and programmers can implement both connection-less and
connection-oriented protocols for programming.
 Application-level network protocols can also be accessed using high-level access provided by
Python libraries. These protocols are HTTP, FTP, etc.

What is Socket programming?


 Sockets are the links through which the client and servers communicate with each other. For
example when a browser is opened a socket is automatically created to connect with the
server. Python has a socket module which can be used to implement various socket
functionalities like binding an address or starting a listener port. Socket programming is
fundamental to computer networking and python handles it well.

What is Client programming?


 The client is the computer which requests for information and waits for the response. Python
programs can be written to validate many client-side actions like parsing a URL, sending
MJKACC

parameters with the URL while submitting a request, connect to a alternate URL if access to
one URL becomes unsuccessful etc. These programs are run in the client programs and
handle all the communication needs with the server even without using a browser. For
example – you can provide an URL to the python program for downloading a file and it will
get done by the program itself without taking help from the browser program.

How to Building web servers?


 It is possible to create simple web servers which are good enough to run websites using
python as a programming language. Python already has some inbuilt web servers which can
be tweaked to achieve some additional functionalities needed.
 The SimpleHTTPServer module provides the functionalities of a web server out of the box
and you can start running it from the local python installation. In python 3 it is named
as [Link] and Tornado are examples of webservers written in python which run
as good as non python well known web servers like Apache or Ngnix.

Web Scrapping
 One of the important reasons python became famous is the its dominance among the
languages used for scrapping the web. Its data structure and network access abilities makes it
ideal for visiting webpages and download their data automatically. And if there is some API
connectivity available for the target website, then python will handle it even more easily
through its program structures.

Page 138 of 201


CS-33: Programming in Python Chapter-4 Network Programming and GUI using Python

Web Frame works


 Web Frame works makes application development easy and fast by offering pre-defined
structures and modularity. The developer has to do minimal coding to leverage those existing
libraries and customize a little to achieve the goal. Django and Flask are two famous ones
which have seen much commercial use even though they are opensource.

4.0.1 What Is a Protocol?


 Protocol is a very generic word, both in regular language as well as in Computer Science.
Most of us are probably familiar with it from hearing TCP Protocol, UDP Protocol or also
HTTP Protocol. Dictionaries have also dedicated definitions for it.
 The Internet Protocol is designed to implement a uniform system of addresses on all of the
Internet-connected computers everywhere and to make it possible for packets to travel from
one end of the Internet to the other.
 A set of rules governing the exchange or the transmission of data between devices
 Which indeed makes sense. All the examples listed above are communication protocols
between two remote devices with a set of rules that are governing the transmission. In the
case of TCP, for instance, the protocol mandates the shape of the message, the possible
operations, the error policies as well as the rules for possible retransmission of a message.
Protocol Python Module Name Description
HTTP [Link] Opening the HTTP URL
HTTP [Link] Create a reponse object for a url request
HTTP [Link] To break Uniform Resource Locator (URL) strings up in
components like (addressing scheme, network location, path
etc.),
HTTP [Link] It finds out whether or not a particular user agent can fetch a
MJKACC

URL on the Web site that published the [Link] file.


implements the client side of the FTP protocol. You can use
FTP ftplib this to write Python programs that perform a variety of
automated FTP jobs, such as mirroring other FTP servers.
This module defines a class, POP3, which encapsulates a
POP poplib connection to a POP3 server to read messages from a email
server
This module defines three classes, IMAP4, IMAP4_SSL and
IMAP imaplib IMAP4_stream, which encapsulate a connection to an IMAP4
server to read emails.
The smtplib module defines an SMTP client session object that
SMTP smtplib can be used to send mail to any Internet machine with an SMTP
listner deamon.
This module provides a Telnet class that implements the Telnet
Telnet telnet
protocol to access a server thorugh teleent.

4.0.2 Python - Sockets Programming


 Python provides two levels of access to network services. At a low level, you can access the
basic socket support in the underlying operating system, which allows you to implement
clients and servers for both connection-oriented and connectionless protocols.
 Sockets are the endpoints of a bidirectional communications channel. Sockets may
communicate within a process, between processes on the same machine, or between
processes on different continents. We use the socket module in python to create and use
sockets.

Page 139 of 201


CS-33: Programming in Python Chapter-4 Network Programming and GUI using Python

Sockets have their own vocabulary –

[Link]. Term & Description


Domain
1 The family of protocols that is used as the transport mechanism. These values are constants such
as AF_INET, PF_INET, PF_UNIX, PF_X25, and so on.
type
2 The type of communications between the two endpoints, typically SOCK_STREAM for
connection-oriented protocols and SOCK_DGRAM for connectionless protocols.
protocol
3
Typically zero, this may be used to identify a variant of a protocol within a domain and type.
hostname
The identifier of a network interface −
 A string, which can be a host name, a dotted-quad address, or an IPV6 address in colon
4 (and possibly dot) notation
 A string "<broadcast>", which specifies an INADDR_BROADCAST address.
 A zero-length string, which specifies INADDR_ANY, or
 An Integer, interpreted as a binary address in host byte order.
port
5 Each server listens for clients calling on one or more ports. A port may be a Fixnum port
number, a string containing a port number, or the name of a service.

[Link] The socket Module


 To create a socket, you must use the [Link]() function available in socket module,
which has the general syntax
o s = [Link] (socket_family, socket_type, protocol=0)
 Here is the description of the parameters − MJKACC

 socket_family − This is either AF_UNIX or AF_INET, as explained earlier.


 socket_type − This is either SOCK_STREAM or SOCK_DGRAM.
 protocol − This is usually left out, defaulting to 0.
 Once you have socket object, then you can use required functions to create your client or
server program.

[Link] Server Socket Methods


[Link]. Method & Description
[Link]()
1
This method binds address (hostname, port number pair) to socket.
[Link]()
2
This method sets up and start TCP listener.
[Link]()
3
This passively accept TCP client connection, waiting until connection arrives (blocking).

[Link] Client Socket Methods


[Link]. Method & Description
[Link]()
1
This method actively initiates TCP server connection.

[Link] General Socket Methods


[Link]. Method & Description
[Link]()
1
This method receives TCP message
[Link]()
2
This method transmits TCP message

Page 140 of 201


CS-33: Programming in Python Chapter-4 Network Programming and GUI using Python

[Link]()
3
This method receives UDP message
[Link]()
4
This method transmits UDP message
[Link]()
5
This method closes socket
[Link]()
6
Returns the hostname.

[Link] A Simple Server


 To write Internet servers, we use the socket function available in socket module to create a
socket object. A socket object is then used to call other functions to setup a socket server.
 Now call bind(hostname, port) function to specify a port for your service on the given host.
 Next, call the accept method of the returned object. This method waits until a client connects
to the port you specified, and then returns a connection object that represents the connection
to that client.
#!/usr/bin/python # This is [Link] file

import socket # Import socket module

s = [Link]() # Create a socket object


host = [Link]() # Get local machine name
port = 12345 # Reserve a port for your service.
[Link]((host, port)) # Bind to the port

[Link](5) # Now wait for client connection.


MJKACC

while True:
c, addr = [Link]() # Establish connection with client.
print 'Got connection from', addr
[Link]('Thank you for connecting')
[Link]() # Close the connection

[Link] A Simple Client


 Let us write a very simple client program which opens a connection to a given port 12345
and given host. This is very simple to create a socket client using Python's socket module
function.
 The [Link] (hosname, port) opens a TCP connection to hostname on the port. Once
you have a socket open, you can read from it like any IO object. When done, remember to
close it, as you would close a file.
 The following code is a very simple client that connects to a given host and port, reads any
available data from the socket, and then exits −
#!/usr/bin/python # This is [Link] file
import socket # Import socket module
s = [Link] () # Create a socket object
host = [Link]() # Get local machine name
port = 12345 # Reserve a port for your service.
[Link]((host, port))
print [Link](1024)
[Link] # Close the socket when done

Page 141 of 201


CS-33: Programming in Python Chapter-4 Network Programming and GUI using Python

 Now run this [Link] in background and then run above [Link] to see the result.

# Following would start a server in background.


$ python [Link] &

# Once server is started run client as follows:


$ python [Link]

 This would produce following result –


o Got connection from ('[Link]', 48437)
o Thank you for connecting

[Link] Socket with Public URL


 In the below example we use few methods from the socket module to find the address
information of server and host name details.
import socket
from pprint import pprint

# get server address


addrinfo = [Link]('[Link]', 'www')

pprint(addrinfo)

# get server hostname


print [Link]() MJKACC

 When we run the above program, we get the following output –


[(<AddressFamily.AF_INET: 2>,
<SocketKind.SOCK_STREAM: 1>,
0,
'',
('[Link]', 80))]
PC-60
4.0.3 Knowing IP Address
We are going to find the IP address of the client using the socket module in Python. Every laptop,
mobile, tablet, etc.., have their unique IP address. We will find it by using the socket module. Let's
see the steps to find out the IP address of a device.
Step 1: Import socket library
Step 2: Then print the value of the IP into the print() function your IP address.
 Here we have to import the socket first then we get the hostname by using the
gethostname() function and then we fetch the IP address using the hostname that we fetched
and the we simply print it.
import socket
hostname = [Link]()
IPAddr = [Link](hostname)
print("Your Computer Name is:" + hostname)
print("Your Computer IP Address is:" + IPAddr)
Output:
Your Computer Name is:PC-60
Your Computer IP Address is:[Link]

Page 142 of 201


CS-33: Programming in Python Chapter-4 Network Programming and GUI using Python

4.0.4 URL

 Urllib package is the URL handling module for python. It is used to fetch URLs (Uniform
Resource Locators). It uses the urlopen function and is able to fetch URLs using a variety of
different protocols.
 Urllib is a package that collects several modules for working with URLs, such as:
 [Link] for opening and reading.
 [Link] for parsing URLs
 [Link] for the exceptions raised
 [Link] for parsing [Link] files
 If urllib is not present in your environment, execute the below code to install it.
o pip install urllib
 [Link]
 This module helps to define functions and classes to open URLs (mostly HTTP).
One of the most simple ways to open such URLs is :
[Link](url)
We can see this in an example:
import [Link]
request_url = [Link]('[Link]
print(request_url.read())
 [Link]
 This module helps to define functions to manipulate URLs and their components
parts, to build or break them. It usually focuses on splitting a URL into small
components; or joining different URL components into URL strings.
MJKACC

We can see this from the below code:


from [Link] import * parse_url = urlparse('[Link]
print(parse_url)
print("\n")
unparse_url = urlunparse(parse_url)
print(unparse_url)
 Note:- The different components of a URL are separated and joined again. Try using
some other URL for better understanding.
 Different other functions of [Link] are :
Function Use
[Link] Separates different components of URL
[Link] Join different components of URL
[Link] It is similar to urlparse() but doesn’t split the params
[Link] Combines the tuple element returned by urlsplit() to form URL
If URL contains fragment, then it returns a URL removing the
[Link]
fragment.
 [Link]: This module defines the classes for exception raised by [Link].
Whenever there is an error in fetching a URL, this module helps in raising
exceptions. The following are the exceptions raised :
 URLError – It is raised for the errors in URLs, or errors while fetching the URL due
to connectivity, and has a ‘reason’ property that tells a user the reason of error.

Page 143 of 201


CS-33: Programming in Python Chapter-4 Network Programming and GUI using Python

 HTTPError – It is raised for the exotic HTTP errors, such as the authentication
request errors. It is a subclass or URLError. Typical errors include ‘404’ (page not
found), ‘403’ (request forbidden), and ‘401’ (authentication required).
 We can see this in following examples :
import [Link]
import [Link]
# trying to read the URL but with no internet connectivity
try:
x = [Link]('[Link]
print([Link]())
# Catching the exception generated
except Exception as e :
print(str(e))
 [Link]: This module contains a single class, RobotFileParser. This class
answers question about whether or not a particular user can fetch a URL that
published [Link] files. [Link] is a text file webmasters create to instruct web
robots how to crawl pages on their website. The [Link] file tells the web scraper
about what parts of the server should not be accessed.
For example :
# importing robot parser class
import [Link] as rb
bot = [Link]()
# checks where the website's [Link] file reside
x = bot.set_url('[Link] / [Link]')
MJKACC

print(x)

# reads the files


y = [Link]()
print(y)

# we can crawl the main site


z = bot.can_fetch('*', '[Link]
print(z)
# but can not crawl the disallowed url
w = bot.can_fetch('*', '[Link] / wp-admin/')
print(w)
4.0.5 Reading the Source Code of a Web Page:
 Library known as beautifulsoup. Using this library, we can search for the values of html tags
and get specific data like title of the page and the list of headers in the page.
 Requests is one of the most widely used library. It allows us to open any
HTTP/HTTPS website and let us do any kind of stuff we normally do on web and
can also save sessions i.e cookie.
 As we all know that a webpage is just a piece of HTML code which is sent by the
Web Server to our Browser, which in turn converts into the beautiful page. Now we
need a mechanism to get hold of the HTML source code i.e finding some particular
tags with a package called BeautifulSoup.
install Beautifulsoup

Page 144 of 201


CS-33: Programming in Python Chapter-4 Network Programming and GUI using Python

 Use the Anaconda package manager to install the required package and its dependent
packages.
o conda install Beaustifulsoap
We take an example by reading a news site Hindustan Times
The code can be divided into three parts.
 Requesting a webpage
 Inspecting the tags
 Print the appropriate contents
Steps:
1. Requesting a webpage: First we see right click on the news text to see the source code

2. Inspecting the tags: We need to figure in which body of the source code contains the
news section we want to scrap. It is the under ul,i.e unordered list, “searchNews” which
contains the news section.

MJKACC

Page 145 of 201


CS-33: Programming in Python Chapter-4 Network Programming and GUI using Python

Note The news text is present in the anchor tag text part. A close observation gives us
the idea that all the news are in li, list, tags of the unordered tag.

3. Print the appropriate contents: The content is printed with the help of code given
below.
import requests
from bs4 import BeautifulSoup
def news():
# the target we want to open
url='[Link]
MJKACC

#open with GET method


resp=[Link](url)

#http_respone 200 means OK status


if resp.status_code==200:
print("Successfully opened the web page")
print("The news are as follow :-\n")

# we need a parser,Python built-in HTML parser is enough .


soup=BeautifulSoup([Link],'[Link]')

# l is the list which contains all the text i.e news


l=[Link]("ul",{"class":"searchNews"})

#now we want to print only the text part of the anchor.


#find all the elements of a, i.e anchor
for i in [Link]("a"):
print([Link])
else:
print("Error")

news()

Page 146 of 201


CS-33: Programming in Python Chapter-4 Network Programming and GUI using Python

4.0.6 Reading the HTML file:


 In the below example we make a request to a URL to be loaded into the python environment.
Then use the html parser parameter to read the entire html file. Next, we print first few lines of
the html page.
 In the below example we make a request to an url to be loaded into the python environment.
Then use the html parser parameter to read the entire html file. Next, we print first few lines of
the html page.

import [Link]
from bs4 import BeautifulSoup
# Fetch the html file
response = [Link]('[Link]
html_doc = [Link]()
# Parse the html file
soup = BeautifulSoup(html_doc, '[Link]')
# Format the parsed html file
strhtm = [Link]()
# Print the first few characters
print (strhtm[:225])

4.0.7 Downloading a Web Page from Internet:


 Python provides different modules like urllib, requests etc to download files from the web. I
am going to use the request library of python to efficiently download files from the URLs.
 Let’s start a look at step by step procedure to download files using URLs
using request library−

MJKACC

1. Import module
o import requests
 2. Get the link or url
o url = '[Link]
o r = [Link](url, allow_redirects=True)
 3. Save the content with name.
o open('[Link]', 'wb').write([Link])
 save the file as [Link].
import requests
url = '[Link]
r = [Link](url, allow_redirects=True)
open('[Link]', 'wb').write([Link])
 But we may need to download different kind of files like image, text, video etc from the web.
So let’s first get the type of data the url is linking to−
>>> r = [Link](url, allow_redirects=True)
>>> print([Link]('content-type'))
image/png
 However, there is a smarter way, which involved just fetching the headers of a URL before
actually downloading it. This allows us to skip downloading files which weren’t meant to be
downloaded.
>>> print(is_downloadable('[Link]
False
>>> print(is_downloadable('[Link]
True

Page 147 of 201


CS-33: Programming in Python Chapter-4 Network Programming and GUI using Python

 To restrict the download by file size, we can get the filezie from the content-length header
and then do as per our requirement.
contentLength = [Link]('content-length', None)
if contentLength and contentLength > 2e8: # 200 mb approx
return False

 Get filename from an URL: To get the filename, we can parse the url. Below is a sample
routine which fetches the last string after backslash(/).
o url= [Link]
[Link]
o if [Link]('/'):
o print([Link]('/', 1)[1]

 Above will give the filename of the URL. However, there are many cases where filename
information is not present in the URL for example – [Link] In such a case,
we need to get the Content-Disposition header, which contains the filename information.
import requests
import re
def getFilename_fromCd(cd):
"""
Get filename from content-disposition
"""
if not cd:
return None
fname = [Link]('filename=(.+)', cd)
if len(fname) == 0:
MJKACC

return None
return fname[0]
url = '[Link]
r = [Link](url, allow_redirects=True)
filename = getFilename_fromCd([Link]('content-disposition'))
open(filename, 'wb').write([Link])
 The above url-parsing code in conjunction with above program will give you filename from
Content-Disposition header most of the time.

4.0.8 Downloading an Image from Internet:


 Web scraping is a technique to fetch data from websites. While surfing on the web, many
websites don’t allow the user to save data for personal use. One way is to manually copy-
paste the data, which both tedious and time-consuming. Web Scraping is the automation of
the data extraction process from websites.
 Firstly the relevant libraries are imported. Then a call to the web address is made,
and the resource returned in the response is stored in the file named
[Link].
 It should be noted that the extension of the image file has to be known here, i.e., the
container for the image file format, such as png, jpg, SVG, BMP, etc., needs to be
known beforehand.
 In this case, the image was in PNG format, which was mentioned in the output file
name. After the aforementioned function has been executed successfully, a file
named [Link] will be produced in the current working directory of the

Page 148 of 201


CS-33: Programming in Python Chapter-4 Network Programming and GUI using Python

program. This file is later opened using the [Link] function and, in the end,
displayed using the [Link] function.
import [Link]
from PIL import Image

# Retrieving the resource located at the URL


# and storing it in the file name [Link]
url = "[Link]
obKTtjYHJK_ZVSzJ8rVIDU5GRbAwbDTOKNxOHnDyvpKcrhLCXy3gghBfJ44FZ
NpFSnM78reGFAcwK5sFhWQVgjhhzdyZHREObyXsCcqtp86P5tEIHr9ucXNOjnf5
1dQar9FrPwYSRRLOAjabv1lRIafvTlKid-sDWrcf3NTePY1kEek8H7do/s16000/"
[Link](url, "[Link]")

# Opening the image and displaying it (to confirm its presence)


img = [Link](r"[Link]")
[Link]()
Modules Needed
 bs4: Beautiful Soup (bs4) is a Python library for pulling data out of HTML and XML files.
This module does not come built-in with Python.
 requests: Requests allows you to send HTTP/1.1 requests extremely easily. This module also
does not come built-in with Python.
 os: The OS module in python provides functions for interacting with the operating system.
OS, comes under Python’s standard utility modules. This module provides a portable way of
using operating system dependent functionality.
MJKACC

4.0.9 A TCP/IP Server, A TCP/IP Client:


Introduction
 There are powerful libraries and tools written in python. In the core part of these libraries and
tools is the socket module. This module provides access to the BSD socket interface and
avaliable on numerous platforms, UNIX, Window, and Mac OS X etc. Here, I'm going to
create a TCP client and TCP server to test and transfer data.

TCP/IP Server
 This sample program, based on the one in the standard library documentation, receives
incoming messages and echos them back to the sender. It starts by creating a TCP/IP socket.
import socket
import sys
# Create a TCP/IP socket
sock = [Link](socket.AF_INET, socket.SOCK_STREAM)

 Then bind() is used to associate the socket with the server address. In this case, the address
is localhost, referring to the current server, and the port number is 10000.
# Bind the socket to the port
server_address = ('localhost', 10000)
print >>[Link], 'starting up on %s port %s' % server_address
[Link](server_address)

 Calling listen () puts the socket into server mode, and accept () waits for an incoming
connection.

Page 149 of 201


CS-33: Programming in Python Chapter-4 Network Programming and GUI using Python

# Listen for incoming connections


[Link] (1)
while True:
# Wait for a connection
print >>[Link], 'waiting for a connection'
connection, client_address = [Link]()
 accept() returns an open connection between the server and client, along with the address of
the client. The connection is actually a different socket on another port (assigned by the
kernel). Data is read from the connection with recv() and transmitted with sendall().
try:
print >>[Link], 'connection from', client_address
# Receive the data in small chunks and retransmit it
while True:
data = [Link](16)
print >>[Link], 'received "%s"' % data
if data:
print >>[Link], 'sending data back to the client'
[Link](data)
else:
print >>[Link], 'no more data from', client_address
break
finally:
# Clean up the connection
[Link]()
 When communication with a client is finished, the connection needs to be cleaned up
MJKACC

using close (). This example uses a try:finally block to ensure that close() is always called,
even in the event of an error.
Full Code Part
import socket
import sys
# Create a TCP/IP socket
sock = [Link](socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to the port
server_address = ('localhost', 10000)
print([Link], 'starting up on %s port %s' % server_address)
[Link](server_address)
# Listen for incoming connections
[Link] (1)
while True:
# Wait for a connection
print([Link], 'waiting for a connection')
connection, client_address = [Link]()
try:
print([Link], 'connection from', client_address)
# Receive the data in small chunks and retransmit it
while True:
data = [Link](16)
print([Link], 'received "%s"' % data)
if data:
print([Link], 'sending data back to the client')

Page 150 of 201


CS-33: Programming in Python Chapter-4 Network Programming and GUI using Python

[Link](data)
else:
print([Link], 'no more data from', client_address)
break
finally:
# Clean up the connection
[Link]()
TCP/IP Client
 The client program sets up its socket differently from the way a server does. Instead of
binding to a port and listening, it uses connect () to attach the socket directly to the remote
address.
import socket
import sys
# Create a TCP/IP socket
sock = [Link](socket.AF_INET, socket.SOCK_STREAM)
# Connect the socket to the port where the server is listening
server_address = ('localhost', 10000)
print >>[Link], 'connecting to %s port %s' % server_address
[Link](server_address)
 After the connection is established, data can be sent through the socket with sendall() and
received with recv(), just as in the server.
try: # Send data
message = 'This is the message. It will be repeated.'
print >>[Link], 'sending "%s"' % message
[Link](message) MJKACC

# Look for the response


amount_received = 0
amount_expected = len(message)

while amount_received < amount_expected:


data = [Link](16)
amount_received += len(data)
print >>[Link], 'received "%s"' % data

finally:
print >>[Link], 'closing socket'
[Link]()
 When the entire message is sent and a copy received, the socket is closed to free up the port.
Full Code Part
import socket
import sys
# Create a TCP/IP socket
sock = [Link](socket.AF_INET, socket.SOCK_STREAM)
# Connect the socket to the port where the server is listening
server_address = ('localhost', 10000)
print([Link], 'connecting to %s port %s' % server_address)
[Link](server_address)
try: # Send data
s = 'This is the message. It will be repeated.'
message = bytes(s, 'utf-8')

Page 151 of 201


CS-33: Programming in Python Chapter-4 Network Programming and GUI using Python

print([Link], 'sending "%s"' % message)


[Link](message)
# Look for the response
amount_received = 0
amount_expected = len(message)
while amount_received < amount_expected:
data = [Link](16)
amount_received += len(data)
print([Link], 'received "%s"' % data)
finally:
print([Link], 'closing socket')
[Link]()
Client and Server Together
 The client and server should be run in separate terminal windows, so they can communicate
with each other. The server output is:
$ python ./socket_echo_server.py
starting up on localhost port 10000
waiting for a connection
connection from ('[Link]', 52186)
received "This is the mess"
sending data back to the client
received "age. It will be"
sending data back to the client
received " repeated."
sending data back to the client
received ""
MJKACC

no more data from ('[Link]', 52186)


waiting for a connection
 The client output is:
$ python socket_echo_client.py
connecting to localhost port 10000
sending "This is the message. It will be repeated."
received "This is the mess"
received "age. It will be"
received " repeated."
closing socket
4.0.10 A UDP Server, A UDP Client:
UDP Overview:
 UDP is the abbreviation of User Datagram Protocol. UDP makes use of Internet Protocol of
the TCP/IP suit. In communications using UDP, a client program sends a message packet to a
destination server wherein the destination server also runs on UDP.
 UDP or User Datagram Protocol is connection-less protocol which is suitable for applications
that require efficient communication that doesn't have to worry about packet loss. For gaming
applications this tends to be the perfect protocol due to the lower overhead incurred as
opposed to TCP.
 Typically games send and receive thousands of packets a second that contain information
such as opposing player’s health, location, and direction and so on. Now if one of these
packets was to be dropped during transmission then it isn't too critical to the game and the
worst case scenario is that a player jerks about for a split second during gameplay.

Page 152 of 201


CS-33: Programming in Python Chapter-4 Network Programming and GUI using Python

Properties of UDP:
 The UDP does not provide guaranteed delivery of message packets. If for some issue in a
network if a packet is lost it could be lost forever. Since there is no guarantee of assured
delivery of messages, UDP is considered an unreliable protocol.
 The underlying mechanisms that implement UDP involve no connection-based
communication. There is no streaming of data between a UDP server or and an UDP Client.
 An UDP client can send "n" number of distinct packets to an UDP server and it could also
receive "n" number of distinct packets as replies from the UDP server.
 Since UDP is connectionless protocol the overhead involved in UDP is less compared to a
connection based protocol like TCP.
MJKACC

Implementing the Client


 Once we''ve got this we need to declare the IP address that we will be trying to send our UDP
messages to as well as the port number. This port number is arbritary but ensure that you
aren''t using a socket that has already been taken.
 Now that we've declared these few variables it''s time to create the socket through which we
will be sending our UDP message to the server.

Page 153 of 201


CS-33: Programming in Python Chapter-4 Network Programming and GUI using Python

 And finally, once we've constructed our new socket it's time to write the code that will send
our UDP message:
import socket
UPD_IP_ADDRESS = [Link]
UDP_PORT_NO = 6789
Message = “Hello, Server”
clientSock = [Link](socket.AF_INET, socket.SOCK_DGRAM)
[Link](Message, (UDP_IP_ADDRESS, UDP_PORT_NO))
Implementing the Server
 Now that we''ve coded our client we then need to move on to creating our server program
which will be continuously listening on our defined IP address and port number for any UDP
messages. It is essential that this server has to be run prior to the execution of the client
python script or the client script will fail.
import socket
UDP_IP_ADDRESS = "[Link]"
UDP_PORT_NO = 6789
serverSock = [Link](socket.AF_INET, socket.SOCK_DGRAM)
[Link]((UDP_IP_ADDRESS, UDP_PORT_NO))
While True:
data, addr = [Link](1024)
print "Message: ", data
4.0.11 File Server, File Client
 Before going forward you have to understand that why you want to send file from the server
to the client system?
 We can use this method when we have a connection between client-server and we are getting
MJKACC

a lot of data from server side and we need to store all the data at a specific location, in this
case we should create a directory into the client system and where all the server data will be
download.
 So once the server will upload the data then the socket helps to download that data into the
client system.

FUNCTION AT SERVER SIDE


def upload_files(serverSocket):
print("[+] Upload file")
path = "Document/"
files = glob(path + "*")
for index, filename in enumerate(files):
filename = [Link](filename)
print("\t\t", index, ":", filename)
while True:
try:
fileIndex = int(input("[+] Select File: "))
if len(files) >= fileIndex >= 0:
fileName = files[fileIndex]
break
except Exception as e:
print("[-] Invalid file selected")
print("[+] Selected File: ", fileName)
[Link](fileName)
[Link](filename, path)

Page 154 of 201


CS-33: Programming in Python Chapter-4 Network Programming and GUI using Python

 1: Create a function that collect all the data from server and call the another function that
used to send file at client side.
def SendFile(self, filename, path):
print("[+] Sending File")
filename = path+filename
with open(filename, "rb") as file:
chunk = [Link](CHUNK_SIZE)
while len(chunk) > 0:
self.client_conn.send(chunk)
chunk = [Link](CHUNK_SIZE)
self.client_conn.send([Link]('latin-1'))
 2: After collection all data, the socket.client_conn.send() function will used to send the data.
FUNCTION AT CLIENT SIDE
def DownloadFile(socket):
print("[+] Downloading Files")
filename = [Link]()
[Link](filename)
 3: Once the server sent the data, now we create a function at client side that accept the data
and will download that data into the client specific directory
def ReceiveFile(self, filename):
print("[+] Receive File")
filename = [Link](filename)
print("[+] Filename: ()".format(filename))
clientPath = "FileDownload/" + filename
with open(clientPath, "wb") as file: MJKACC

while True:
chunk = [Link](CHUNK_SIZE)
if [Link]([Link]('utf-8')):
chunk = chunk[:-len(DELIMETER)]
[Link](chunk)
break
[Link](chunk)
print("[+] Completed")

 4: The client will use [Link]() function that receive the incoming data and write the data
at defined directory.
 This 4 steps used to upload the file from the server system and download the file into the
client system using socket.

Page 155 of 201


CS-33: Programming in Python Chapter-4 Network Programming and GUI using Python

4.0.12 Two Way Communication between server and client:

[Link]
import socket, time
def Tcp_connect( HostIp, Port ):
global s
s = [Link](socket.AF_INET, socket.SOCK_STREAM)
[Link]((HostIp, Port))
return
def Tcp_Write(D):
[Link](bytes(D + '\r','UTF-8'))
return
def Tcp_Read( ):
a=''
MJKACC

b = ''
while a != '\r':
a = [Link](1)
b=b+a
return b
def Tcp_Close( ):
[Link]()
return
Tcp_connect( '[Link]', 17098)
Tcp_Write('hi')
print (Tcp_Read())
Tcp_Write('hi')
print (Tcp_Read())
Tcp_Close()

Page 156 of 201


CS-33: Programming in Python Chapter-4 Network Programming and GUI using Python

[Link]
import socket, time
#things to begin with
def Tcp_connect( HostIp, Port ):
global s
s = [Link](socket.AF_INET, socket.SOCK_STREAM)
[Link]((HostIp, Port))
return
def Tcp_server_wait ( numofclientwait, port ):
global s2
s2 = [Link](socket.AF_INET, socket.SOCK_STREAM)
[Link](('',port))
[Link](numofclientwait)
def Tcp_server_next ( ):
global s
s = [Link]()[0]

def Tcp_Write(D):
[Link](D + '\r')
return
def Tcp_Read( ):
a=''
b = ''
while a != '\r':
a = [Link](1)
b = str(b) + str(a) MJKACC

print (b)
return b
def Tcp_Close( ):
[Link]()
return
Tcp_server_wait ( 5, 17098 )
Tcp_server_next()
print (Tcp_Read())
Tcp_Write('hi')
print (Tcp_Read())
Tcp_Write('hi')
Tcp_Close()

4.0.13 Send simple email using python


 Here, we are going to learn how to send a simple basic mail using Python code. Python, being
a powerful language don’t need any external library to import and offers a native library to
send emails- “SMTP lib”. “smtplib”
 Creates a Simple Mail Transfer Protocol client session object which is used to send emails to
any valid email id on the internet. Different websites use different port numbers.
 In this article, we are using a Gmail account to send a mail. Port number used here is ‘587’.
And if you want to send mail using a website other than Gmail, you need to get the
corresponding information.

Page 157 of 201


CS-33: Programming in Python Chapter-4 Network Programming and GUI using Python

Steps to send mail from Gmail account:


 First of all, “smtplib” library needs to be imported.
 After that, to create a session, we will be using its instance SMTP to encapsulate an SMTP
connection.
o s = [Link]('[Link]', 587)
 In this, we need to pass the first parameter of the server location and the second parameter of
the port to use. For Gmail, we use port number 587.
 For security reasons, now put the SMTP connection in the TLS mode. TLS (Transport Layer
Security) encrypts all the SMTP commands. After that, for security and authentication, you
need to pass your Gmail account credentials in the login [Link] compiler will show an
authentication error if you enter invalid email id or password.
 Store the message you need to send in a variable say, message. Using the sendmail() instance,
send your message. sendmail() uses three parameters: sender_email_id, receiver_email_id
and message_to_be_sent. The parameters need to be in the same sequence.
 This will send the email from your account. After you have completed your task, terminate
the SMTP session by using quit().
 Note: Generate Two step verification password by adding website and generate
password for authorize access
Example: Python code to illustrate Sending mail from your Gmail account
import smtplib
# creates SMTP session
s = [Link]('[Link]', 587)
#start TLS for security
[Link]()
#Authentication MJKACC

[Link]("anilmakwana03@[Link]", "nrnh kyzi hman svjo")


#message to be sent
message = "hellooooooooooo"
# sending the mail
[Link]("anilmakwana03@[Link]"," anilmakwana03@[Link]", message)
#terminating the session
[Link]()
Important Points:
 This code can send simple mail which doesn’t have any attachment or any subject.
 One of the most amazing things about this code is that we can send any number of emails
using this and Gmail mostly put your mail in the primary section. Sent mails would not be
detected as Spam generally.
 File handling can also be used to fetch email id from a file and further used for sending the
emails.

4.1 GUI Programming


 Most of the programs we have done till now are text-based programming. But many
applications need GUI (Graphical User Interface). Python provides various options for
developing graphical user interfaces (GUIs). The most important features are listed below.
 Tkinter − Tkinter is the Python interface to the Tk GUI toolkit shipped with Python.
 wxPython − This is an open-source Python interface for wxWidgets GUI toolkit.
 PyQt − This is also a Python interface for a popular cross-platform Qt GUI library.
 PyGTK − PyGTK is a set of wrappers written in Python and C for GTK + GUI library.

Page 158 of 201


CS-33: Programming in Python Chapter-4 Network Programming and GUI using Python

 PySimpleGUI − PySimpleGui is an open source, cross-platform GUI library for Python. It


aims to provide a uniform API for creating desktop GUIs based on Python's Tkinter, PySide
and WxPython toolkits.
 Pygame − Pygame is a popular Python library used for developing video games. It is free,
open source and cross-platform wrapper around Simple DirectMedia Library (SDL).
 Jython − Jython is a Python port for Java, which gives Python scripts seamless access to the
Java class libraries on the local machine [Link]

4.1.0 Event-driven programming paradigm:


 Event-driven programming focuses on the events (messages) and their flow between different
software components. In fact, it can be found in many types of software. Historically, event-
based Python programming is the most common paradigm for software that deals with direct
human interaction.
 Eventually, the flow of a program depends upon the events, and programming which focuses
on events is called Event-Driven programming. We were only dealing with either parallel or
sequential models, but now we will discuss the asynchronous model. The programming
model following the concept of Event-Driven programming is called the Asynchronous
model. The working of Event-Driven programming depends upon the events happening in a
program.

Other than this, it depends upon the program's


event loops that always listen to a new incoming
event in the program. Once an event loop starts in
the program, then only the events will decide what
will execute and in which order.
MJKACC

[Link] Python Module – Asyncio


Asyncio module was added in Python 3.4 and it
provides infrastructure for writing single-threaded
concurrent code using co-routines. Following are
the different concepts used by the Asyncio module

The event loops


Event-loop is a functionality to handle all the
events in a computational code. It acts round the
way during the execution of whole program and
keeps track of the incoming and execution of
events.

 The Asyncio module allows a single event loop per process.


 Followings are some methods provided by Asyncio module to manage an event loop –
o loop = get_event_loop() − This method will provide the event loop for the current
context.
o loop.call_later(time_delay,callback,argument) − This method arranges for the
callback that is to be called after the given time_delay seconds.
o loop.call_soon(callback,argument) − This method arranges for a callback that is to be
called as soon as possible. The callback is called after call_soon() returns and when
the control returns to the event loop.
o [Link]() − This method is used to return the current time according to the event
loop’s internal clock.

Page 159 of 201


CS-33: Programming in Python Chapter-4 Network Programming and GUI using Python

o asyncio.set_event_loop() − This method will set the event loop for the current context
to the loop.
o asyncio.new_event_loop() − This method will create and return a new event loop
object.
o loop.run_forever() − This method will run until stop() method is called.
Example
import asyncio
def hello_world(loop):
print('Hello World')
[Link]()
loop = asyncio.get_event_loop()
loop.call_soon(hello_world, loop)
loop.run_forever()
[Link]()

4.1.1 Creating simple GUI


 A graphical interface, or GUI, is an interactive environment that is the first thing a user sees
and interacts with aftering opening an application or website. A system of interactive visual
components for computer software, a GUI displays objects that convey information, and it
represents actions that a user can take. The objects can change color, size, or visibility when
the user interacts with them. A GUI can include graphical elements like icons, cursors, and
buttons that can also be enhanced with sounds or visual effects, such as transparency.
 A good GUI is crucial for increasing your platform’s reputation and user count, and the
combination of all of these elements plays a big role in your application or website’s user
experience.
 When creating GUIs, many developers turn to Python, which has a lot of different
MJKACC

frameworks. Python is an interactive programming language that makes it easy to get started
with programming a GUI framework. Python has a wide range of options for GUI
frameworks, including Cross-Platform frameworks and Platform-Specific frameworks.
 Here is a look at the 10 best Python libraries for GUI:

Python Libraries for GUI Programming


 We can use any of the following toolkits in Python for GUI programming.
 Tkinter: Another top Python library for GUI is Tkinter, which is an open-source Python
Graphic User Interface library. It is well known for its simplicity and comes pre-installed in
Python, meaning there is no work on your part. These features make it a great choice for
beginners and intermediates, but it is not capable of carrying out larger-scale projects.
 With Tkinter, the visual elements are called widgets, and each of the widgets comes with a
different level of customizability. It also offers a wide range of commonly used elements that
many developers are already familiar with, such as Frame, Buttons, Checkbuttons, Labels,
File Dialogs, and Canvas.
 Here are some of the main advantages of Tkinter:
o Easy-to-use and fast to implement
o Flexible and stable
o Included in Python
o Provides a simple syntax

 PyQt5: Developed by Riverbank Computing, PyQt5 is one of the most popular Python
frameworks for GUI. The PyQt package is built around the Qt framework, which is a cross-
platform framework used for creating various applications on different platforms.

Page 160 of 201


CS-33: Programming in Python Chapter-4 Network Programming and GUI using Python

 PyQt5 is fully cross-platform, meaning developers can use it to build applications on a


variety of platforms like Mac, Windows, Linux, iOS, and Android. It offers QtGUI and
QtDesigner modules that provide visual elements the developer can implement with drag and
drop. You can also opt to create the element by code, which enables you to develop small-
scale and large-scale applications easily.
 Here are some of the main advantages of PyQt5:
o Coding versatility
o Various UI components
o Several learning resources
o Broad variety of native platform APIs for networking, database management, and
more

 wxPython: One more Python library for GUI is wxPython, which enables Python developers
to create native user interfaces with zero additional overhead to the application. Like the
other libraries and frameworks, wxPython works on a variety of platforms like Mac OS,
Windows, Linux, and Unix-based systems.
 wxPython includes many widgets, which is its biggest selling point. It also looks great across
all platforms right away, and it doesn’t require much custom altering. With that said, it has a
steeper learning curve than some of the other frameworks, such as Tkinter.
 Here are some of the advantages of wxPython:
o Large library of widgets
o Native look-and-feel
o Highly flexible
o Helpful user community

 Kivy: An OpenGL ES 2 accelerated framework, Kivy was designed for the creation of new
MJKACC

user interfaces. It provides support for a variety of platforms like Windows, Mac, Linux,
Android, and iOS. The open-source library includes over 20 widgets in its toolkit.
 Kivy was written with a mix of Python and Cython, and it helps build some of the most
intuitive user interfaces with multi-touch applications. These multi-touch applications help
implement Natural User Interface (NUI), which is a type of interface where the user naturally
learns about the various interactions while they’re usually invisible.
 Kivy enables interface designers to code and deploy to multiple platforms, and the built-in
support for OpenGL ES 2 enables modern graphics and techniques.
 Here are some of the main advantages of Kivy:
o Based on Python
o Code written once can be used across all devices
o Easy-to-use widgets with multi-touch support
o Deploy to multiple platforms

 PySimpleGUI: PySimpleGUI was developed back in 2018 to make it easier for Python
beginners to get started with GUI development. A lot of the other frameworks require more
complicated work, but PySimpleGUI enables you to begin right away without worrying about
the advanced intricacies of other libraries.
 The framework relies on four other GUI frameworks: Qt, Tkinter, wxPython, and Remi. By
implementing most of the code, the difficulty of them falls dramatically. Beginners can pick
the GUI framework and have easy access to the visual elements that come with it, enabling
them to create intuitive user interfaces.

Page 161 of 201


CS-33: Programming in Python Chapter-4 Network Programming and GUI using Python

 Here are some of the main advantages of PySimpleGUI:


o Easy for beginners
o Doesn’t require advanced intricacies of other frameworks
o Uses Qt, Tkinter, wxPython, and Remi
o Create UIs based on favourite GUI framework

 Libavg: Libavg is a GUI framework that relies on Python as the scripting language. It is
widely considered one of the best libraries for developing user interfaces for modern touch-
based devices, and its hardware-acceleration is achieved through OpenGL and GPU shaders.
 The Python library has a wide range of features like camera support, animation support, text
alignment, GPU effects, and more. The advanced screen layout engine has rotation, scaling,
blending modes, cropping, and other visual element techniques.
 Libavg is written in C++, which helps it achieve fast execution times.
 Here are some of the main advantages of Libavg:
o Python as scripting language
o Wide range of features
o Advanced screen layout engine
o Written in C++

 PyForms: The PyForms GUI framework is the Python implementation of Windows Forms,
which enables developers to create highly interactive interfaces for Windows GUI mode,
Web mode, and Terminal mode.
 The open-source and cross-platform library makes it easy for developers to create
applications for multiple platforms without needing to make significant changes to the code.
It also provides instances of popular graphic-centric libraries like PyQT and Open GL.

MJKACC

PyForms can be broken down into three different sections: PyForms-GUI, PyForms-Web,
and PyForms-Terminal. Each layer enables the execution of the PyForms application as
Windows, or in Web or Terminal.
 Here are some of the main features of PyForms:
o Highly interactive interfaces for Windows GUI mode, Web mode, and Terminal mode
o Open-source
o Cross-platform
o Doesn’t require significant changes to code

 PySide2: Another top Python GUI library is PySide2, or QT for Python, which offers the
official Python bindings for Qt (PySide2). It enables the use of its APIs in Python
applications, and the binding generator tool can be used to expose C++ projects into Python.
 Qt is considered the golden standard for GUI design, with all other Python GUI frameworks
being measured against it. This means PySide2 enables Python developers to access a wide
collection of effective tools and libraries to quickly and flexibly create user interfaces.
 Here are some of the main advantages of PySide2:
o Cross platform
o Extensive community support and documentation
o Supports Python 3 and Python 2.7
o Used by big companies like Mercedes

 Wax: Nearing the end of our list is Wax, which is the wrapper for wxPython. Offering the
same functionality as wxPython, Wax stands out thanks to it being far more user-friendly.
Wax is also implemented as an extension module for Python, and it supports the development
of cross-platform applications.

Page 162 of 201


CS-33: Programming in Python Chapter-4 Network Programming and GUI using Python

 Wax was designed to create a simpler way to access Python elements and objects for building
GUIs. With the underlying platform being wxWindows, which is highly efficient, Wax has a
high level of efficiency and speed.
 Here are some of the main advantages of Wax:
o Open-source and cross-platform
o Easy-to-use
o Same functionality as wxPython
o Implemented as an extension module for Python

 PyGUI: Closing out our list of 10 best Python libraries for GUI is PyGUI, which is a simple
API that enables developers to create user interfaces with native elements for Python
applications. It is a lightweight framework requiring less code between the app and target
platform, which also ensures more efficiency.
 PyGUI supports the creation of applications across different systems, such as Windows
machines, MacOS devices, and Unix-based systems. The documentation for the library is in
Python, meaning you don't need to refer to other GUI libraries.
 Here are some of the main advantages of PyGUI:
o All documentation written in Python
o Available in Python 2 and 3
o Supports Python extensions like OpenGL and GTK
o Open-source and cross-platform

[Link] Python Tkinter Module


 As said before we will concentrate on the Tkinter module.
 Tkinter is a standard Python library used for GUI programming. It provides an object-
oriented interface to build the Tk GUI toolkit. It is a faster and easier way to build a GUI in
MJKACC

Python.
 The creation of a blank GUI interface is the first step of the creation of any GUI. This process
of creating a simple GUI in Tkinter requires the following steps:
 1. Importing the Tkinter library: We can import the Tkinter library by writing the below
code.
o import tkinter
 Creating the main window for the application:
 To create the main GUI window using the function Tk() function. The syntax of the Tk()
function is:
o Tk(screenName=None, baseName=None, className=’Tk’, useTk=1)
 All the arguments are optional. We can change the name of the window by setting the
className argument to your choice. This function returns the main window object which can
be used in the next steps.
 Adding the required widgets to the window:
 Tinter provides 19 widgets. We will discuss each of these in the next section.
 Calling the function mainloop():
 This is the function that gets triggered when an event occurs. This is an infinite loop that runs
till we close the application window.
 Now let us see the code to build a simple GUI.
# Import Module
from tkinter import *
# create root window
root = Tk()

Page 163 of 201


CS-33: Programming in Python Chapter-4 Network Programming and GUI using Python

# root window title and dimension


[Link]("Welcome to My Programming World")
# Set geometry (widthxheight)
[Link]('400x350')

# all widgets will be here


# Execute Tkinter
[Link]()

[Link] Tkinter Widgets


 Tkinter have 19 widgets in the Tkinter library which include text fields, labels, buttons, etc.
Before discussing the widgets let us use functions offered by Tkinter to organize these
widgets.
 Tkinter supports the below mentioned core widgets –

Widgets Description
Label It is used to display text or image on the screen
Button It is used to add buttons to your application
Canvas It is used to draw pictures and others layouts like texts, graphics etc.
ComboBox It contains a down arrow to select from list of available options
ComboBox It contains a down arrow to select from list of available options
It displays a number of options to the user as toggle buttons from which user can
CheckButton select any number of options.
It is used to implement one-of-many selection as it allows only one option to be
Radio Button selected MJKACC

Entry It is used to input single line text entry from user


Frame It is used as container to hold and organize the widgets
Message It works same as that of label and refers to multi-line and non-editable text
It is used to provide a graphical slider which allows to select any value from that
Scale scale
Scrollbar It is used to scroll down the contents. It provides a slide controller.
SpinBox It is allows user to select from given set of values
Text It allows user to edit multiline text and format the way it has to be displayed
Menu It is used to create all kinds of menu used by an application

Geometry Management
 Creating a new widget doesn’t mean that it will appear on the screen. To display it, we need
to call a special method: either grid, pack (example above), or place.
Method Description
pack() The Pack geometry manager packs widgets in rows or columns.
The Grid geometry manager puts the widgets in a 2-dimensional table.
grid() The master widget is split into a number of rows and columns, and each “cell” in the
resulting table can hold a widget.
The Place geometry manager is the simplest of the three general geometry managers
provided in Tkinter.
place()
It allows you explicitly set the position and size of a window, either in absolute terms,
or relative to another window.

Page 164 of 201


CS-33: Programming in Python Chapter-4 Network Programming and GUI using Python

 Now let us see each of these widgets:


 Button: To add a button to the window, we use the Button() method. Its syntax is given
below.
o btn=Button(master, option=value)
 The parent window is given as the master. Besides this, we have many other parameters that
set the features of the button. These include:
 Tkinter Button Widget Options:
 Following are the various options used with tkinter button widgets:
Option name Description
This option indicates the background of the button at the time when the mouse hovers
activebackground
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.
The command option is used to set the function call which is scheduled at the
command
time when the function is called.
This option mainly represents the font color of the button when the mouse hovers the
activeforeground
button.
fg This option represents the foreground color of the button.
font This option indicates the font of the button.
This option indicates the height of the button. This height indicates the number of text
height
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
This option is used to indicate the way by which the multiple text lines are represented.
justify 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.
MJKACC

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.
This option specifies the width of the button. For textual buttons, It exists as a number
width
of letters or for image buttons it indicates the pixels.
In the case, if this option's value is set to a positive number, the text lines will be
Wraplength
wrapped in order to fit within this length.
This option's value set to DISABLED to make the button unresponsive. The ACTIVE
state
mainly represents the active state of the button.

Example of creating a button.


from tkinter import *
win = Tk() ## win is a top or parent window
[Link]("200x100")
b = Button(win, text = "Submit")
[Link]() #using pack() geometry
[Link]()
Canvas
 This lets you draw shapes such as lines, polygons, etc., and other layouts like graphics, text,
and widgets. Its syntax is given below.
o can=Canvas (master, option=value)
 The parent window is given as the parameter master. In addition, we have parameters like:

Page 165 of 201


CS-33: Programming in Python Chapter-4 Network Programming and GUI using Python

Option Value
This option is mainly used to set the width of the border in pixels.
bd The default value of 0px means no border, 1px means thin line border and you can
increase the width of the border.
bg This option is used to set the background color.
Whether to use an arrow, dot, or circle on the canvas for the cursor, this option can
cursor
be used.
confine This option is set to make the canvas non-scrollable outside the scroll region.
height This option is used for controlling the height of the canvas.
width This option is used to set the width of the widget.
highlightcolor This option indicates the highlight color when there is a focus on the button
In the case, if the canvas is of scrollable type, then this attribute should act as
xscrollcommand
the set() method of the horizontal scrollbar
In the case, if the canvas is of scrollable type, then this attribute should act as
yscrollcommand
the set() method of the vertical scrollbar
This is option is mainly used to represent the coordinates that are specified as the
scrollregion
tuple containing the area of the canvas
If the value of this option is set to a positive value then, the canvas is placed only
xscrollincrement
to the multiple of this value.
It is mainly used for vertical movement and it works in the same
yscrollincrement
way xscrollincrement option works.
MJKACC

Example:
from tkinter import *
# window named top
top = Tk()
# set height and width of window
[Link]("300x300")
#creating a simple canvas with canvas widget
cv = Canvas(top, bg = "yellow", height = "300")
[Link]()
[Link]()

CheckButton
 This widget lets the display multiple options for the user to select. The user can select any
number of checkboxes. Its syntax is:
o cb=CheckButton(master, option=value)
 The parent window is given as the master. There are many other parameters related to the
check button like:

Option name Description


activebackground This option indicates the background color of the checkbutton at the time when
the checkbutton is under the cursor.
bd This option indicates the size of the border around the corner. The default size
is 2 pixels.
bg This option is used to represent the background color of the checkbutton.

Page 166 of 201


CS-33: Programming in Python Chapter-4 Network Programming and GUI using Python

Option name Description


bitmap This option is mainly used to display the image on the button.
command The command option is used to set the function call which is scheduled at the
time when the state of checkbutton is changed.
activeforeground This option mainly represents the foreground color of the button when the
checkbutton is under the cursor.
fg This option represents the text color of the checkbutton.
font This option indicates the font of the checkbutton.
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. the default value is 1.
image This option indicates the image representing the checkbutton.
cursor This option helps in changing the mouse pointer to the cursor name when it is
over the checkbutton.
disableforeground This option is the color which is used to indicate the text of a disabled
checkbutton.
higlightcolor This option indicates the highlight color when there is a focus on the checkbutton
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 padding of the checkbutton in the horizontal direction.
pady This option indicates the padding of the checkbutton in the vertical direction.
underline This option is used to underline the text of the checkbutton.
width This option specifies the width of the checkbutton. For textual buttons, It exists as
a number of letters or for image buttons it indicates the pixels.
MJKACC

Wraplength In the case If this option is set to an integer number, then the text will be broken
into the number of pieces.
variable This option is mainly used to represents the associated variable that is used to
track the state of the checkbutton
offvalue The associated control variable of checkbutton is set to 0 by default if the button
is (off). you can also change the state of an unchecked variable to some other
one.
onvalue The associated control variable of checkbutton will be set to 1 when it is set
(on). Any alternate value will be supplied for the on state by setting onvalue to that
value.
text This option is used to indicate the label just next to the checkbutton. For
multiple lines use "\n".
state This option mainly used to represent the state of the checkbutton. Its default
value= normal. It can be changed to DISABLED to make the checkbutton
unresponsive. The value of this button is ACTIVE when checkbutton is under
focus
selectcolor This option indicates the color of the checkbutton when it is set. Its default value
is Red.
selectimage This option indicates the image on the checkbutton when it is set.

Page 167 of 201


CS-33: Programming in Python Chapter-4 Network Programming and GUI using Python

 Tkinter Checkbutton Widget Methods: Following are the methods used with checkbutton
widgets:
Method
Description
Name
This method in checkbutton widget is used to invoke the method associated with the
invoke()
checkbutton.
select() This method in the checkbutton widget is called to turn on the checkbutton.
deselect() This method in the checkbutton widget is called to turn off the checkbutton.
This method in the checkbutton widget is used to toggle between the different
toggle()
Checkbuttons.
This method in the checkbutton widget is used to flashed between active and normal
flash()
colors.
Example:
from tkinter import *
root = Tk()
[Link]("300x300")
w = Label(root, text ='StudyTonight', fg="Blue",font = "100")
[Link]()
Checkbutton1 = IntVar()
Checkbutton2 = IntVar()
Checkbutton3 = IntVar()
Button1 = Checkbutton(root, text = "Homepage", variable = Checkbutton1, onvalue = 1,
offvalue = 0,
height = 2,
width = 10)
MJKACC

Button2 = Checkbutton(root, text = "Tutorials", variable = Checkbutton2, onvalue = 1,


offvalue = 0,
height = 2,
width = 10)
Button3 = Checkbutton(root, text = "Contactus", variable = Checkbutton3, onvalue = 1,
offvalue = 0,
height = 2,
width = 10)
[Link]()
[Link]()
[Link]()
mainloop()

Frame
 This widget acts as a container of other widgets. This is used to organize and position the
widgets. Its syntax is:
o frame=Frame(master, option=value)
 The parent window is given as the ‘master’ parameter. There are other parameters like:
 Tkinter Frame Widget Options:Following are the various options used with frame widgets:
Option Description
bd This option is used to represent the width of the border. Its default value is 2 pixels.
bg This option is used to indicate the normal background color of a widget.
With the help of this option, the mouse pointer can be changed to the cursor type which
cursor
is set to different values like an arrow, dot, etc.
height This option is used to indicate the height of the frame.

Page 168 of 201


CS-33: Programming in Python Chapter-4 Network Programming and GUI using Python

width This option is used to indicate the width of the frame.


highlightbackground This option denotes the color of the background color when it is under focus.
This option is used to specify the thickness around the border when the widget is under
highlightthickness
the focus.
relief This option specifies the type of the border of the frame. Its default value is FLAT
This option is mainly used to represent the color of the focus highlight when
highlightcolor
the frame has the focus.

Tkinter Frame Widget Example: Below we have a basic example where we will organize different
button widgets in a Frame widget. Let us see the code snippet given below:

from tkinter import *


root = Tk()
[Link]("300x150")
w = Label(root, text ='StudyTonight', font = "80")
[Link]()
frame = Frame(root)
[Link]()
bottomframe = Frame(root)
[Link](side = BOTTOM)
button1 = Button(frame, text ="Block1", fg ="red")
[Link](side = LEFT)
button2 = Button(frame, text ="Block2", fg ="brown")
[Link](side = LEFT)
button3 = Button(frame, text ="Block3", fg ="blue")
[Link](side = LEFT) MJKACC

button4 = Button(bottomframe, text ="Block4", fg ="orange")


[Link](side = BOTTOM)
button5 = Button(bottomframe, text ="Block5", fg ="orange")
[Link](side = BOTTOM)
button6 = Button(bottomframe, text ="Block6", fg ="orange")
[Link](side = BOTTOM)
[Link]()

Entry
 The Entry widget is mainly used to display a small text box that the user can type some text
into. There are the number of options available to change the styling of the Entry Widget.
 It is important to note that the Entry widget is only used to get a single-line text from the user
because in the case of multiline text the text widget will be used.
 This widget is mainly used to accept text strings from the user.
 The syntax of the entry widget is given below:
o w = Entry(master, option=value)
 In the above syntax, the master parameter denotes the parent window. You can use many
options to change the styling of the entry widget and these options are written as comma-
separated.
 Tkinter Entry Widget Options:Various options used with the entry widget are given below:
Option Name Description
bg This option is used for the background color of the widget.
This option is used for the width of the border in pixels. Its default value is 2
bd
pixels.

Page 169 of 201


CS-33: Programming in Python Chapter-4 Network Programming and GUI using Python

Option Name Description


This option helps in changing the mouse pointer to the cursor type and set it
cursor
to the arrow, dot, etc.
It is important to note that By Default, the text that is written inside the entry
exportselection box will get automatically copied to the clipboard. If you do not want to copy
the text then set the value of exportselection to 0.
fg This option is used to indicate the color of the text.
font This option is used to represent the font type of the text
This option is used to represent the color to display in the traversal highlight
highlightbackground
region when the widget does not have the input focus.
This option is used to represent the color to use for the traversal highlight
highlightcolor rectangle which is drawn around the widget when the widget has an input
focus.
This option is used to specify how the text is organized in the case if the text
justify
contains multiple lines.
This option is used to indicate the type of border. The default value of this
relief
option is FLAT. It has more values like GROOVE, RAISED,RIGID.
selectbackground This option is used to indicate the background color of the selected text.
selectforeground It is used to set the font of the selected task.
This option indicates the width of the border to display around the selected
selectborderwidth
task
width This option indicates the width of the image or width of text to display.
With the help of this option, you will be able to retrieve the current text from
textvariable your entry widget, you need to set this option to an instance of
the StringVar class. MJKACC

This option is used to show the entry text of some other type instead of the
show
string. For example, we type the password using stars (*).
You can link the entry widget to the horizontal scrollbar if you want the user
xscrollcommand
to enter more text rather then the actual width of the widget.
This option mainly represents the color to use as a background in the area
insertbackground covered by the insertion cursor. and thus this color will normally override the
normal background for the widget.

 Tkinter Entry Widget Methods: Various methods used with entry widgets are given below:
Method Name Description
delete(first, last=None) This method is used to delete the specified characters inside the widget.
get() This method is used to get the entry widget's current text as a string.
This method is used to set the insertion cursor just before the character at
icursor(index)
the specified index.
This method is used to place the cursor to the left of the character written
index(index)
at the specified index.
This method is used to clear the selection in the case if some selection has
select_clear()
been done.
If there is a presence of some selection then this method will
select_present()
return true otherwise, it will return false.
This method is mainly used to insert the specified string(s) before
insert(index, s)
the character placed at the specified index
This method mainly includes the selection of the character present at
select_adjust(index)
the specified index

Page 170 of 201


CS-33: Programming in Python Chapter-4 Network Programming and GUI using Python

Method Name Description


This method mainly sets the anchor index position to the character
select_form(index)
specified by the index.
This method is used to select the characters to exist between the specified
select_range(start, end)
range
This method mainly selects all the characters from the beginning to the
select_to(index)
specified index
xview(index) This method is used to link the entry widget to a horizontal scrollbar
xview_scroll(number, This method is mainly used to make the entry widget scrollable
what) horizontally

 Entry Widget Example: Below we have a basic example of the Tkinter Entry widget. Let us
see the code snippet:

from tkinter import *


win = Tk()
[Link]("400x250")
name = Label(win, text = "Name").place(x = 30,y = 50)
email = Label(win, text = "Email").place(x = 30, y = 90)
password = Label(win, text = "Password").place(x = 30, y = 130)
submitbtn = Button(win, text = "Submit",activebackground = "red", activeforeground
= "blue").place(x = 30, y = 170)
entry1 = Entry(win).place(x = 80, y = 50)
entry2 = Entry(win).place(x = 80, y = 90)
entry3 = Entry(win).place(x = 95, y = 130)
MJKACC

[Link]()

Label
 The syntax of the label widget is given below,
o W = Label(master,options)
 In the above syntax, the master parameter denotes the parent window. You can use
many options to configure the text and these options are written as comma-separated key-
value pairs.
 Tkinter Label Widget Options
Following are the options used with label widgets:
Option Description
This option is mainly used for controlling the position of text in the provided widget
anchor size. The default value is CENTER which is used to align the text in center in the
provided space.
bd This option is used for the border width of the widget. Its default value is 2 pixels.
This option is used to set the bitmap equals to the graphical object specified so that
bitmap
now the label can represent the graphics instead of text.
bg This option is used for the background color of the widget.
This option is used to specify what type of cursor to show when the mouse is moved
cursor
over the label. The default of this option is to use the standard cursor.
This option is used to specify the foreground color of the text that is written inside the
fg
widget.
font This option specifies the font type of text inside the label.
height This option indicates the height of the widget

Page 171 of 201


CS-33: Programming in Python Chapter-4 Network Programming and GUI using Python

Option Description
image This option indicates the image that is shown as the label.
This option specifies the alignment of multiple lines in the label. The default value
justify is CENTER. Other values are RIGHT, LEFT; you can justify according to your
requirement
This option indicates the horizontal padding of the text. The default value of
padx
this option is 1.
This option indicates the vertical padding of the text. The default value of this option
pady
is 1.
relief This option indicates the type of border. The default value of this option is FLAT
This option is set to the string variable and it may contain one or more than one line of
text
text
This option is associated with a Tkinter variable that is (StringVar) with a label. If you
textvariable change the value of this variable then text inside the label gets updated.

This option is used to underline a specific part of the text. The default value of this
underline option =-1(no underline); you can set it to any integer value up to n and counting
starts from 0.
width This option indicates the width of the widget.
Rather than having only one line as the label text, you can just break it to any number
wraplength
of lines where each line has the number of characters specified to this option.
 Label Widget Example Now let us see a basic example of the label widget and the code
snippet is given below:

import tkinter MJKACC

from tkinter import *


win = Tk()
var = StringVar()
label = Label( win, textvariable=var, relief=RAISED )
# set label value
[Link]("Hey!? Welcome to hene world")
[Link]()
[Link]()
 In the above code, we created a simple variable StringVar() and then assigned a value to it,
and this variable is assigned as value to the textvariable option of the Label widget.
 Tkinter Label Widget - Another Example: Below we have another code snippet for more
clear understanding. Let us see the code snippet given below:

from tkinter import *


win = Tk()
[Link]("400x250")
#creating a label
username = Label(win, text = "Username").place(x = 30,y = 50)
#creating second label
password = Label(win, text = "Password").place(x = 30, y = 90)
submitbutton = Button(win, text = "Submit",activebackground = "red", activeforeground =
"blue").place(x = 30, y = 120)
e1 = Entry(win,width = 20).place(x = 100, y = 50)
e2 = Entry(win, width = 20).place(x = 100, y = 90)
[Link]()

Page 172 of 201


CS-33: Programming in Python Chapter-4 Network Programming and GUI using Python

Listbox
 The syntax of the Tkinter Listbox widget is given below:
o W = Listbox(master, options)
 In the above syntax, the master parameter denotes the parent window. You can use
many options to change the look of the ListBox and these options are written as comma-
separated key-value pairs.
 Tkinter Listbox Widget Options: Following are the various options used with Listbox
widgets:
Option Description
bg This option indicates the background color of the widget.
This option is used to represent the size of the border. The default value is 2
bd
pixels.
With the help of this option, the mouse pointer will look like the cursor type
cursor
like dot, arrow, etc.
font This option indicates the font type of the Listbox items.
fg This option indicates the color of the text.
This option is used to represents the count of the lines shown in the Listbox.
height
The default value of this option is 10.
This option is used to indicate the color of the Listbox items when the widget
highlightcolor
is under focus.
highlightthickness This option is used to indicate the thickness of the highlight.
relief This option indicates the type of border. The default value is SUNKEN.
This option is used to indicate the background color that is used to display
selectbackground
the selected text.
This option is used to determine the number of items that can be selected from
selectmode MJKACC

the list. It can set to BROWSE, SINGLE, MULTIPLE, EXTENDED.


width This option is used to represent the width of the widget in characters.
xscrollcommand This option is used to let the user scroll the Listbox horizontally.
yscrollcommand This option is used to let the user scroll the Listbox vertically.
 Tkinter ListBox Widget Methods: Following are the methods associated with the Listbox
widget:
Method Description
activate(index) This method is mainly used to select the lines at the specified index.
This method is used to return a tuple containing the line numbers of the
curselection() selected element or elements, counting from 0. If nothing is selected,
return an empty tuple.
delete(first, last =
This method is used to delete the lines which exist in the given range.
None)
get(first, last = None) This method is used to get the list of items that exist in the given range.
This method is used to place the line with the specified index at the top of
index(i)
the widget.
This method is used to insert the new lines with the specified number of
insert(index, *elements)
elements before the specified index.
This method is used to return the index of the nearest line to the y
nearest(y)
coordinate of the Listbox widget.
This method is used to adjust the position of the Listbox to make the lines
see(index)
specified by the index visible.
This method returns the number of lines that are present in the Listbox
size()
widget.

Page 173 of 201


CS-33: Programming in Python Chapter-4 Network Programming and GUI using Python

Method Description
xview() This method is used to make the widget horizontally scrollable.
This method is used to make the Listbox horizontally scrollable by the
xview_moveto(fraction)
fraction of the width of the longest line present in the Listbox.
xview_scroll(number, This method is used to make the listbox horizontally scrollable by the
what) number of characters specified.
yview() This method allows the Listbox to be vertically scrollable.
This method is used to make the listbox vertically scrollable by the
yview_moveto(fraction)
fraction of the width of the longest line present in the Listbox.
yview_scroll (number, This method is used to make the listbox vertically scrollable by the
what) number of characters specified.
 Example: Below we have a basic example using this widget:
from tkinter import *
top = Tk()
[Link]("200x250")
lbl = Label(top, text="List of Programming Languages")
listbox = Listbox(top)
[Link](1,"Python")
[Link](2, "Java")
[Link](3, "C")
[Link](4, "C++")
[Link]()
[Link]()
[Link]()
MJKACC

Menu
 The syntax of the Tkinter Listbox widget is given below:
o W = Listbox(master, options)
 In the above syntax, the master parameter denotes the parent window. You can use
many options to change the look of the ListBox and these options are written as comma-
separated key-value pairs.
 Tkinter Listbox Widget Options: Following are the various options used with Listbox
widgets:
Option Description
bg This option indicates the background color of the widget.
This option is used to represent the size of the border. The default value is 2
bd
pixels.
With the help of this option, the mouse pointer will look like the cursor type
cursor
like dot, arrow, etc.
font This option indicates the font type of the Listbox items.
fg This option indicates the color of the text.
This option is used to represents the count of the lines shown in the Listbox.
height
The default value of this option is 10.
This option is used to indicate the color of the Listbox items when the widget
highlightcolor
is under focus.
highlightthickness This option is used to indicate the thickness of the highlight.
relief This option indicates the type of border. The default value is SUNKEN.
This option is used to indicate the background color that is used to display
selectbackground
the selected text.

Page 174 of 201


CS-33: Programming in Python Chapter-4 Network Programming and GUI using Python

Option Description
This option is used to determine the number of items that can be selected from
selectmode
the list. It can set to BROWSE, SINGLE, MULTIPLE, EXTENDED.
width This option is used to represent the width of the widget in characters.
xscrollcommand This option is used to let the user scroll the Listbox horizontally.
yscrollcommand This option is used to let the user scroll the Listbox vertically.
 Tkinter ListBox Widget Methods: Following are the methods associated with the Listbox
widget:
Method Description
activate(index) This method is mainly used to select the lines at the specified index.
This method is used to return a tuple containing the line numbers of the
curselection() selected element or elements, counting from 0. If nothing is selected,
return an empty tuple.
delete(first, last =
This method is used to delete the lines which exist in the given range.
None)
get(first, last = None) This method is used to get the list of items that exist in the given range.
This method is used to place the line with the specified index at the top of
index(i)
the widget.
This method is used to insert the new lines with the specified number of
insert(index, *elements)
elements before the specified index.
This method is used to return the index of the nearest line to the y
nearest(y)
coordinate of the Listbox widget.
This method is used to adjust the position of the Listbox to make the lines
see(index)
specified by the index visible.
This method returns the number of lines that are present in the Listbox
MJKACC

size()
widget.
xview() This method is used to make the widget horizontally scrollable.
This method is used to make the Listbox horizontally scrollable by the
xview_moveto(fraction)
fraction of the width of the longest line present in the Listbox.
xview_scroll(number, This method is used to make the listbox horizontally scrollable by the
what) number of characters specified.
yview() This method allows the Listbox to be vertically scrollable.
This method is used to make the listbox vertically scrollable by the
yview_moveto(fraction)
fraction of the width of the longest line present in the Listbox.
yview_scroll (number, This method is used to make the listbox vertically scrollable by the
what) number of characters specified.
 Example: Below we have a basic example using this widget:
from tkinter import *
top = Tk()
[Link]("200x250")
lbl = Label(top, text="List of Programming Languages")
listbox = Listbox(top)
[Link](1,"Python")
[Link](2, "Java")
[Link](3, "C")
[Link](4, "C++")
[Link]()
[Link]()
[Link]()

Page 175 of 201


CS-33: Programming in Python Chapter-4 Network Programming and GUI using Python

Menubutton
 This widget is used to provide various types of menus in the Python Application.
 It is important to note that every Menubutton in an application is associated with a Menu
widget and that in return can display the choices for that menubutton whenever the user
clicks on it.
 The Tkinter Menubutton widget provides the user with an option to select the appropriate
choice that exists within the application.
 The syntax of the Tkinter Menubutton widget is given below:
o W = Menubutton(master, options)
 In the above syntax, the master parameter denotes the parent window. You can use
many options to change the look of the menubuttons and these options are written as comma-
separated key-value pairs.
 Tkinter Menubutton Widget Options: Following are the various options used with Tkinter
Menubutton widgets:
Option Description
This option indicates the background color of the menubutton at the time when
activebackground
the mouse hovers the menubutton.
This option is used to represent the width of the border in pixels. The default
bd
value is 2 pixels.
This option will be set to the graphical content which is to be displayed to the
bitmap
widget.
bg This option is used to represent the background color of the widget.
cursor This option indicates the cursor when the mouse hovers the menubutton.
This option mainly represents the font color of the widget at the time when the
activeforeground
widget is under the focus MJKACC

fg This option represents the foreground color of the widget.


With the help of this option, you can specify the direction so that menu can
direction be displayed to the specified direction of the button. You can Use LEFT,
RIGHT, or ABOVE to place the widget accordingly.
disabledforeground This option indicates the text color of the widget when the widget is disabled
This option indicates the height of the menubutton. This height indicates
height 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 menubutton.
higlightcolor This option indicates the highlight color when there is a focus on the button
This option is used to indicate the way by which the multiple text lines are
justify 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.
This option indicates the additional padding of the widget in the horizontal
padx
direction.
This option indicates the additional padding of the widget in the vertical
pady
direction.
menu This option is used to indicate the menu associated with the menubutton
This option specifies the width of the widget. For textual buttons, It exists as a
width
number of letters or for image buttons it indicates the pixels
In this case, if this option's value is set to a positive number, the text lines will
Wraplength
be wrapped in order to fit within this length.
As the normal state of menubutton is [Link] can be set to disable to make
state
the menubutton unresponsive.

Page 176 of 201


CS-33: Programming in Python Chapter-4 Network Programming and GUI using Python

Option Description
text This option is used to indicate the text on the widget.
A control variable of class StringVar can be associated with this menubutton.
textvariable
If you will set that control variable then it will change the displayed text.
This option is mainly used to represent the index of the character in the text of
underline the widget which is to be underlined. The indexing generally starts with zero
in the text.
relief This option is used to specify the border type. Its default value is RAISED

 Example: Now let us see a code snippet for the Tkinter Menubutton widget:
from tkinter import *
import tkinter
win = Tk()
mbtn = Menubutton(win, text="Courses", relief=RAISED)
[Link]()
[Link] = Menu(mbtn, tearoff = 0)
mbtn["menu"] = [Link]
pythonVar = IntVar()
javaVar = IntVar()
phpVar = IntVar()
[Link].add_checkbutton(label="Python", variable=pythonVar)
[Link].add_checkbutton(label="Java", variable=javaVar)
[Link].add_checkbutton(label="PHP", variable=phpVar)
[Link]()
[Link]() MJKACC

Message
 Tkinter radiobutton widget is used to implement multiple-choice options that are mainly
created in user input forms.
 This widget offers multiple selections to the user and allows the user to select only one option
from the given ones. Thus it is also known as implementing one-of-many selection in a
Python Application.
 Also, different methods can also be associated with radiobutton.
 You can also display multiple line text and images on the radiobutton.
 Each radiobutton displays a single value for a particular variable.
 You can also keep a track of the user's selection of the radiobutton because it is associated
with a single variable
 The syntax of the Radiobutton widget is given below:
o W = Radiobutton(master, options)
 In the above syntax, the master parameter denotes the parent window. You can use
many options to change the look of the radiobutton and these options are written as comma-
separated key-value pairs.
 Tkinter Radiobutton Widget Options: Following are the options used with Tkinter
Radiobutton widgets:

option Description
This option is used to represent the exact position of the text within the
anchor widget, in the case of the widget contains more space than the requirement of
the text. The default value of this option is CENTER.
bg This option represents the background color of the widget.

Page 177 of 201


CS-33: Programming in Python Chapter-4 Network Programming and GUI using Python

option Description
This option represents the background color of the widget when it is under
activebackground
focus.
activeforeground This option represents the font color of the widget when it is under focus.
borderwidth This option is used to represent the size of the border.
If you want to display graphics on the widget then you can set this widget to
bitmap
any graphical or image object.
This option is used to set the procedure which must be called every
command
time when the state of the radiobutton is changed.
This option will convert the mouse pointer to the specified cursor type and it
cursor
can be set to an arrow, dot, etc.
font This option is used to represent the font type of the text of the widget.
This option is used to represent the foreground color of the text of the
fg
widget.
height This option indicates the vertical dimension of the widget
This option indicates the horizontal dimension of the widget and it is
width
represented as the number of characters.
padx This option represents the horizontal padding of the widget.
pady This option represents the vertical padding of the widget
This option is used to represent the color of the focus highlight when the
highlightcolor
widget is under the focus
This option is used to represent the color of the focus highlight when
highlightbackground
the widget is not under the focus.
If you want to display an image on the widget then this option will be set to
image
an image rather than the text
MJKACC

This option is used to represent the justification of the multiline text. The
justify
default value is CENTER. Other values are LEFT, RIGHT.
This option is used to represent the type of border. The default value
relief
is FLAT.
selectcolor This option indicates the color of the radiobutton when it is selected
This option indicates the image to be displayed on the radiobutton when it is
selectimage
selected
This option is used to represent the state of the radio button. The default state
state of the Radiobutton is NORMAL. You can also set the state to DISABLED in
order to make the radiobutton unresponsive.
text This option indicates the text to be displayed on the radiobutton.
This option is used to control the text represented by the widget.
textvariable The textvariable can be set to the text that is needed to be shown on the
widget.
This option can be set to an existing number in order to specify that nth letter
underline of the string will be underlined. Its default value is -1 which indicates no
underline
This option is also known as the control variable which is used to keep the
variable
track of user's choices. Thus this variable is shared among all radiobuttons.
This option of each radiobutton is assigned to the control variable when it is
value
turned on by the user.
This option is used to wrap the text to the number of lines just by setting this
wraplength option to the desired number so that each line contains only that number of
characters.

Page 178 of 201


CS-33: Programming in Python Chapter-4 Network Programming and GUI using Python

 Tkinter Radiobutton Widget Methods: Following are the various methods used with the
Tkinter Radiobutton widgets:
Method Description
deselect() This method is used to deselect or turns off the radio button
select() This method is used to select the radio button
This method is generally used to call a function when the state of radio button gets
invoke()
changed.
This method is generally used to flash the radio button between its normal and active
flash()
colors many times.
 Example: Below we have a basic example for the radio button widget. let us see the code
snippet for the Radiobutton widget:
#firstly ImportTkinter module
from tkinter import *
from [Link] import *
# Creating parent Tkinter window
win = Tk()
[Link]("200x200")
# let us create a Tkinter string variable
# that is able to store any string value
v = StringVar(win, "1")
# here is a Dictionary to create multiple buttons
options = {" Option A" : "1",
"Option B" : "2",
"Option C" : "3",
"Option D" : "4" MJKACC

}
# We will use a Loop just to create multiple
# Radiobuttons instaed of creating each button separately
for (txt, val) in [Link]():
Radiobutton(win, text=txt, variable=v, value=val).pack(side = TOP, ipady = 4)
mainloop()

Radiobutton
 Tkinter radiobutton widget is used to implement multiple-choice options that are mainly
created in user input forms.
 This widget offers multiple selections to the user and allows the user to select only one option
from the given ones. Thus it is also known as implementing one-of-many selection in a
Python Application.
 Also, different methods can also be associated with radiobutton.
 You can also display multiple line text and images on the radiobutton.
 Each radiobutton displays a single value for a particular variable.
 You can also keep a track of the user's selection of the radiobutton because it is associated
with a single variable
 The syntax of the Radiobutton widget is given below:
o W = Radiobutton(master, options)
 In the above syntax, the master parameter denotes the parent window. You can use
many options to change the look of the radiobutton and these options are written as comma-
separated key-value pairs.

Page 179 of 201


CS-33: Programming in Python Chapter-4 Network Programming and GUI using Python

 Tkinter Radiobutton Widget Options: Following are the options used with Tkinter
Radiobutton widgets:
Option Description
This option is used to represent the exact position of the text within the
anchor widget, in the case of the widget contains more space than the requirement of
the text. The default value of this option is CENTER.
bg This option represents the background color of the widget.
This option represents the background color of the widget when it is under
activebackground
focus.
activeforeground This option represents the font color of the widget when it is under focus.
borderwidth This option is used to represent the size of the border.
If you want to display graphics on the widget then you can set this widget to
bitmap
any graphical or image object.
This option is used to set the procedure which must be called every
command
time when the state of the radiobutton is changed.
This option will convert the mouse pointer to the specified cursor type and it
cursor
can be set to an arrow, dot, etc.
font This option is used to represent the font type of the text of the widget.
This option is used to represent the foreground color of the text of the
fg
widget.
height This option indicates the vertical dimension of the widget
This option indicates the horizontal dimension of the widget and it is
width
represented as the number of characters.
padx This option represents the horizontal padding of the widget.
pady This option represents the vertical padding of the widget
MJKACC

This option is used to represent the color of the focus highlight when the
highlightcolor
widget is under the focus
This option is used to represent the color of the focus highlight when
highlightbackground
the widget is not under the focus.
If you want to display an image on the widget then this option will be set to
image
an image rather than the text
This option is used to represent the justification of the multiline text. The
justify
default value is CENTER. Other values are LEFT, RIGHT.
This option is used to represent the type of border. The default value
relief
is FLAT.
selectcolor This option indicates the color of the radiobutton when it is selected
This option indicates the image to be displayed on the radiobutton when it is
selectimage
selected
This option is used to represent the state of the radio button. The default state
state of the Radiobutton is NORMAL. You can also set the state to DISABLED in
order to make the radiobutton unresponsive.
text This option indicates the text to be displayed on the radiobutton.
This option is used to control the text represented by the widget.
textvariable The textvariable can be set to the text that is needed to be shown on the
widget.
This option can be set to an existing number in order to specify that nth letter
of the string will be underlined. Its default value is -1 which indicates no
underline
underline

Page 180 of 201


CS-33: Programming in Python Chapter-4 Network Programming and GUI using Python

Option Description
This option is also known as the control variable which is used to keep the
variable
track of user's choices. Thus this variable is shared among all radiobuttons.
This option of each radiobutton is assigned to the control variable when it is
value
turned on by the user.
This option is used to wrap the text to the number of lines just by setting this
wraplength option to the desired number so that each line contains only that number of
characters.

 Tkinter Radiobutton Widget Methods:Following are the various methods used with the
Tkinter Radiobutton widgets:
Method Description
deselect() This method is used to deselect or turns off the radio button
select() This method is used to select the radio button
This method is generally used to call a function when the state of radio button gets
invoke()
changed.
This method is generally used to flash the radio button between its normal and active
flash()
colors many times.

 Example: Below we have a basic example for the radio button widget. let us see the code
snippet for the Radiobutton widget:
#firstly ImportTkinter module
from tkinter import *
from [Link] import *
# Creating parent Tkinter window MJKACC

win = Tk()
[Link]("200x200")
# let us create a Tkinter string variable
# that is able to store any string value
v = StringVar(win, "1")
# here is a Dictionary to create multiple buttons
options = {" Option A" : "1",
"Option B" : "2",
"Option C" : "3",
"Option D" : "4"
}
# We will use a Loop just to create multiple
# Radiobuttons instaed of creating each button separately
for (txt, val) in [Link]():
Radiobutton(win, text=txt, variable=v, value=val).pack(side = TOP, ipady = 4)
mainloop()

Scale
 In this tutorial, we will cover the Tkinter Scale widget in Python which is used to add
a graphical slider object which the user can slide and choose a number, as a numeric value is
attached to this slider scale and as you move the slider up/down or right/left the numeric
value attached to it increases or decreases and you can set the slider to the value you wish to
select. The sliding bar provided by the scale widget is helpful in selecting the values just by
sliding from left to right or top to bottom depending upon the orientation of the sliding bar in
our application.

Page 181 of 201


CS-33: Programming in Python Chapter-4 Network Programming and GUI using Python

 The scale widget is used as an alternative to the Entry widget if the purpose of the Entry
widget is to take numeric input from user within a given range of values.
 You can also control minimum and maximum values along with the resolution of the scale.
 The syntax of the Tkinter Scale widget is given below:
o W = Scale(master, options)
 In the above syntax, the master parameter denotes the parent window. You can use
many options to change the layout of the scale widget and these options are written as
comma-separated key-values.
 Tkinter Scale Widget Options: Following are the various options used with Tkinter Scale
widget:
Option Description
This option represents the background color of the widget when it is under
activebackground
focus.
bg This option represents the background color of the widget
This option represents the border size of the widget. The default value is 2
bd
pixels.
With the help of this option, the mouse pointer will be changed to a specific
cursor
cursor type and it can be an arrow, dot, etc.
This option will be set to the procedure which is called every time when we
command move the slider. If we move the slider rapidly, the callback to the procedure
is done when it settles.
When the control variable which is used to control the scale data is of string
digits type, then this option is mainly used to specify the number of digits when the
numeric scale is converted to a string.
fg This option indicates the foreground color of the text
MJKACC

font This option indicates the font type of the text


from_ This option is used to represent one end of the widget range.
highlightcolor This option indicates the highlight color when the widget is under the focus
This option indicates the highlight color when the widget is not under the
highlightbackground
focus
This option can be set to some text which then can be shown as a label with
label the scale. If the scale is horizontal then it is shown in the top left corner or if
the scale is vertical then it shown in the top right corner.
This option indicates the length of the widget. It represents the X dimension
length if the scale is in the horizontal direction and it represents the Y dimension if
the scale is in a vertical direction.
relief This option is used to specify the border type. Its default value is FLAT
This option can be set to either horizontal or vertical depending upon the type
orient
of the scale.
This option will be set to the smallest change which is made to the value of
resolution
the scale
This option is mainly used to tell the duration up to which the button is to be
repeatdelay pressed before the slider starts moving in that direction repeatedly. its default
value is 300 ms
This option represents the length of the slider window along the length of the
sliderlength scale. Its default value is 30 pixels. Also, you can change it to the appropriate
value.
By default, the value of the scale is shown in the text form, also we can set
showvalue
this option to 0 in order to suppress the label.

Page 182 of 201


CS-33: Programming in Python Chapter-4 Network Programming and GUI using Python

Option Description
By default, the state of the scale widget is active. To make it unresponsive
state
you can also set it to DISABLED
width This option is used to represent the width of the trough part of the widget
variable This option is used to represent the control variable for the scale
This option is used represents a float or integer value that specifies the other
to
end of the range represented by the scale
Generally, the focus will cycle through the scale widgets. If you don't want
takefocus
this behavior you can set this option to 0.
With the help of this option, scale values are displayed on the multiple of the
tickinterval
specified tick interval. The default value of this option is 0.
troughcolor This option is used to set the color for the trough

 Tkinter Scale Widget Methods: Following are the few methods used with Scale widgets:
 get(): This method is used to get the current value of the scale.
 set(value): This method is used to set the value of the scale.
 Tkinter Scale Widget - Horizontal Example: Below we have a basic example where we
will create a horizontal slide bar.
from tkinter import *
win = Tk()
[Link]("200x100")
v = DoubleVar()
scale = Scale( win, variable=v, from_=1, to=50, orient=HORIZONTAL)
[Link](anchor=CENTER)
btn = Button(win, text="Value") MJKACC

[Link](anchor=CENTER)
label = Label(win)
[Link]()
[Link]()
Scrollbar
 To scroll up or down or right or left the content in a Python desktop application, the
Tkinter Scrollbar widget is used.
 To scroll the content of other widgets like Listbox, canvas, etc we use this widget.
 Both Horizontal and Vertical scrollbars can be created in the Trinket Entry widget.
 The syntax of the Scrollbar widget is given below:
o W = Scrollbar(master, options)
 In the above syntax, the master parameter denotes the parent window. You can use
many options to configure your scrollbar widget and these options are written as comma-
separated key-value pairs.
 Tkinter Scrollbar Widget Options: Following are the various options used with Tkinter
Scrollbar widgets:
Option Description
This option represents the background color of the widget when it is under
activebackground
focus.
bg This option represents the background color of the widget
This option represents the border size of the widget. The default value is 2
bd
pixels.
With the help of this option, the mouse pointer will be changed to a specific
cursor
cursor type and it can be an arrow, dot, etc.

Page 183 of 201


CS-33: Programming in Python Chapter-4 Network Programming and GUI using Python

Option Description
This option will be set to the procedure associated which is called every time
command
the scrollbar is moved.
This option mainly represents the border width around the arrowheads and
elementborderwidth
the slider. The default value of this option is -1.
highlightthickness This option represents the thickness of the focus highlights
This option indicates the highlight color when the widget is not under the
highlightbackground
focus
highlightcolor This option indicates the highlight color when the widget is under the focus
This option is used to control the behavior of the scroll jump. If this option is
jump set to 1, then the callback is called at the time when the user releases the
mouse button.
This option can be set to either horizontal or vertical depending upon the
orient
orientation of the scrollbar.
width This option represents the width of the scrollbar.
troughcolor This option is used to set the color for the trough
By default, you can tab the focus through this widget. If you don't want this
takefocus
behavior you can set this option to 0.
This option is mainly used to tell the duration up to which the button is to be
repeatdelay pressed before the slider starts moving in that direction repeatedly. its default
value is 300 ms
repeatinterval The default value of this option is 100

 Tkinter Scrollbar Widget Methods: Few methods used with Tkinter Scrollbar widgets are:
 get(): This method returns the two numbers suppose a and b which represents the current
MJKACC

position of the scrollbar.


 Set(first, last): This method is used to connect the scrollbar to any other widget. That
is yscrollcommand or xscrollcommand of the other widget to this method.
 Tkinter Scrollbar Widget Example: Below we have a basic example of a scrollbar widget.
from tkinter import *
win= Tk()
sbb = Scrollbar(win)
[Link](side = RIGHT, fill = Y)
mylist = Listbox(win, yscrollcommand = [Link])
for line in range(45):
[Link](END, "Value " + str(line))
[Link](side = LEFT)
[Link](command = [Link])
mainloop()

Text
 The text widget is used to provide a multiline textbox (input box) because in Tkinter single-
line textbox is provided using Entry widget.
 You can use various styles and attributes with the Text widget.
 You can also use marks and tabs in the Text widget to locate the specific sections of the text.
 Media files like images and links can also be inserted in the Text Widget.
 There are some variety of applications where you need multiline text like sending
messages or taking long inputs from users, or to show editable long format text content in
application, etc. use cases are fulfilled by this widget.

Page 184 of 201


CS-33: Programming in Python Chapter-4 Network Programming and GUI using Python

 Thus in order to show textual information, we will use the Text widget.
 The syntax of the Text widget is given below:
o W = Text(master, options)
 In the above syntax, the master parameter denotes the parent window. You can use
many options to configure the text editor and these options are written as comma-separated
key-value pairs.
 Tkinter Text Widget Options: Following are the various options used with Text widgets:
Option Description
bd This option represents the border width of the widget.
bg This option indicates the background color of the widget.
This option is used to export the selected text in the selection of the window
exportselection manager. If you do not want to export the text then you can set the value of
this option to 0.
This option will convert the mouse pointer to the specified cursor type and it
cursor
can be set to an arrow, dot, etc.
font This option is used to indicate the font type of the text.
fg This option indicates the text color of the widget
This option indicates the vertical dimension of the widget and it is mainly in
height
the number of lines.
This option indicates the highlightcolor at the time when the widget isn't
highlightbackground
under the focus.
This option is used to indicate the thickness of the highlight. The default
higlightthickness
value of this option is 1.
This option indicates the color of the focus highlight when the widget is
highlightcolor
under the focus. MJKACC

insertbackground This option is used to represent the color of the insertion cursor.
padx This option indicates the horizontal padding of the widget.
pady This option indicates the vertical padding of the widget.
This option indicates the type of the border of the widget. The default value
relief
of this option is SUNKEN.
If the value of this option is set to DISABLED then the widget becomes
state
unresponsive to mouse and keyboard
This option is used to control how the tab character is used for the
tabs
positioning of the text
width This option represents the width of the widget and this is in characters.
To wrap wider lines into multiple lines this option is used. The default value
wrap of this option is CHAR which breaks the line which gets too wider at any
character
If you want to make the Text widget horizontally scrollable, then you can set
xscrollcommand
this option to the set() method of Scrollbar widget
If you want to make the Text widget vertically scrollable, then you can set
yscrollcommand
this option to the set() method of Scrollbar widget
spacing1 This option indicates the vertical space to insert above each line of the text.
This option is used to specify how much extra vertical space to add
spacing2 between displayed lines of text when a logical line wraps. The default value
of this option is 0
spacing3 This option indicates the vertical space to insert below each line of the text.
selectbackground This option indicates the background color of the selected text.
selectborderwidth This option indicates the width of the border around the selected text.

Page 185 of 201


CS-33: Programming in Python Chapter-4 Network Programming and GUI using Python

Option Description
This option represents the time amount in Milliseconds and during this time
insertofftime
the insertion cursor is off in the blink cycle
This option represents the time amount in Milliseconds and during this time
insertontime
the insertion cursor is on in the blink cycle
In order to represent the width of the border around the cursor, we use this
insertborderwidth
option. The default value of this option is 0.

 Tkinter Text Widget Methods: Some methods used with the text widget are given below:
Method Description
index(index) This method is used to get the specified index.
This method returns true or false on the basis that if the string is visible
see(index)
or not at the specified index.
insert(index,string) This method is used to insert a string at the specified index.
get(startindex,endindex) This method returns the characters in the specified range
delete(startindex,endindex) This method deletes the characters in the specified range

Methods for Tag Handling


 Mainly tags are used to configure different areas of the text widget separately. Tag is
basically the name given to separate areas of the text. Some Methods for handling tags are
given below:
 tag_config(): To configure the properties of the tag this method will be used.
 Tag_add(tagname, startindex, endindex): This method is mainly used to tag the string that
is present at the specified index.
 tag_delete(tagname): This method is mainly used to delete the specified tag.
MJKACC

 Tag_remove(tagname, startindex, endindex): To remove the tag from the specified range
this method is used.

Methods for Mark Handling


 In a given text widget in order to bookmark specified positions between the
characters Mark is used. Some methods for the same are given below:
 index(mark): This method is mainly used to get the index of the mark
 specified.mark_names(): This method is used to get all the names of the mark in the range
in the text widget.
 mark_gravity(mark, gravity): To get the gravity of the given mark this method will be
used.
 Mark_set(mark, index): This method is used to inform the new position of the given mark.
 Mark_unset(mark): In order to remove the given mark from the text this method will be
used.
 Tkinter Text Widget Example: Let us discuss a basic example for the text widget. The code
snippet for the example of the text widget is given below:
import tkinter as tk
from tkinter import *
win = Tk()
#to specify size of window.
[Link]("250x170")
# To Create a text widget and specify size.
T = Text(win, height = 6, width = 53)
# TO Create label

Page 186 of 201


CS-33: Programming in Python Chapter-4 Network Programming and GUI using Python

l = Label(win, text = "Quote for the Day")


[Link](font =("Courier", 14))
Quote = """Success usually comes to those who are too busy to be looking for it"""
# Create a button for the next text.
b1 = Button(win, text = "Next", )
# Create an Exit button.
b2 = Button(win, text = "Exit", command = [Link])
[Link]()
[Link]()
[Link]()
[Link]()
# Insert the Quote
[Link]([Link], Quote)
[Link]()

Toplevel
 With the help of the Tkinter Toplevel widget, you can provide extra information to the user in
a separate window on top of the parent window.
 This top-level window created using the Toplevel widget is directly organized and
managed by the window manager.
 It is not necessary for the top-level windows to have parents on their top.
 You can create multiple top-level windows one over the other.
 Top-level windows created using Top-level widgets contain title bars, borders, and some
window decorations too.
 With the help of this widget, you can provide pop-ups, some extra information, or some
MJKACC

widgets on the new window if you want.


 The syntax of the Tkinter Toplevel widget is given below:
o W = Toplevel(master,options)
 In the above syntax, the master parameter denotes the parent window. You can use
many options to configure your Toplevel widget and these options are written as comma-
separated key-value pairs.
 Tkinter Toplevel Widget Options: Following are the various options used with Tkinter
Toplevel widgets are given below:
Option Description
bd To represent the border size of the window
bg To represent the background color of the window
Generally, the text selected in the text widget is simply exported to be selected to the
class_ window manager. You can also set the value of this option to 0 to make this kind of
behavior false.
This option will convert the mouse pointer to the specified cursor type and it can be set to
cursor
an arrow, dot, etc.
width This option is used to represent the width of the window
height This option is used to represent the height of the window
font This option indicates the font type of the text to be inserted into the widget.
fg This option is used to indicate the foreground color of the widget.
relief This option indicates the type of the window.

Page 187 of 201


CS-33: Programming in Python Chapter-4 Network Programming and GUI using Python

 Tkinter Toplevel Widget Methods: Following are the various methods used with Tkinter
Toplevel widgets are given below:
Method Description
title(string) This method is used to define the title for the window.
This method is used to delete the window but it would not destroy the
withdraw()
window.
positionfrom(who) This method is used to define the position controller
sizefrom(who) This method is used to define the size controller.
minsize(width,height) This method is used to declare the minimum size for the window
maxsize(width,height) This method is used to declare the maximum size for the window
This method is used to control whether the window can be resizable or
resizable(width,height)
not.
transient([master]) This method is used to convert the window into a temporary window
iconify() This method is used to convert the top-level window into an icon.
deiconify() This method is mainly used to display the window.
frame() To indicate a system-dependent window identifier this method is used.
This method is used to add a top-level window to a specified window
group(window)
group
This method is used to indicate a function which will be called for the
protocol(name,function)
specific protocol
This method is used to get the current state of the window. Some Possible
state()
values of this option are normal, iconic, withdrawn, and icon.
 Tkinter Toplevel Widget Example: Below we have a basic example where we will create a
simple top-level window.
from tkinter import * MJKACC

win = Tk()
[Link]("200x200")
def open():
top = Toplevel(win)
[Link]()
btn = Button(win, text="open", command=open)
[Link](x=75, y=50)
[Link]()
SpinBox
 This widget is an alternative to Entry widget, when we want user to enter a numeric value
within a specific range.
 This widget is used only in the case where users need to chose from a given range of choices.
 The syntax of the Spinbox widget is given below:
o w = Spinbox(master, option=value)
 In the above syntax, the master parameter denotes the parent window. You can use
many options to configure your spinbox widget and these options are written as comma-
separated key-value pairs.
 Tkinter Spinbox Widget Options: Following are the various options used with Tkinter
Spinbox widgets:
Option Description
bg This option is used for the background color of the widget.
bd This option is used for the border width of the widget
This option is used to indicate the associated function with the widget which
command
is called every time the state of the widget is changed.

Page 188 of 201


CS-33: Programming in Python Chapter-4 Network Programming and GUI using Python

Option Description
With the help of this option, your mouse pointer type can be changed to the
cursor
cursor type that is assigned to this option.
This option indicates the background color of the widget when it is under
activebackground
the focus
This option is used to indicate the background color of the widget when it
disabledbackground
is disabled.
This option is used to indicate the foreground color of the widget when it is
disabledforeground
disabled.
font This option specifies the font type of text inside the widget.
fg This option specifies the foreground color of the widget.
This option is mainly used for the format string. There is no default value of
format
this option.
from_ This option is used to indicate the starting range of the widget
This option specifies the alignment of multiple lines in the label. The default
justify
value is LEFT. Other values are RIGHT and CENTER.
This option indicates the type of border. The default value of this option
relief
is SUNKEN.
This option is used to represent the state of the widget. The default value of
state
this option is NORMAL. Other values are "DISABLED", "read-only", etc.
validate This option is used to control how to validate the value of the widget
This option represents the maximum limit of the widget value. The other
to
value is specified by the from_ option
This option is mainly used to control the autorepeat button. The value here is
repeatdelay
in milliseconds. MJKACC

This option is similar to repeatdelay option. The value here is also given in
repeatinterval
milliseconds.
This option is associated with the function callback that is used for
validatecommand
the validation of the content of the widget.
This option is mainly used with the set() method of the scrollbar widget to
xscrollcommand
make this widget horizontally scrollable
wrap This option is mainly used to wrap-up the up and down button of the Spinbox
width This option indicates the width of the widget.
vcmd This option is similar to validatecommand.
values This option represents the tuple which contains the values for the widget
textvariable It is a control variable that is used to control the text of the widget

 Tkinter Spinbox Widget Methods:Following are the various methods used with Tkinter
Spinbox widget:
Method Name Description
This method is used to invoke the callback that is associated with the
invoke(element)
widget.
We use this method mainly to insert the string at the given specified
insert(index,string)
index
index(index) To get the absolute value of the given index this method will be used
This method is used to identify the widget's element in the specified
identify(x,y)
range
get(startindex, endindex) This method is used to get the characters in the specified range
delete(startindex, endindex) This method is used to delete the characters in the specified range

Page 189 of 201


CS-33: Programming in Python Chapter-4 Network Programming and GUI using Python

 Tkinter Spinbox Widget Example: Below we have a basic example of the Spinbox widget.
Let us see the code snippet given below:
from tkinter import *
win = Tk()
[Link]("300x200")
w = Label(win, text ='StudyTonight', fg="navyblue",font = "50")
[Link]()
sp = Spinbox(win, from_= 0, to = 50)
[Link]()
[Link]()

PanedWindow
 This widget arranges child widgets either in a vertical or in a horizontal manner.
 It is also known as the Geometry Manager widget.
 This widget is used to implement different layouts in a Python desktop application created
using the Tkinter module.
 The child widgets inside the PanedWindow widget can be resized by the user by moving
separator lines sashes using the mouse.
 You can implement multiple panes using the PanedWindow widget.
 Here is a simple Tkinter application window with three widgets stacked vertically inside a
PanedWindow widget.

MJKACC

 The syntax of the PanedWindow widget is given below:


o W = PanedWindow(master, options)
 In the above syntax, the master parameter denotes the parent window. You can use many
options to change the look of the PanedWindow and these options are written as comma-
separated.
 Tkinter PanedWindow Widget Options: Following are the various options used with
PanedWindow widget:
Option Description
This option is used to represent the 3D border size of the widget. The default value of
bd this option indicates that the trough contains no border and the arrowheads and slider
contain the 2-pixel border size.
bg This option represents the background color of the widget.
This option will convert the mouse pointer to the specified cursor type and it can be
cursor
set to an arrow, dot, etc.
This option is used to indicate the border width of the widget. The default value of
borderwidth this option is 2 pixels.

Page 190 of 201


CS-33: Programming in Python Chapter-4 Network Programming and GUI using Python

Option Description
To represents the distance between the handle and the end of the sash we use this
handlepad option. In horizontal orientation, it is the distance between the top of the sash and the
handle. The default value of this option is 8 pixels
This option represents the height of the widget. If we do not specify the height then
height
the height will be calculated by the height of the child widgets.
This option represents the size of the handle and its default value is 8 pixels. Also,
handlesize
the handle will always be in square
The value of this option will be set to HORIZONTAL if we want to place the child
orient windows side by side. If we want to place the child windows from top to bottom then
the value of this option will be set to VERTICAL.
This option is used to represent the padding to be done around each sash. The default
sashpad
value of this option is 0.
This option indicates the width of the sash. The default value of this option is 2
sashwidth
pixels.
This option is used to represent the type of border around each of the sash. The
sashrelief
default value of this option is FLAT
To display the handles, the value of this option should be set to true. The default
showhandle
value of this option is false.
This option represents the width of the widget. If we do not specify the height then
width
the height will be calculated by the height of the child widgets.
relief This option indicates the type of border. The default value of this option is FLAT.

 Tkinter PanedWindow Widget Methods: Following are some methods used with
PanedWindow widget: MJKACC

Method Description
This method is mainly used to configure any widget with some specified
config(options)
options.
get(startindex,endindex) This method is used to get the text at the specified given range.
add(child,options) This method is used to add a window to a parent window.

 Tkinter PanedWindow Widget Example: Below we have a basic example for the
understanding of the PanedWindow widget. Let us see the code snippet given below:
from tkinter import *
# event handler for button
def addition():
x = int([Link]())
y = int([Link]())
leftdata = str(x+y)
[Link](1, leftdata)
# first paned window
w1 = PanedWindow()
[Link](fill=BOTH, expand=1)
leftinput = Entry(w1, bd=5)
[Link](leftinput)
# second paned window
w2 = PanedWindow(w1, orient=VERTICAL)
[Link](w2)
e1 = Entry(w2)
e2 = Entry(w2)

Page 191 of 201


CS-33: Programming in Python Chapter-4 Network Programming and GUI using Python

[Link](e1)
[Link](e2)
bottomBtn = Button(w2, text="Addition", command=addition)
[Link](bottomBtn)
mainloop()

LabelFrame:
 This widget is a bordered container widget and is used to group the related widgets in a
Tkinter application to provide a better user experience to the user.
 For example, we can group the radiobutton widgets used in an application using the
labelframe widget.
 One can also add a title for the LabelFrame widget(we will see this in the code example).
 The LabelFrame widget is simply a variant of the Frame widget and it has all the features of a
frame.
 Note: If you have used HTML for web development, then the labelframe is just like HTML
fieldset tag.
 The syntax of the LabelFrame widget is given below. Let us see:
o w = LabelFrame(master, option=value)
 In the above syntax, the master parameter denotes the parent window. You can use
many options to configure the labelframe and these options are written as comma-separated
key-value pairs.
 Tkinter LabelFrame Widget Options: Following are the various options used with
LabelFrame widgets:
Option Description
height This option is used to represent the height of the widget.
MJKACC

width This option is used to represent the width of the frame.


text This option represents the string containing the text of the Label.
This option represents the style of the [Link] default value of this option
relief
is GROOVE
padx This option represents the horizontal padding of the widget
pady This option represents the vertical padding of the widget
font This option represents the font type of the text of the widget
highlighthickness This option represents the width of the focus highlight border
This option indicates the color of the focus highlight border at the time when
highlightbackground
the widget doesn't have the focus
This option indicates the color of the focus highlight when the widget is
highlightcolor
under the focus
bg This option indicates the background color of the widget
This option is used to represent the size of the border around the
bd
[Link] default value of this option is 2 pixels.
Class The default value of this option is LabelFrame.
This option is mainly used to specify which colomap to be used for this
[Link] the help of this option, we can reuse the colormap of another
colormap
window on this [Link] colormap means 256 colors that are used to form
the graphics
The LabelFrame becomes the container widget if we will set the value of this
container
option to [Link] default value of this option is false
This option will convert the mouse pointer to the specified cursor type and it
cursor
can be set to an arrow, dot, etc

Page 192 of 201


CS-33: Programming in Python Chapter-4 Network Programming and GUI using Python

Option Description
fg This option is used to indicate the foreground color of the widget
This option represents the exact position of the text inside the widget. The
labelAnchor
default value of this option is NW(north-west)
This option indicates the widget to be used for the label. Also,the frame uses
labelwidget
the text for the label if no value specified

 Tkinter LabelFrame Widget Example: Below we have a basic example of the LabelFrame
widget. Let us see the code snippet given below:
from tkinter import *
win = Tk()
[Link]("300x200")
labelframe1 = LabelFrame(win, text="Happy Thoughts!!!")
[Link](fill="both", expand="yes")
toplabel = Label(labelframe1, text="You can put your happy thoughts here")
[Link]()
labelframe2 = LabelFrame(win, text = "Changes You want!!")
[Link](fill="both", expand = "yes")
bottomlabel = Label(labelframe2, text = "You can put here the changes you want,If any!")
[Link]()
[Link]()

MeesageBox
 In order to display message boxes in a desktop application, we use the MessageBox module
in Tkinter.
 There are various functions present in this module which helps to provide an appropriate type
MJKACC

of message according to the requirement.


 With the help of this module, we can create pop-up message boxes to take user input.
 The functions of the MessageBox module are as follows: showError(), askretrycancel(),
showwarning(), etc., all of which are used to create a messagebox.
 To use the messagebox module, we first need to import it in our python script:
o from tkinter import messagebox
 Then following is the basic syntax to use the messagebox:
o messagebox.function_name(title, message [, options])
 In the above syntax, we have used the following:
 function_name: This is used to indicate the name of the appropriate MessageBox Function.
 Title: This is used to indicate the text to be displayed in the title bar of the appropriate
message box.
 Message: This is used to indicate the text to be displayed as a message in the message box.
 Options: It is used to indicate various options in order to configure the MessageBox. There
are two values of it and these are default and parent.
 default: It is used to specify a default button such as ABORT, RETRY, IGNORE.
 parent: It is used to specify a window on the top of which we will display the MessageBox.
 The functions present in the MessageBox module uses the same syntax but the functionalities
of each function are different.
 Let us see a few functions of the Tkinter MessageBox module.
 Tkinter MessageBox - showwarning(): This method is used to display any warning to the
user in a Python application.

Page 193 of 201


CS-33: Programming in Python Chapter-4 Network Programming and GUI using Python

 Here is a code for the same:


from tkinter import *
from tkinter import messagebox
win = Tk()
[Link]("200x200")
[Link]("warning","This is a Warning")
[Link]()

 Tkinter MessageBox - askquestion(): This method in MessageBox is mainly used to ask


some question to the user which can be answered either in Yes or No.
 The code for this method is as follows:
from tkinter import *
from tkinter import messagebox
win = Tk()
[Link]("100x100")
[Link]("Confirm","Are you sure about it?")
[Link]()

MJKACC

 Tkinter MessageBox - askretrycancel(): If you want to ask a user to do any particular


task or not then this method will be used.
 Let us see the code for the same:
from tkinter import *
from tkinter import messagebox
win= Tk()
[Link]("100x100")
[Link]("Application"," wanna try again?")
[Link]()

Page 194 of 201


CS-33: Programming in Python Chapter-4 Network Programming and GUI using Python

 Tkinter MessageBox - showerror(): To display an error message this method will be used.
 Let us see the code snippet given below:
from tkinter import *
from tkinter import messagebox
top = Tk()
[Link]("100x100")
[Link]("errorWindow","oops!!!Error")
[Link]()

MJKACC

Page 195 of 201


CS-33: Programming in Python Chapter-5 Connecting with Database

5.0 Installing MySQL Connector Package in Python


 MySQL is a Relational Database Management System (RDBMS) whereas the structured
Query Language (SQL) is the language used for handling the RDBMS using commands i.e
Creating, Inserting, Updating and Deleting the data from the databases.
A connector is employed when we have to use MySQL with other programming languages.
The work of mysql-connector is to provide access to MySQL Driver to the required language.
Thus, it generates a connection between the programming language and the MySQL Server.
 Installation: To install Python-mysql-connector module, one must have Python and PIP,
preinstalled on their system. To check if your system already contains Python, go through the
following instructions:
 Open the Command line (search for cmd in the Run dialog (Window + R). Now run the
following command:
o python –version
 If Python is not present, go through How to install Python on Windows and Linux?
 mysql-connector method can be installed on Windows with the use of following command:
o pip install mysql-connector-python

5.1 Verifying the MySQL dB Interface Installation:


 Check if you’re getting the following messages after running pip command:
o Collecting mysql-connector-python
o Downloading packages
o Requirement already satisfied: setup tools in D:python\python 37-32\lib\site-packages
o Installing collected packages: mysql-connector-python
o Successfully installed mysql-connector-python-8.0.13
 Pip Command to install MySQL Connector Python
MJKACC

 MySQL Connector Python is available on [Link] so that you can install MySQL Connector
Python on any operating system using the pip command.
 You may use the following pip command to install MySQL Connector Python.
o pip install mysql-connector-python
 If you are facing any problem while installing mysql-connector-python, please mention the
version of the module and then try to install again. If you have any doubts regarding versions
and installation, refer to the above commands to install the correct version.

5.2 Working with MySQL Database


 Procedure To Follow In Python To Work With MySQL
1. Connect to the database.
2. Create an object for your database.
3. Execute the SQL query.
4. Fetch records from the result.
5. Informing the Database if you make any changes in the table. Create Connection
6. Start by creating a connection to the database.
7. Use the username and password from your MySQL database:
Example: Connection with mysql
import [Link]
mydb = [Link](host="localhost",user="root",password="")
print(mydb)

Page 196 of 201


CS-33: Programming in Python Chapter-5 Connecting with Database

5.2.0 Creating a Database


 To create a database in MySQL, use the "CREATE DATABASE" statement:
 Example: create a database named "Mydb108":

import [Link]
mydb = [Link](host="localhost",user="root",password="")
mycursor = [Link]()
[Link]("CREATE DATABASE MyDb108")

 Check if Database Exists: You can check if a database exist by listing all databases in your
system by using the "SHOW DATABASES" statement:
 Example: Return a list of your system's databases:
import [Link]
mydb = [Link](host="localhost",user="root",password="")
mycursor = [Link]()
[Link]("SHOW DATABASES")
for x in mycursor:
print(x)

5.2.1 Creating a Table


 To create a table in MySQL, use the "CREATE TABLE" statement.
 Make sure you define the name of the database when you create the connection
 Example: Create a table named Stud":

import [Link] MJKACC

mydb= [Link](host="localhost",user="root",password="",database="MyDB108")
mycursor = [Link]()
[Link]("CREATE TABLE Stud (name VARCHAR(255), address VARCHAR(255))")

5.2.2 Retrieving All Rows from a Table in python


 We can retrieve/fetch data from a table in MySQL using the SELECT query. This
query/statement returns contents of the specified table in tabular form and it is called as
result-set.
 Syntax: Following is the syntax of the SELECT query –
o SELECT column1, column2, columnN FROM table_name;
Example
import [Link]
mydb = [Link](host=”localhost”,user=”root”,password=””,database="MyDB108")
mycursor = [Link]()
[Link]("SELECT * FROM Stud")
myresult = [Link]()
for x in myresult:
print(x)

Page 197 of 201


CS-33: Programming in Python Chapter-5 Connecting with Database

5.2.3 Inserting Rows into a Table


 How to execute INSERT Query from Python to add a new row into the MySQL table.
 In this we will learn the following Python MySQL insert operations using a ‘MySQL
Connector’ module.
 Insert single and multiple rows into the database table.
 Use a parameterized query to insert a Python variable value (Integer, string, float, double, and
DateTime) into a database table. Connect to MySQL from Python
 Refer to Python MySQL database connection to connect to MySQL database from Python
using MySQL Connector module
1. Define a SQL Insert query
 Next, prepare a SQL INSERT query to insert a row into a table. in the insert query, we
mention column names and their values to insert in a table.
 For example,
o INSERT INTO mysql_table (column1, column2, …) VALUES (value1, value2, …);

2. Get Cursor Object from Connection


 Next, use a [Link]() method to create a cursor object. This method creates a new
MySQLCursor object.

3. Execute the insert query using execute() method


 Execute the insert query using the [Link]() method. This method executes the
operation stored in the Insert query.

4. Commit your changes


 After the successful execution of a query make changes persistent into a database using the
MJKACC

commit() of a connection class.

5. Get the number of rows affected


 After a successful insert operation, use a [Link] method to get the number of rows
affected. The count depends on how many rows you are Inserting.

6. Verify result using the SQL SELECT query


 Execute a MySQL select query from Python to see the new changes.

7. Close the cursor object and database connection object


 Use [Link]() and [Link]() method to close open connections after your work
completes.

Inserting Rows into table

Page 198 of 201


CS-33: Programming in Python Chapter-5 Connecting with Database

Example
import [Link]
try:
connection = [Link](host='localhost', database='MyDB108', user='', password='')
mySql_insert_query = """INSERT INTO Stud (Id, Name, Class, City)
VALUES (%s, %s, %s, %s) """
records_to_insert = [(1, 'Krishawa ', ‘TYBCA’, 'Rajkot'), (2, 'Dishwa',’TYBCA’ , 'Rajkot'),
(3, 'Vishwa',’TYBCA’ , 'Rajkot')]
cursor = [Link]()
[Link](mySql_insert_query, records_to_insert)
[Link]()
print([Link], "Record inserted successfully into Stud table")
except [Link] as error:
print("Failed to insert record into MySQL table {}".format(error))
finally:
if connection.is_connected():
[Link]()
[Link]()
print("MySQL connection is closed")

 Note: Using [Link](sql_insert_query, records_to_insert) we are inserting


multiple rows (from a List) into the table.
 Using the [Link] we can find the number of records inserted.

5.2.4 Updating Rows in a Table


 How to execute a MySQL UPDATE query from Python to modify the MySQL table’s data.
MJKACC

 We will learn the following MySQL UPDATE operations from Python using a ‘MySQL
Connector’ module.
 Update single and multiple rows, single and multiple columns
 Use a Python variable in a parameterized query to update table rows.
 Also, Update a column with date-time and timestamp values
 The role of commit and rollback in the update operation.
Prerequisite
 Before executing the following program, make sure you have the following in place –
1. Username and password that you need to connect MySQL
2. MySQL database table name which you want to update.
3. Connect to MySQL from Python

 Refer to Python MySQL database connection to connect to MySQL database from Python
using MySQL Connector module

4. Prepare a SQL Update Query


 Prepare an update statement query with data to update. FOr example, UPDATE table_name
SET column1 = value1, column2 = value2 WHERE condition;

5. Execute the UPDATE query, using [Link]()


 Execute the UPDATE query using [Link]() method. This method execute the
operation stored in the UPDATE query.

Page 199 of 201


CS-33: Programming in Python Chapter-5 Connecting with Database

6. Commit your changes


 Make modification persistent into a database using the commit() of a connection class.

7. Extract the number of rows affected


 After a successful update operation, use a [Link] method to get the number of rows
affected. The count depends on how many rows you are updating.

8. Verify result using the SQL SELECT query


 Execute a MySQL select query from Python to see the new changes

9. Close the cursor object and database connection object


 Use [Link]() and [Link]() method to close open connections after your work
completes.

MJKACC

Updating Rows into table

Example
import [Link]
mydb = [Link](host="localhost",user="root",password="",database="MyDB108")
mycursor = [Link]()
sql = "UPDATE Stud SET address = 'Pune' WHERE id = '5'"
[Link](sql)
[Link]()
print([Link], "record(s) affected")

5.2.5 Deleting Rows from a Table


Follow these steps: – How to delete a row in MySQL using Python
1. Connect to MySQL from Python
 Refer to Python MySQL database connection to connect to MySQL database from Python
using MySQL Connector module

2. Define a SQL Delete Query


 Next, prepare a SQL delete query to delete a row from a table. Delete query contains the row
to be deleted based on a condition placed in where clause of a query.
 For example, DELETE FROM MySQL_table WHERE id=10;

3. Get Cursor Object from Connection: Next, use a [Link]() method to create a cursor
object. This method creates a new MySQLCursor object.

Page 200 of 201


CS-33: Programming in Python Chapter-5 Connecting with Database

4. Execute the delete query using execute() method


 Execute the delete query using the [Link]() method. This method executes the
operation stored in the delete query.
 After a successful delete operation, the execute() method returns us the number of rows
affected.

5. Commit your changes


 After successfully executing a delete operation, make changes persistent into a database using
the commit() of a connection class.

6. Get the number of rows affected


 Use a [Link] method to get the number of rows affected. The count depends on how
many rows you are deleting.
 You can also Execute a MySQL select query from Python to Verify the result.

7. Close the cursor object and database connection object


 Use [Link]() and [Link]() method to close open connections after your work
completes.

MJKACC

Deleting Rows into table

Example
import [Link]
mydb = [Link](host="localhost",user="root",password="",database="MyDB108")
mycursor = [Link]()
sql = "DELETE FROM Stud WHERE id = '5'"
[Link](sql)
[Link]()

5.2.6 Delete a Table Example

import [Link]
mydb = [Link](host="localhost",user="root",password="",database="MyDB108")
mycursor = [Link]()
sql = "DROP TABLE Stud"
[Link](sql)

Page 201 of 201


[Link]

You might also like