Python Programming Guide for BCA
Python Programming Guide for 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
Page 3 of 201
[CS-33] Programming in Python
Page 4 of 201
[CS-33] Programming in Python
Page 5 of 201
[CS-33] Programming in Python
Page 6 of 201
[CS-33] Programming in Python
Page 7 of 201
CS-33: Programming in Python ch-1 Introduction to Python
MJKACC MJKACC
Page 8 of 201
CS-33: Programming in Python ch-1 Introduction to Python
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”.
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.
Page 12 of 201
CS-33: Programming in Python ch-1 Introduction to Python
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
X = 1
X = “string
value”
Python allows you to assign a single value to several variables simultaneously.
a=b=c=1
Page 14 of 201
CS-33: Programming in Python ch-1 Introduction to Python
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
a,b=4,5
if a<b:
x="smaller"
else:
x="bigger"
print(x)
Page 15 of 201
String indexes starting at 0 in the beginning of the string and working their way from -1 at the
end.
Page 16 of 201
CS-33: Programming in Python ch-1 Introduction to Python
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
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
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
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
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
Page 20 of 201
CS-33: Programming in Python ch-1 Introduction to Python
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.
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
n_terms = 10
Output
Fibonacci series:
0
1
1
2
3 MJKACC
5
8
13
21
34
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.
if (n == 0):
return 1
MJKACC
return n * Recur_facto(n-1)
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.
Output
720
Page 24 of 201
CS-33: Programming in Python ch-1 Introduction to Python
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
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!
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
[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.
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
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.
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
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
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
MJKACC
Page 32 of 201
CS-33: Programming in Python Ch-2 OOP Using Python
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
my_list = [1, 2, 3]
try:
my_list[99]
except Exception as e:
print(e)
Page 35 of 201
CS-33: Programming in Python Ch-2 OOP Using Python
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.
Page 36 of 201
CS-33: Programming in Python Ch-2 OOP Using Python
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.
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
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
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.
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:
# initializing number
a =4 MJKACC
b =0
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)
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
Code:
# Python 3 code to demonstrate
# working of assert
# Application
# initializing list of foods temperatures
batch =[ 40, 26, 39, 30, 25, 21]
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.
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.
Example:
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
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:
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
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.
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.
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
So, we find that we can access the instance and class attributes just by using the dot operator.
Code:
class Human:
species = "Homo Sapiens"
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!!!
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
[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
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")
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}")
Output:
Hey! My name is Aaru, I'm a girl and I'm 20 years old
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.
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
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
Page 56 of 201
CS-33: Programming in Python Ch-2 OOP Using Python
def getSalary(self):
print(f"The salary of Employee is {self.__salary}")
def getSalary(self):
print(f"The salary of Employee is {self.__salary}")
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.
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
Page 58 of 201
CS-33: Programming in Python Ch-2 OOP Using Python
Code:
from abc import ABC
bike = Bike()
bike.no_of_wheels()
tempo = Tempo()
tempo.no_of_wheels()
truck = Truck()
truck.no_of_wheels()
Output:
Bike have 2 wheels MJKACC
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.
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]
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
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
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]
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
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
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
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)
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]:
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
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:
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.
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
MJKACC
Page 71 of 201
CS-33: Programming in Python Unit-3 Plotting Using PyLab
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
Page 72 of 201
CS-33: Programming in Python Unit-3 Plotting Using PyLab
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
Page 73 of 201
CS-33: Programming in Python Unit-3 Plotting Using PyLab
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]()
Page 74 of 201
CS-33: Programming in Python Unit-3 Plotting Using PyLab
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
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 –
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
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.
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
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 −
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.
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
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
MJKACC
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.
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.
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 −
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.
Page 82 of 201
CS-33: Programming in Python Unit-3 Plotting Using PyLab
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.
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
MJKACC
Page 85 of 201
CS-33: Programming in Python Unit-3 Plotting Using PyLab
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.
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
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)
Page 87 of 201
CS-33: Programming in Python Unit-3 Plotting Using PyLab
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 −
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 −
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
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.
MJKACC
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%.
MJKACC
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.
MJKACC
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
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
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
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)
MJKACC
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.
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
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
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')
MJKACC
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 −
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]()
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.
fig = [Link]()
ax = [Link](projection='3d')
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 −
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]()
MJKACC
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)
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.
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.
imgplot = [Link](img)
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.
[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 −
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.
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
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.
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))
# 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:
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.
MJKACC
MJKACC
Tabulation vs Memoization
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.
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
# Initialize to -1
dp = []
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.
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.
return x + y
n = 5;
# Function Call
print(fib(n))
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.
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.
# Helper Function
def fibo_helper(n, ans):
# Base case
if (n <= 1):
return n
# Calculate output
x = fibo_helper(n - 1, ans)
y = fibo_helper(n - 2, ans)
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.
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
# 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
# Drivers code
n=5
# Function Call
print(fibo(n))
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.
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]
}
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 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)]
# Directions
X = [-1, 0, 0, 1]
Y = [0, 1, -1, 0]
# 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)]
pq = deque()
[Link]((cx, cy))
# 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))
if __name__ == "__main__":
# Test case #1:
# .....*.
# ...#...
# .*.#.*.
# .......
r=4
c=7
# - initialization # - precalculations
init()
ans = solve(0, 1)
print("Minimum distance for the given grid : ", end='')
print(ans)
# Test Case #2
# ...#...
# ...#.*.
# ...#...
# .*.#.*.
# ...#...
]
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 :
.....*.
...#...
.*.#.*.
.......
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
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
F(1) = A0 + A1 = 19
F(2) = A0 + A2 = 21
F(3) = A0 + A1 + A2 + A3 = 49
Example
# Python 3 program
# for brute force
# approach of SumOverSubsets DP
# array to store
# the SumOverSubsets
sos = [0] * (1 << n)
# if i is a bitwise subset of x
if ((x & i) == i):
sos[x] += a[i]
# 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.
while i > 0:
sos[x] += a[i]
i = ((i - 1) & x)
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)
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
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.
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.
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.
[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.
while True:
c, addr = [Link]() # Establish connection with client.
print 'Got connection from', addr
[Link]('Thank you for connecting')
[Link]() # Close the connection
Now run this [Link] in background and then run above [Link] to see the result.
pprint(addrinfo)
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
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)
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
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
news()
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])
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
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.
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
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.
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')
[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
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')
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
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.
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.
[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()
[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()
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]()
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:
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.
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.
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.
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
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()
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
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.
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.
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:
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.
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
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.
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:
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.
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
Entry Widget Example: Below we have a basic example of the Tkinter Entry widget. Let us
see the code snippet:
[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
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:
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
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.
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]()
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
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.
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.
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.
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
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.
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
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.
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
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.
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.
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
Tag_remove(tagname, startindex, endindex): To remove the tag from the specified range
this method is used.
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
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.
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
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
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)
[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
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
MJKACC
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
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.
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)
mydb= [Link](host="localhost",user="root",password="",database="MyDB108")
mycursor = [Link]()
[Link]("CREATE TABLE Stud (name VARCHAR(255), address VARCHAR(255))")
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")
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
MJKACC
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")
3. Get Cursor Object from Connection: Next, use a [Link]() method to create a cursor
object. This method creates a new MySQLCursor object.
MJKACC
Example
import [Link]
mydb = [Link](host="localhost",user="root",password="",database="MyDB108")
mycursor = [Link]()
sql = "DELETE FROM Stud WHERE id = '5'"
[Link](sql)
[Link]()
import [Link]
mydb = [Link](host="localhost",user="root",password="",database="MyDB108")
mycursor = [Link]()
sql = "DROP TABLE Stud"
[Link](sql)