0% found this document useful (0 votes)
246 views

Python - 1 Year - Unit-5

The document discusses Python packages, modules, and loading modules in Python code. Packages are directories that can contain other packages and modules. Modules are files that contain reusable Python code. Modules can be loaded using import, from-import, or from-import * statements.

Uploaded by

Bessy Bijo
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
246 views

Python - 1 Year - Unit-5

The document discusses Python packages, modules, and loading modules in Python code. Packages are directories that can contain other packages and modules. Modules are files that contain reusable Python code. Modules can be loaded using import, from-import, or from-import * statements.

Uploaded by

Bessy Bijo
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 217

PYTHON PROGRAMMING

by
C. RAJEEV
C. RAJEEV
Assistant Professor,
Assist. Prof.
Department of CSE,
Dept. of. CSE,
MRECW MRECW.
UNIT V

Python Packages, Python Libraries, Python Modules, Collection Module, Math Module, OS

Module, Random Module, Statistics Module, Sys Module, Date & Time Module, Loading the

Module in our Python Code, import Statement, from-import Statement, Renaming a Module,

Regular Expressions, Command Line Arguments, Object Oriented Programming (OOPs),

Object-oriented vs Procedure-oriented Programming languages, Object, Class, Method,

Inheritance, Polymorphism, Data Abstraction, Encapsulation, Python Class and Objects, Creating

Classes in Python, Creating an Instance of the Class, Python Constructor, Creating the,

Constructor in Python, Parameterized Constructor, Non-Parameterized Constructor, In- built

Class Functions, In-built Class Attributes, Python Inheritance, Python Multi-Level Inheritance,

Python Multiple Inheritance, Method Overriding, Data Abstraction in Python,

Graphical User Interface (GUI) Programming, Python Tkinter, Tkinter Geometry, pack()
1. Python Packages:
Modular programming :
Modular programming refers to the process of breaking a large, unwieldy programming task
into separate, smaller, more manageable subtasks or modules. Individual modules can then be
cobbled together like building blocks to create a larger application.

There are several advantages to modularizing code in a large application :


1. Simplicity
2. Maintainability
3. Reusability

Functions, modules and packages are all constructs in Python that promote code


modularization.
Python Package:
Packages are also known as directories. A package can contain many other
packages and modules. Python has packages for directories and modules for files.

As our application program grows larger in size with a lot of modules, we place similar
modules in one package and different modules in different packages. This makes a project
(program) easy to manage and conceptually clear.

Similarly, as a directory can contain subdirectories and files, a Python package can have
sub-packages and modules.

Each package should have a file called__init__.py The __init__.py can be empty but


should exist that makes the regular directory a Python package.

 If the file __init__.py is present in a package, it specifies the package and


its modules can be imported.
Here is an example. Suppose we are developing a game. One possible organization of packages
and modules could be as shown in the figure below.

Importing module from a package


We can import modules from packages using the dot (.) operator.
For example, if we want to import the start module.
import Game.Level.start
Now, if this module contains a function named select_difficulty(), we must use the full name
to reference it.
Game.Level.start.select_difficulty(2)
if this construct seems lengthy, we can import the module without the package prefix as
follows:
from Game.Level import start
We can now call the function simply as follows:
start.select_difficulty(2)
Another way of importing just the required function (or class or variable) from a module
within a package would be as follows:
from Game.Level.start import select_difficulty
Now we can directly call this function.
select_difficulty(2)
Although easier, this method is not recommended. Using the full namespace avoids
confusion and prevents two same identifier names from colliding.
While importing packages, Python looks in the list of directories defined in sys.path, similar as
for module search path
We can see help function in python to get the list of modules installed.
>>>help("modules")
Python PIP (Preferred Installer Program ):
"Pip Installs Packages" or "Pip Installs Python“.
PIP is a package manager for Python packages, or modules.
PIP - is a package management system that helps in installing Python packages and managing
them. Many packages exist in the default source.
What is a Package?
A package contains all the files you need for a module. Modules are Python code libraries you
can include in your project.
Check if PIP is Installed
Navigate your command line to the location of Python's script directory, and type thefollowing:
Example
Check PIP version:
C:\Users\Your Name\AppData\Local\Programs\Python\Python36-32\Scripts>pip –version
Install PIP
If you do not have PIP installed, you can download and install it from this page: 
https://pypi.org/project/pip/
Download a Package
Downloading a package is very easy.
Open the command line interface and tell PIP to download the package you want.
Navigate your command line to the location of Python's script directory, and type the following:
Example
Download a package named "camelcase":
C:\Users\Your Name\AppData\Local\Programs\Python\Python36-32\Scripts>pip install camelcase

Using a Package
Once the package is installed, it is ready to use. Import the "camelcase" package into your project.
Example
Import and use "camelcase":
Program: capitalizes the first letter of each word in text
import camelcase Output: Hello
c = camelcase.CamelCase() World

txt = "hello world”


print(c.hump(txt)) #This method capitalizes the first letter of each word.
Find Packages
Find more packages at https://pypi.org/.
Remove a Package
Use the uninstall command to remove a package:
Example
Uninstall the package named "camelcase“:
C:\Users\Your Name\AppData\Local\Programs\Python\Python36-32\Scripts>pip uninstall camelcase

The PIP Package Manager will ask you to confirm that you want to remove the camelcase package:
Uninstalling camelcase-02.1:
Would remove:
c:\users\Your Name\appdata\local\programs\python\python36-32\lib\site-packages\camecase-0.2
py3.6.egg-info
c:\users\Your Name\appdata\local\programs\python\python36-32\lib\site-packages\camecase\*
Proceed (y/n)?
Press y and the package will be removed.
List Packages
Use the list command to list all the packages installed on your system:
Example
List installed packages:
C:\Users\Your Name\AppData\Local\Programs\Python\Python36-32\Scripts>pip list
Result:
Package Version
--------------------------------
camelcase 0.2
mysql-connector 2.1.6
pip 18.1
pymongo 3.6.1
setuptools 39.0.1

NOTE
In google coalb, !pip install Django
Features of PIP :

Pip stands for "Preferred Installer Program".

Pip is already installed for versions above Python 2.7.9 or Python 3 and above .

PIP can be installed through the system package manager or by invoking cURL,
a client-side data transfer tool.

PIP is used because it is easy to use it through the command-line interface.

Using PIP, installing python packages is just a single command.

Users not only install a package but also uninstall it very easily .

PIP also manages the list of packages along with its version numbers.
2. PYTHON MODULES
What are modules in Python?
If we need to reuse the code then we can define functions, but if we need to reuse

number of functions then we have to go for modules

Modules refer to a file containing Python statements and definitions.

A python module can be defined as a python program file which contains a python code
including python functions, class, or variables. 

for e.g.: example.py, is called a module and its module name would be example.

Modules provide reusability of code. Modules provides us the flexibility to organize the
code in a logical way.
To use the functionality of one module into another, we must have to import the
specific module.
Modules are three types:
1. Standard modules
2. User-defined modules
3. Third party modules
1.Standard modules:
 These modules are already defined and kept in python software .so, when we install
python then automatically these standards modules will install in our machine.
Ex: math, calender, os, sys,..etc
2. User-defined modules
 These modules are defined by user as per their requirement .so, here .py file contains
methods, variables, and classes.
3. Third party modules:
 These modules are already defined by some other people and kept in internet . So
that, we can download and install in our machines by using PIP(pyhton package
installing)
 PIP is a package management system used to install and manage software packages
written in python like.. Django, Flask, Pyramid ,SQLAlchemy, numpy, scipy,
3. Loading the Module in our Python Code
We can import module in three ways:
1. import <module_name>
2. from <module_name> import <method_name>
3. from <module_name> import *

1. import <module_name>:
 We can import all methods which is presented in that specified modules
Ex: import math
print(math.pi)
 We can import all methods which are available in math module
2. from <module_name> import <method_name>:
 This import statement will import a particular method from the module which is
specified in import statement.
Ex: from math import pi
print(pi)
 We cannot use other methods which are available in that module.
 But, we need to avoid this type of modules as they may cause name clashes in the
current python file
3. from <module_name> import * :
This import statement will import all methods from the specified module and also we
can import all names(definitions) from a module
all the functions and constants can be imported using *. 
Ex: from math import *
print(pi)
print(factorial(6))
importing everything with the asterisk (*) symbol is not a good programming
4. Renaming a Module
We can import a module by renaming it as follows.
>>> import math
>>> math.pi
3.141592653589793

>>> import math as m


>>> m.pi
3.141592653589793
5. Python Module Search Path
While importing a module, Python looks at several places. Interpreter first looks for a
built-in module.
Then(if built-in module not found), Python looks into a list of directories defined in
sys.path. The search is in this order.
1. The directory from which the input script was run or the current directory if the
interpreter is being run interactively.

2. The list of directories contained in the PYTHONPATH environment variable, if


it is set. (The format for PYTHONPATH is OS-dependent but should mimic
the PATH environment variable.)

3. An installation-dependent list of directories configured at the time Python is


installed
The resulting search path is accessible in the Python variable sys.path, which is obtained from a
module named sys:
>>> import sys
>>> sys.path

['','C:\\Users\\ajee\\AppData\\Local\\Programs\\Python\\Python37-32\\Lib\\idlelib', 'C:\\Users\\
ajee\\AppData\\Local\\Programs\\Python\\Python37-32\\python37.zip', 'C:\\Users\\ajee\\AppData\\
Local\\Programs\\Python\\Python37-32\\DLLs', 'C:\\Users\\ajee\\AppData\\Local\\Programs\\
Python\\Python37-32\\lib', 'C:\\Users\\ajee\\AppData\\Local\\Programs\\Python\\Python37-32',
'C:\\Users\\ajee\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages', 'C:\\Users\\
ajee\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages\\win32’,
'C:\\Users\\ajee\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site- packages\\
win32\\lib',
‘C:\\Users\\ajee\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages\\
Pythonwin‘]
In ubuntu python, module search path is like--
>>> import sys
>>> print '\n'.join(sys.path)
/usr/local/lib/python27.zip
/usr/local/lib/python2.7
/usr/local/lib/python2.7/plat-linux2
/usr/local/lib/python2.7/lib-tk
/usr/local/lib/python2.7/lib-old
/usr/local/lib/python2.7/lib-dynload
/usr/local/lib/python2.7/site-packages
It's possible to find out where a module is located after it has been imported, Using __file__
>>> import random # built_in module
>>> random.__file__
'C:\\Users\\ajee\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\random.py‘
>>> import fact # user defined module
enter a number:5
Factorial of 5 is: 120
>>> fact.__file__
'C:\\Users\\ajee\\AppData\\Local\\Programs\\Python\\Python37-32\\fact.py‘
But, __file__ attribute is not present for C modules that are statically linked into the interpreter.
Like math, sys, time, itertools modules
Output
>>> import math
Traceback (most recent call last):
>>> math.__file__
File "<pyshell#28>", line 1, in <module>
math.file
AttributeError: module 'math' has no attribute 'file'
To know the C modules that are statically linked into the interpreter.
Execute the below command
>>> import sys
>>> print(sys.builtin_module_names)

('_abc', '_ast', '_bisect', '_blake2', '_codecs', '_codecs_cn', '_codecs_hk', '_codecs_iso2022',


'_codecs_jp', '_codecs_kr', '_codecs_tw', '_collections', '_contextvars', '_csv', '_datetime',
'_functools', '_heapq', '_imp', '_io', '_json', '_locale', '_lsprof', '_md5', '_multibytecodec', '_opcode',
'_operator', '_pickle', '_random', '_sha1', '_sha256', '_sha3', '_sha512', '_signal', '_sre', '_stat',
'_string', '_struct', '_symtable', '_thread', '_tracemalloc', '_warnings', '_weakref', '_winapi', 'array',
'atexit', 'audioop', 'binascii', 'builtins', 'cmath', 'errno', 'faulthandler', 'gc', 'itertools', 'marshal',
'math', 'mmap', 'msvcrt', 'nt', 'parser', 'sys', 'time', 'winreg', 'xxsubtype', 'zipimport', 'zlib')
6. Reloading a module
The Python interpreter imports a module only once during a session. This makes things
more efficient.
Here is an example to show how this works.
Suppose we have the following code in a module named my_module.
my_module.py
# This module shows the effect of
# multiple imports and reload
print("This code got executed")

Now we see the effect of multiple imports.


>>> import my_module
This code got executed
>>> import my_module
>>> import my_module
We can see that our code got executed only once. This goes to say that our module was
imported only once.
Now if our module changed during the course of the program, we would have to reload it.
One way to do this is to restart the interpreter. But this does not help much.

Python provides a more efficient way of doing this. We can use the reload() function inside
the imp module to reload a module. We can do it in the following ways:
>>> import imp
>>> import my_module
This code got executed
>>> import my_module
>>> imp.reload(my_module)
This code got executed
<module 'my_module' from '.\\my_module.py'>
dir() built-in function
We can use the dir() function to find out names that are defined inside a module.
>>>import math
>>> dir(math)
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin',
'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp',
'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf',
'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf',
'nan', 'pi', 'pow', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']

Here, we can see a sorted list of names . All other names that begin with an underscore are
default Python attributes associated with the module (not user-defined).
For example, the __name__ attribute contains the name of the module.
import math
>>> math.__name__
'math’
All the names defined in our current namespace can be found out using the dir() function
without any arguments.

>>> import math


>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__',
'__spec__', 'math']
7. Python Collection Module
The Python collection module is defined as a container that is used to store collections of
data, for example - list, dict, set, and tuple, etc.
Collections module provides us with improved functionalities and highly optimized
alternatives to inbuilt Python containers like List, Tuple, Dictionary, etc.,
Python collection module was first introduced in its 2.4 release.
There are 6 most commonly used data structures in the collections modules.
1. Defaultdict: 
Defaultdict is exactly like a dictionary in python. The only difference is that it does not
give an exception/key error when you try to access the non-existent key.

In the following code, even though the 4th index was not initialized, the compiler still
returns a value, 0, when we try to access it.
In dicitionary, In collection,

dict={'one': 1, 'two': 2, 'three': 3} from collections import defaultdict  

#print(dict) nums = defaultdict(int)  

print(dict['one']) nums['one'] = 1  

print(dict['four']) nums['two'] = 2
Output nums['three'] = 3 
1 print(nums['three']) 
KeyError: 'four' print(nums['four']) 
Output
3
2. Counter
Counter is a built-in data structure which is used to count the occurrence of each value
present in an array or list.
Ex
from collections import Counter  
list = [1,2,3,4,1,2,6,7,3,8,1,2,2]  
answer = Counter(list)  
print(answer) 
print(answer[2])  
output
Counter({2: 4, 1: 3, 3: 2, 4: 1, 6: 1, 7: 1, 8: 1})
4
3. Deque
Deque is an optimal version of list used for inserting and removing items. It can add/remove
items from either start or the end of the list. In collections,
Ex In list,
from collections import deque  
list = ["a","b","c"]  
list = ["a","b","c"]  
list.append("z")
deq = deque(list)  
print(list)
print(deq)  
list.appendleft("z")
deq.append("z")
print(list)
print(deq)    
list.pop()
deq.appendleft("g")  
print(list)
print(deq)
list.popleft()
deq.pop()  
print(list) deque(['a', 'b', 'c'])
print(deq)
['a', 'b', 'c', 'z']
deq.popleft()   deque(['a', 'b', 'c', 'z'])
AttributeError: 'list' object has no
attribute‘appendleft' print(deq) deque(['g', 'a', 'b', 'c', 'z'])
['a', 'b', 'c'] deque(['g', 'a', 'b', 'c'])
AttributeError: 'list' object has no attribute 'popleft'
4. namedtuple( )
It returns a tuple with a named entry, which means there will be a name assigned to
each value in the tuple.

It overcomes the problem of accessing the elements using the index values.

With namedtuple( ) it becomes easier to access these values, since you do not have to
remember the index values to get specific elements.

The namedtuple() function returns a tuple-like object with named fields. These field


attributes are accessible by lookup as well as by index.
syntax
collections.namedtuple(type_name, field-list)
Ex In the following code, an index is not required to print the name of a student rather passing
an attribute is sufficient for the required output.

from collections import namedtuple
Student = namedtuple('Student', 'fname, lname, age')  
s1 = Student('Peter', 'James', '13')
print(s1.fname)   
print(s1)

output
Peter
Student(fname='Peter', lname='James', age='13')
5. ChainMap
ChainMap combines a lot of dictionaries together and returns a list of dictionaries.
ChainMaps basically encapsulates a lot of dictionaries into one single unit with no
restriction on the number of dictionaries.
Ex
import collections
dictionary1 = { 'a' : 1, 'b' : 2 }  
dictionary2 = { 'c' : 3, 'b' : 4 }  
chain_Map = collections.ChainMap(dictionary1, dictionary2)  
print(chain_Map.maps)
Output
[{'a': 1, 'b': 2}, {'c': 3, 'b': 4}]
6. OrderedDict
OrderedDict is a dictionary that ensures its order is maintained.
For example, if the keys are inserted in a specific order, then the order is maintained. Even
if you change the value of the key later, the position will remain the same.
Ex
In dicitonary, (order is not maintained)
statesAndCapitals = { 'Gujarat' : 'Gandhinagar', 'Maharashtra' : 'Mumbai', 'Rajasthan' :
'Jaipur', Bihar' : 'Patna’}                       
print('List Of given states:\n')    Output:
# Iterating over keys List Of given states:
for state in statesAndCapitals: Rajasthan
    print(state) Bihar
Maharashtra
Gujarat
In order to maintain the order of keys and values in a dictionary, use OrderedDict().
Program:
from collections import OrderedDict   
statesAndCapitals = OrderedDict([ Output:
                                 ('Gujarat', 'Gandhinagar'), List Of given states:
                                 ('Maharashtra', 'Mumbai'), Gujarat
                                 ('Rajasthan', 'Jaipur'), Maharashtra
                                 ('Bihar', 'Patna') Rajasthan
                                ])                        Bihar
print('List Of given states:\n')   
# Iterating over keys
for state in statesAndCapitals:
    print(state)
8. Math module:
# importing built-in module math >>> math.ceil(10.9)
import math   
11
# using square root(sqrt) function contained 
# in math module >>> math.floor(10.9)
print math.sqrt(25) 
10
  
# using pi function contained in math module >>> math.fabs(10)
print math.pi 
10.0
  
# 2 radians = 114.59 degreees >>> math.fabs(-10)
print math.degrees(2) 
10.0
  
# 60 degrees = 1.04 radians >>> math.fmod(10,2)
print math.radians(60) 
0.0
  
# Sine of 2 radians >>> math.fsum([1,2,4])
print math.sin(2) 
7.0
  
# Cosine of 0.5 radians >>> math.pow(2,3)
print math.cos(0.5) 
8.0
  
>>> math.factorial(4) 
# Tangent of 0.23 radians
24
print math.tan(0.23)
9. OS Module:
OS module provides functions for interacting with the operating system.
 OS, comes under Python’s standard utility modules. This module provides a portable
way of using operating system dependent functionality.

1.os.name: 
This function gives the name of the operating system dependent module(real module )
imported.
>>> import os
>>> os.name
'nt'
2. os.getcwd()
A directory or folder is a collection of files and sub directories.
We can get the present working directory using the getcwd() method.
This method returns the current working directory in the form of a string. We can also
use the getcwdb() method to get it as bytes object.
Ex:
>>> import os
>>> os.getcwd()
'C:\\Users\\ajee\\AppData\\Local\\Programs\\Python\\Python37-32‘
>>> os.getcwdb()
b'C:\\Users\\ajee\\AppData\\Local\\Programs\\Python\\Python37-
32‘
The extra backslash implies escape sequence. 
>>> print(os.getcwd())
C:\Users\ajee\AppData\Local\Programs\Python\Python37-32
3. os.chdir()
We can change the current working directory using the chdir() method.

Ex:

>>> os.chdir('C:\\Python3')

>>> os.getcwd()

'C:\\Python3'

>>> print(os.getcwd())

C:\Python3
4. os.listdir()
All files and sub directories inside a directory can be known using the listdir() method.

This method takes in a path and returns a list of sub directories and files in that path.

If no path is specified, it returns from the current working directory.

>>> import os

>>> print(os.getcwd())

C:\Users\ajee\AppData\Local\Programs\Python\Python37-32

>>> os.listdir()

['a.txt', 'ab.txt', 'data.txt', 'demo', 'demo.txt', 'demo1', 'DLLs', 'Doc', 'dw.txt', 'include', 'Lib', 'libs',

'LICENSE.txt', 'new1.txt', 'NEWS.txt', 'python.exe', 'python3.dll', 'python37.dll', 'pythonw.exe‘]


5. os.mkdir( )
We can make a new directory using the mkdir() method. This method takes in the path

of the new directory.

If the full path is not specified, the new directory is created in the current working

directory.

>>> os.mkdir('test')

>>> os.listdir()

['a.txt', 'ab.txt', 'data.txt', 'demo', 'demo.txt', 'demo1', 'DLLs', 'Doc', 'dw.txt', 'include', 'Lib',

'libs', 'LICENSE.txt', 'new1.txt', 'NEWS.txt', 'python.exe', 'python3.dll', 'python37.dll',

'pythonw.exe', 'tcl', 'test‘]


6. os.rename( )
The rename() method can rename a directory or a file.

The first argument is the old name and the new name must be supplies as the second

argument.

>>> os.rename('test','new_test')

>>> os.listdir()

['a.txt', 'ab.txt', 'data.txt', 'demo', 'demo.txt', 'demo1', 'DLLs', 'Doc', 'dw.txt', 'include', 'Lib',

'libs', 'LICENSE.txt', 'new1.txt', 'NEWS.txt', 'new_test‘]


7. Removing Directory or File

A file can be removed (deleted) using the remove() method.

Similarly, the rmdir() method removes an empty directory.

>>> os.listdir()

['a.txt', 'ab.txt', 'data.txt', 'demo', 'demo.txt', 'demo1', 'DLLs‘, 'empty file‘, ‘non-

empty file’]

>>> os.remove('demo.txt')

['a.txt', 'ab.txt', 'data.txt', 'demo', 'demo1', 'DLLs‘, 'empty file‘, ‘non-empty file’]

>>>os.rmdir('empty file')

['a.txt', 'ab.txt', 'data.txt', 'demo', 'demo1', 'DLLs‘, ‘non-empty file’]

However, note that rmdir() method can only remove empty directories.


In order to remove a non-empty directory we can use the rmtree() method and import
 shutil module.

>>>os.rmdir('non-empty file')
Traceback (most recent call last):
File "<pyshell#21>", line 1, in <module>
os.rmdir('non-empty file')
OSError: [WinError 145] The directory is not empty: 'non-empty file‘

>>> import shutil


>>> shutil.rmtree('non-empty file')
>>> os.listdir()
['a.txt', 'ab.txt', 'data.txt', 'demo', 'demo1', 'DLLs‘]
10.Sys module:
python sys module provides allows us to operate on underlying interpreter(i.e., system
and environment-specific variables ), irrespective of it being a Windows Platform, Macintosh
or Linux.
Python sys module also used to read the PATH variable and the list of command-line
parameters passed to the Python script.
Functions in sys module
1.  sys.modules.keys()
This function gives the names of the existing python modules current shell has
imported
Ex
import sys
sys.modules.keys()
Output
dict_keys(['sys', 'builtins', '_frozen_importlib', '_imp', '_thread',
'_warnings‘………'zmq.utils.garbage'])
2. sys.path
This function displays the PATH of the current system or environment.
>>> import sys
>>> sys.path
['','C:\\Users\\ajee\\AppData\\Local\\Programs\\Python\\Python37-32\\Lib\\idlelib', 'C:\\
Users\\ajee\\AppData\\Local\\Programs\\Python\\Python37-32\\python37.zip', 'C:\\Users\\
ajee\\AppData\\Local\\Programs\\Python\\Python37-32\\DLLs', 'C:\\Users\\ajee\\AppData\\
Local\\Programs\\Python\\Python37-32\\lib', 'C:\\Users\\ajee\\AppData\\Local\\Programs\\
Python\\Python37-32', 'C:\\Users\\ajee\\AppData\\Local\\Programs\\Python\\Python37-32\\
lib\\site-packages', 'C:\\Users\\ajee\\AppData\\Local\\Programs\\Python\\Python37-32\\
lib\\site-packages\\win32’,
'C:\\Users\\ajee\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-
packages\\win32\\lib',
‘C:\\Users\\ajee\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages\\
Pythonwin‘]
3. sys.stdin
This function of sys module is used to accept input for a user-input-prompt program.
This function is standard file in python
Syntax:
sys.stdin.readline()
Ex
import sys
print('Enter your name: ')
c = sys.stdin.readline()
print('Your name is:', c)
Output:
Enter your name:    rajeev                 
Your name is: rajeev 
4. sys.stdout
This function of sys module is used to print message.
This function is standard file in python
Syntax:
sys.stdout.write()

Ex
import sys
sys.stdout.write(‘hi I am standard files')
Output:
hi I am standard files
4. sys.stderr
This function of sys module is used to error message.
This function is standard file in python
Syntax:
sys.stderr.write()
Ex
import sys
sys.stderr.write(‘name a is not defined’)
Output:
name a is not defined
5. sys.version
To know the version of python
Ex
import sys
sys.version
output
3.7.10 (default, May 3 2021, 02:48:31) [GCC 7.5.0]
6. sys.exit
This method makes the Python interpretor exits the current flow of execution abruptly
Ex
import sys
print("python programming")
sys.exit(1)
print("datascience")
Output
python programming
7. sys.copyright
This function displays the copyright information on currently installed Python version.
Ex
import sys
sys.copyright
Output
Copyright (c) 2001-2021 Python Software Foundation.
All Rights Reserved.
Copyright (c) 2000 BeOpen.com.
All Rights Reserved.
Copyright (c) 1995-2001 Corporation for National Research Initiatives.
All Rights Reserved.
Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.
All Rights Reserved.
8. sys.maxsize
This function returns the largest integer of a variable.
Ex
import sys
sys.maxsize
Output
9223372036854775807
8. sys.argv or Command line arguments :
Command line arguments in python:

Till now in python , we have taken input using raw_input() or input().

There is another method that uses command line arguments.

Almost all programming language provide support for command line arguments. Then we
also have command line options to set some specific options for the program in python.

The command line arguments are those arguments must be given whenever we want to
give the input before the start of the script.

These arguments are given on the command line along with the program name in a text-
based environment like a unix- or dos-shell.
However, in an IDE or GUI environment, this would not be the case. Most IDES provide

a separate window with which to enter your "command-line arguments." These will be

passed into the program as if you started your application from the command line.

There are many options to read python command line arguments. One of most common

method to read python command line arguments is:

1. Python sys.argv
Python sys.argv module
sys module provides access to any command-line arguments via sys.argv
Python sys module stores the command line arguments into a list, we can access it
using sys.argv.

This is very useful and simple way to read command line arguments as String.
The names "argc" and "argv" stand for "argument count" and "argument vector,“
The argv variable contains an array of strings consisting of each argument from the
command line while the argc variable contains the number of arguments entered.i.e., the
number of items in the sys.argv list.

In list, each element represents a single argument.


The first one -- sys.argv[0] -- is the name of the Python script or program name.
The other list elements --  are the command line arguments 2 to n. 
sys.argv is the list of command-line arguments
len(sys.argv) is the number of command-line arguments
Ex:
# file save as cmd.py
import sys
print("you entered", len(sys.argv), "arguments...")
print(len(sys.argv),'arguments input from command line are:')
for x in sys.argv:
print(x)
Open cmd prompt and execute below cmd where your python software is installed.
>>C:\Users\ajee\AppData\Local\Programs\Python\Python37-32>python cmd.py 2 3 4 5
you entered 5 arguments...
5 arguments input from command line are:
cmd.py
2
3
4

Python program to find sum of two numbers using
command line arguments
Python program to find sum of two numbers using command line arguments
Program:
import sys
print("you entered", len(sys.argv), "arguments...")
print("they were:", str(sys.argv))
a = int(sys.argv[1])
b = int(sys.argv[2])
sum = a+b
print("sum of",sys.argv[1],"and",sys.argv[2],"is",sum)
Output :
C:\Users\ajee\AppData\Local\Programs\Python\Python37-32>python cmd.py 20 30
you entered 3 arguments...
they were: ['cmd.py', '20', '30']
sum of 20 and 30 is 50
11. Random module
Python defines a set of functions that are used to generate or manipulate random numbers.
This particular type of functions are used in a lot of games, lotteries or any application
requiring random number generation
Randon Number Operations :
1. choice() :- This function is used to generate 1 random number from a container.
2. randrange(beg, end, step) :- This function is also used to generate random number but within
a range specified in its arguments. This function takes 3 arguments, beginning number (included
in generation), last number (excluded in generation) and step ( to skip numbers in range while
selecting).
Ex:
>>> import random
>>> print(random.choice([1,2,4,5]))
5
>>> print(random.randrange(20,50,3))
23
3. random() :- This number is used to generate a float random number less than 1 and greater
or equal to 0.
>>> print (random.random())
0.17656383747256632

4 uniform(a, b) :- This function is used to generate a floating point random number between the
numbers mentioned in its arguments. It takes two arguments, lower limit(included in generation)
and upper limit(not included in generation).
>>> import random
>>> random.uniform(5,10)
6.828444584562927

5. randint(): generate random integer numbers


Ex:
import random
   # printing random integer between 0 and 5
6. seed() :-
random.seed() gives a value to random value generator
(random.random(),‘random.randint()') which generates these values on the basis of this seed.

One of the must properties of random numbers is that they should be reproducible. When you
put same seed, you get the same pattern of random numbers. 
Ex >>> import random
>>> import random >>> random.seed(4)
>>> random.seed(3) >>> random.randint(1,100)
>>> random.random() 31
0.23796462709189137 >>> random.seed(4)
>>> random.seed(3) >>> random.randint(1,100)
>>> random.random() 31
0.23796462709189137
12. Platform module
# to know your operting system
>>> import platform
>>> platform.system()
'Windows'
13. Statistics Module:
The statistics module provides functions to mathematical statistics of numeric data. The
following popular statistical functions are defined in this module.
1. mean() :
The mean() method calculates the arithmetic mean of the numbers in a list
Ex :
import statistics    
# list of positive integer numbers   
datasets = [5, 2, 7, 4, 2, 6, 8]     
x = statistics.mean(datasets)     
# Printing the mean   
print("Mean is :", x)  
Output :
Mean is : 4.857142857142857
2. median()
The median() function is used to return the middle value of the numeric data in the list.
Before median, this function will perform sort and then find its middle value
Ex
import statistics     
datasets = [3,1,2,5,4]      
# Printing median of the   
# random data-set   
print("Median of data-set is :",statistics.median(datasets))  
Output
Median of data-set is : 3
3. mode() function
The mode() function returns the most common data that occurs in the list.

Example
import statistics
# declaring a simple data-set consisting of real valued positive integers.
dataset =[2, 4, 7, 7, 2, 2, 3, 6, 6, 8]
# Printing out the mode of given data-set
print("Calculated Mode % s" % (statistics.mode(dataset)))
Output:
Calculated Mode 2
4. stdev() function
The stdev() function is used to calculate the standard deviation on a given sample which
is available in the form of the list.
Example
import statistics
# creating a simple data - set
sample = [7, 8, 9, 10, 11]
# Prints standard deviation
print("Standard Deviation of sample is % s " % (statistics.stdev(sample)))
Output:
Standard Deviation of sample is 1.5811388300841898
4. variance() function
This function is used to calculate the variance on a given sample which is available in the
form of the list.
Example
import statistics     
datasets = [4, -5, 6, 6, 9, 4, 5, -2]      
# Printing median of the   
# random data-set   
print("standard variance of data-set is :",statistics.variance(datasets)) 
Output
standard variance of data-set is : 21.125
14. datetime module
Python has a module named datetime to work with dates and times.
1. How to Get Current Date and Time:
import datetime
datetime_object = datetime.datetime.now()
print(datetime_object)
Output:
2020-06-15 12:25:54.193616
Here, we have imported datetime module using import datetime statement.
One of the classes defined in the datetime module is datetime class.
We then used now() method to create a datetime object containing the current local date and
time.
2. Get Current Date:
import datetime
date_object = datetime.date.today()
print(date_object)
Output:
2020-06-15
In this program, we have used today() method defined in the date class to get a date object
containing the current local date.

3. What's inside datetime?


We can use dir() function to get a list containing all attributes of a module datetime.
import datetime
print(dir(datetime))
Output:
['MAXYEAR', 'MINYEAR', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__',
'__name__', '__package__', '__spec__', 'date', 'datetime', 'datetime_CAPI', 'sys', 'time',
'timedelta', 'timezone', 'tzinfo']
Commonly used classes in the datetime module are:
1. date Class
2. time Class
3. datetime Class
4. timedelta Class
1. datetime.date Class
 We can instantiate date objects from the date class.
 A date object represents a date (year, month and day).  
Date object to represent a date
import datetime
d = datetime.date(2019, 4, 13)
print(d)

date() in the above example is a constructor of the date class.


 The constructor takes three arguments: year, month and day.
We can only import date class from the datetime module. Here's how:
from datetime import date
a = date(2019, 4, 13)
print(a)

The variable a is a date object.

Get current date:


We can create a date object containing the current date by using a class method
named today()
from datetime import date
today = date.today()
print("Current date =", today)
Print today's year, month and day
We can get year, month, day, day of the week etc. from the date object easily.
from datetime import date
# date object of today's date
today = date.today()
print("Current year:", today.year)
print("Current month:", today.month)
print("Current day:", today.day)

Output:
Current year: 2020
Current month: 6
Current day: 16
2. datetime.time class
A time object instantiated from the time class represents the local time.
Time object to represent time:
from datetime import time
# time(hour = 0, minute = 0, second = 0)
a = time()
print("a =", a)
# time(hour, minute and second)
b = time(11, 34, 56)
print("b =", b) Output:

# time(hour, minute and second) a = 00:00:00

c = time(hour = 11, minute = 34, second = 56) b = 11:34:56

print("c =", c) c = 11:34:56

# time(hour, minute, second, microsecond) d = 11:34:56.234566

d = time(11, 34, 56, 234566)


print("d =", d)
Print hour, minute, second and microsecond:
Once you create a time object, you can easily print its attributes such as hour, minute etc.
from datetime import time
a = time(11, 34, 56)
print("hour =", a.hour)
print("minute =", a.minute)
print("second =", a.second)
print("microsecond =", a.microsecond)
Output:
hour = 11
minute = 34
second = 56
microsecond = 0
Notice that we haven't passed microsecond argument. Hence, its default value 0 is printed.
3. datetime.datetime:
The datetime module has a class named datetimeclass that can contain information from both
date and time objects.
Python datetime object:
from datetime import datetime
Output:
#datetime(year, month, day)
2018-11-28 00:00:00
a = datetime(2018, 11, 28)
2017-11-28 23:55:59.342380
print(a)
# datetime(year, month, day, hour, minute, second, microsecond)
b = datetime(2017, 11, 28, 23, 55, 59, 342380)
print(b)

The first three arguments year, month and day in the datetime() constructor are
mandatory.
4. Datetime.timedelta:
A timedelta object represents the difference between two dates or times.
from datetime import datetime, date
t1 = date(year = 2018, month = 7, day = 12)
t2 = date(year = 2017, month = 12, day = 23)
t3 = t1 - t2
print("t3 =", t3)
print("type of t3 =", type(t3))
Output:
t3 = 201 days, 0:00:00
type of t3 = <class 'datetime.timedelta'>

t3 of <class 'datetime.timedelta'> type.


Difference between two timedelta objects:
from datetime import timedelta
t1 = timedelta(weeks = 2, days = 5, hours = 1, seconds = 33)
t2 = timedelta(days = 4, hours = 11, minutes = 4, seconds = 54)
t3 = t1 - t2
print("t3 =", t3)
Output:
t3 = 14 days, 13:55:39
Python format datetime
The way date and time is represented may be different in different places, organizations
etc.
 It's more common to use mm/dd/yyyy in the US, whereas dd/mm/yyyy is more common
in the UK.
Python has ---
1.strftime() and
2. strptime() methods----- to handle this.

1. Python strftime() - datetime object to string


The strftime() method is defined under classes date, datetime and time.
The method creates a formatted string from a given date, datetime or time object.
Format date using strftime()
from datetime import datetime
# current date and time
now = datetime.now()
t = now.strftime("%H:%M:%S")
print("time:", t)
s1 = now.strftime("%m/%d/%Y, %H:%M:%S")
# mm/dd/YY H:M:S format
print("s1:", s1)
s2 = now.strftime("%d/%m/%Y, %H:%M:%S")
# dd/mm/YY H:M:S format
print("s2:", s2)

Output: Here, %Y, %m, %d, %H etc. are format codes.


time: 20:02:51 here, t, s1 and s2 are strings.
s1: 06/15/2020, 20:02:51
s2: 15/06/2020, 20:02:51
The strftime() method takes one or more format codes and returns a formatted string based on
it.
%Y - year [0001,..., 2018, 2019,..., 9999]
%m - month [01, 02, ..., 11, 12]
%d - day [01, 02, ..., 30, 31]
%H - hour [00, 01, ..., 22, 23]
%M - minute [00, 01, ..., 58, 59]
%S - second [00, 01, ..., 58, 59]
2. Python strptime() - string to datetime
The strptime() method creates a datetime object from a given string (representing date and time).

Output:
from datetime import datetime
date_string = 21 June, 2018
date_string = "21 June, 2018"
date_object = 2018-06-21 00:00:00
print("date_string =", date_string)
date_object = datetime.strptime(date_string, "%d %B, %Y")
print("date_object =", date_object)

The strptime() method takes two arguments:


1. a string representing date and time
2. format code equivalent to the first argument

Here , %d, %B and %Y format codes are used for day, month(full name) and year
respectively.
15. Regular Expressions:
Introduction
The regular expressions can be defined as the sequence of characters which are
used to search for a pattern in a string.

It is extremely useful for extracting information from text such as code, files, log,
spreadsheets or even documents.

While using the regular expression the first thing is to recognize is that everything
is a character, and we are writing patterns to match a specific sequence of
characters also referred as string.

It is also called RegEx or re.


For example,

^a...s$
The above pattern defines a RegEx pattern.
 The pattern is: any five letter string starting with a and ending with s.
Regex Functions
The following regex functions are used in the python.
1. re.match():
 This method matches the regex pattern in the string .It returns true if a match is
found in the string otherwise it returns false.

import re
pattern = '^a...s$'
test_string = 'abyss'
result = re.match(pattern, test_string)
if result:
print("Search successful.")
else:
print("Search unsuccessful.")

Here, we used re.match() function to search pattern within the test_string. The


method returns a match object if the search is successful. If not, it
2. re.search()
The re.search() method takes two arguments: a pattern and a string. The method
looks for the first location where the RegEx pattern produces a match with the string.
If the search is successful, re.search() returns a match object; if not, it returns None.
Syntax:
match = re.search(pattern, str)
Ex:
import re
string = "Python is fun“
match = re.search(‘fun', string)
if match:
print("pattern found inside the string")
else:
print("pattern not found")
3. The findall() function
This method returns a list containing a list of all matches of a pattern within the
string.
 It returns the patterns in the order they are found. If there are no matches, then an
empty list is returned.
Example
>>> import re
>>> str="How are you. How is everything"
>>> matches=re.findall("How",str)
>>> print(matches)
['How', 'How']
4. re.split(pattern, string, [maxsplit=0]):
This methods helps to split string by the occurrences of given pattern.
Ex:
import re
result=re.split('y','Analytics')
Result
Output:
['Anal', 'tics']

ex:
>>> result=re.split('i','Analytics information',maxsplit=3)
>>> result
['Analyt', 'cs ', 'nformat', 'on']
5. re.sub(pattern, repl, string):
It helps to search a pattern and replace with a new sub string. If the pattern is
not found, string is returned unchanged.
Ex;
import re
result=re.sub('India','the World','AV is largest Analytics community of India')
result
Output: 'AV is largest Analytics community of the World'
2. Special Symbols and Characters:
Forming a regular expression
A regular expression can be formed by using the mix of meta-characters, special
sequences, and sets.
1. Meta-Characters
Metacharacter is a character with the specified meaning.
EX:
import re
match=re.match('[abc]','a')
if match:
print("matched")
else:
print("not matched") import re
match=re.match('[^a-e]','a')
if match:
import re print("matched")
match=re.match('[a-e]','a') else:
if match: print("not matched")
print("matched")
else:
print("not matched")
Ex:
import re
match=re.match('..',‘a')
if match:
print("matched")
else:
print("not matched“)
Output: not matched

import re
match=re.match('..','ac')
if match:
print("matched")
else:
print("not matched")
Output: matched
Ex:
import re
match=re.match('^a','ba')
if match:
print("matched")
else:
print("not matched")

Output: not matched


import re
match=re.match('^a',’ab')
if match:
print("matched")
else:
print("not matched“)
Output: matched
import re
match=re.match('......a$','formula')
if match:
print("matched")
else:
print("not matched")
Ex:
import re
match=re.match('ma*n','man')
if match:
print("matched")
else:
print("not matched")
Output: matched
Ex:
import re
match=re.match('ma*n','main')
if match:
print("matched")
else:
print("not matched")
Output: not matched
Ex:
import re
match=re.match('ma+n','mn')
if match:
print("matched")
else:
print("not matched")
Output: not matched
Ex:
import re
match=re.match('ma+n','man')
if match:
print("matched")
else:
print("not matched“)
Output: matched
Ex:
import re
match=re.match('ma?n','mn')
if match:
print("matched")
else:
print("not matched")
Output: matched
Ex:
import re
match=re.match('ma?n','maaan')
if match:
print("matched")
else:
print("not matched")
Output: not matched
Ex:
import re
match=re.match('a{2,3}','abc dat')
if match:
print("matched")
else:
print("not matched“)
Output: not matched
import re
match=re.match('a{2,3}','aabc daaat')
if match:
print("matched")
else:
print("not matched“)
Output: matched
Ex:
import re
match=re.match('a|b','ade')
if match:
print("matched")
else:
print("not matched“)
Output: matched
Ex:
import re
match=re.match('a|b',‘cde')
if match:
print("matched")
else:
print("not matched")
Output: not matched
Ex:
import re
match=re.match('(a|b)xz','axz cabxz')
if match:
print("matched")
else:
print("not matched")
Output: matched
import re
match=re.match('(a|b)xz','ab xz')
if match:
print("matched")
else:
print("not matched")
Output: not matched
15. Object-Oriented Programming
Object-Oriented Programming(OOP), is all about creating “objects”. An object is a group of
interrelated variables and functions. These variables are often referred to as properties of the
object and functions are referred to as the behavior of the objects. These objects provide a
better and clear structure for the program.

For example, If we consider a dog as an object then its properties would be- his color, his
breed, his name, his weight, etc. And his behavior/function would be walking, barking, playing,
etc.
Another example- a car can be an object. If we consider the car as an object then its
properties would be – its color, its model, its price, its brand, etc. And its behavior/function
would be acceleration, slowing down, gear change.

Object-Oriented programming is famous because it implements the real-world entities like


objects, hiding, inheritance, etc in programming. It makes visualization easier because it is
close to real-world scenarios.
16. Object-Oriented Programming (OOP) vs Procedure Oriented Programming
(POP)
The basic difference between OOP and procedural programming is-
One way to think about POP is the same way you make lemonade for example. The
procedure of making lemonade involves- first taking water according to the need, then
adding sugar to the water, then adding lemon juice to the mixture, and finally mixing the
whole solution. And your lemonade is ready to serve.

In a similar way, POP requires a certain procedure of steps. A procedural program
consists of functions. This means that in the POP approach the program is divided into
functions, which are specific to different tasks. These functions are arranged in a specific
sequence and the control of the program flows sequentially.

Whereas an OOP program consists of objects. The object-Oriented approach divides


the program into objects. And these objects are the entities that bundle up the properties
and the behavior of the real-world objects.
POP is suitable for small tasks only. Because as the length of the program increases, the
complexity of the code also increases. And it ends up becoming a web of functions. Also, it
becomes hard to debug. OOP solves this problem with the help of a clearer and less complex
structure. It allows code re-usability in the form of inheritance.

Another important thing is that in procedure-oriented programming all the functions have
access to all the data, which implies a lack of security. Suppose you want to secure the
credentials or any other critical information from the world. Then the procedural approach fails
to provide you that security. For this OOP helps you with one of its amazing functionality
known as Encapsulation, which allows us to hide data.

Programming languages like C, Pascal and BASIC use the procedural approach whereas 
Java, Python, JavaScript, PHP, Scala, and C++ are the main languages that provide the Object-
oriented approach.
17.Python OOPs concept
1. Class
2. Object
3. Method
4. Inheritance
5. Data Abstraction
6. Encapsulation
7. Polymorphism
1. Class :
 class is a collection of objects.  Unlike the primitive data structures, classes are data
structures that the user defines. They make the code more manageable.
How to create Class 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.
Syntax
class class_name:
class body
 We define a class with a keyword “class” following the class_name and semicolon. And we
consider everything you write under this after using indentation as its body.
Ex:
class MyNewClass:
'''This is a docstring. I have created a new class'''
pass
A class creates a new local namespace where all its attributes are defined.
Attributes may be data or functions..
class MyClass:
"This is my second class"
a = 10
def func(self):
print('Hello‘)
print(MyClass.a)
print(MyClass.func)
print(MyClass.__doc__)
There are also special attributes in it that begins with double underscores (__). For example,
__doc__ gives us the docstring of that class.
2. Objects:
Python is an object oriented programming language.

Almost everything in Python is an object, with its properties and methods.

Object is simply a collection of data (variables) and methods (functions) that act on those

data. and, class is a blueprint for the object.


Ex:

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.

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.


Creating an Objects or object instantiation in Python:

When we define a class only the description or a blueprint of the object is created.

There is no memory allocation until we create its object. The objector instance contains

real data or information.

Instantiation is nothing but creating a new object/instance of a class.

Syntax

object = class_name() # creation of an object is similar to a function call.

Ex

ob = MyClass()

This will create a new instance object named ob. We can access attributes of objects using
the object name prefix.
Ex:
class MyClass:
"This is my second class"
a = 10
ob = MyClass() # creating object of a class
print(ob.a)
# Output: 10

We can access attributes of objects using the object name prefix.

Attributes may be data or method. Method of an object are corresponding functions of that
class. Any function object that is a class attribute defines a method for objects of that class.

This means to say, since MyClass.func is a function object (attribute of class), ob.func will be
a method object.
3. Methods
Objects can also contain methods. Methods in objects are functions that belong to the object
Let us create a method in the Person class:

Ex: Insert a function that prints a greeting, and execute it on the p1 object:
class Person:
def __init__(self, name, age): Output: Hello my name is John

self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
p1.myfunc()

Note: The self parameter is a reference to the current instance of the class, and is used to access
variables that belong to the class.
The self Parameter
The self parameter is a reference to the current instance of the class, and is used to
access variables that belongs to the class.

It does not have to be named self , you can call it whatever you like, but it has to be the
first parameter of any function in the class:

Ex: Use the words mysillyobject and abc instead of self:


class Person:
def __init__(mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age
def myfunc(abc):
print("Hello my name is " + abc.name)
p1 = Person("John", 36)
p1.myfunc()
pass Statement in class
class definitions cannot be empty, but if you for some reason have a class definition
with no content, put in the pass statement to avoid getting an error.
Ex:
class Person:
pass
4. Inheritance
Inheritance allows us to define a class that inherits all the methods and properties from
another class.
Parent class is the class being inherited from, also called base class.
Child class is the class that inherits from another class, also called derived class.

Create a Parent Class


Any class can be a parent class, so the syntax is the same as creating any other class:
Ex:
Create a class named Person, with firstname and lastname properties, and a printname method:
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname) #Use the Person class to create an object, and
x = Person("John", "Doe") then execute the printname method:
x.printname()
Create a Child Class
To create a class that inherits the functionality from another class, send the parent class
as a parameter when creating the child class:
Example:
Create a class named Student, which will inherit the properties and methods from the Person
class:
class Student(Person):
pass
Note: Use the pass keyword when you do not want to add any other properties or methods
to the class.
Now the Student class has the same properties and methods as the Person class.
Example:
Use the Student class to create an object, and then execute the printname method:
x = Student("Mike", "Olsen")
x.printname()
Example:
class Person: # parent class
def __init__(self, fname, lname):
self.firstname = fname
attributes
self.lastname = lname
def printname(self):
methods
print(self.firstname, self.lastname)
x = Person("John", "Doe")
x.printname()
class Student(Person): # child class
pass
x = Student("Mike", "Olsen")
x.printname()

Output:
John Doe
Mike Olsen
Add the __init__() Function
So far we have created a child class that inherits the properties and methods from its
parent.
We want to add the __init__() function to the child class (instead of the pass keyword).
Note: The __init__() function is called automatically every time the class is being used to
create a new object.

Example: Add the __init__() function to the Student class:


class Student(Person):
def __init__(self, fname, lname):
#add properties etc.

When you add the __init__() function, the child class will no longer inherit the parent's
__init__() function.

Note: The child's __init__() function overrides the inheritance of the parent's __init__()
To keep the inheritance of the parent's __init__() function, add a call to the parent's __init__()
function:
Example
class Student(Person):
def __init__(self, fname, lname):
Person.__init__(self, fname, lname)

Now we have successfully added the __init__() function, and kept the inheritance of the
parent class, and we are ready to add functionality in the __init__() function.
Example:
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
x = Person("John", "Doe") Output:
John Doe
x.printname()
Mike
Olsen
class Student(Person):
def __init__(self, fname, lname):
Person.__init__(self, fname, lname)
x = Student("Mike", "Olsen")
x.printname()
Use the super() Function
Python also has a super() function that will make the child class inherit all the methods
and properties from its parent:
Example
class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
By using the super() function, we do not have to use the name of the parent element, it will
automatically inherit the methods and properties from its parent.
Example:
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)

class Student(Person):
Output:
def __init__(self, fname, lname, year):
Welcome Mike Olsen to the class of 2019
super().__init__(fname, lname)
self.graduationyear = year

def welcome(self):
print("Welcome", self.firstname, self.lastname, "to the class of", self.graduationyear)
x = Student("Mike", "Olsen", 2019)
x.welcome()
Two built-in functions isinstance() and issubclass() are used to check inheritances.

Function isinstance() returns True if the object is an instance of the class or other classes
derived from it. Each and every class in Python inherits from the base class object.

Similarly, issubclass() is used to check for class inheritance.

Example: a=issubclass(Student,Person)
b=isinstance(x,Person) print(a)
print(b) f=issubclass(Person,Student)
c=isinstance(x,Student) print(f)
print(c)
d=isinstance(x,object)
print(d) Output: Output:
True True
e=isinstance(x,int) True False
print(e) True
False
Multiple Inheritance in Python
In Python., like C++, a class can be derived from more than one base classes. This is
called multiple inheritance.
In multiple inheritance, the features of all the base classes are inherited into the derived
class.
The syntax for multiple inheritance is similar to single inheritance.
Example
class Base1:
pass
class Base2:
pass
class MultiDerived(Base1, Base2):
pass

Here, MultiDerived is derived from classes Base1 and Base2.


Multilevel Inheritance in Python
On the other hand, we can also inherit from a derived class. This is called multilevel
inheritance. It can be of any depth in Python.
In multilevel inheritance, features of the base class and the derived class is inherited into
the new derived class.
Ex:
class Base:
pass
class Derived1(Base):
pass
class Derived2(Derived1):
pass
Here, Derived1 is derived from Base, and Derived2 is derived from Derived1
Data hiding in python:
One of the fundamental concepts which provide data hiding in OOP are:
1. Data Abstraction
2. Data Encapsulation

1. Data abstraction:
  It refers to the act of representing essential features without including the background
details and explanations. i.e., Abstraction is the process of hiding the real
implementation of an application from the user and emphasizing only on how to use the
application.

 Consider the example of a switchboard, you can only press certain switches according
to your requirement. What is happening inside, how it is happening, you need not
know.

 This is an abstraction, you know only essential things to operate on switchboard


Abstract Classes
A class containing one or more abstract methods is called an abstract class.
Abstract methods do not contain any implementation. Instead, all the
implementations can be defined in the methods of sub-classes that inherit the abstract class.
An abstract class can have both a normal method and an abstract method.
An abstract class cannot be instantiated, ie., we cannot create objects for the abstract
class
Syntax
from abc import ABC
Class ClassName(ABC): #abstract class
pass

An abstract class is created by importing a class named 'ABC' from the 'abc' module and
inheriting the 'ABC' class.
abstract methods should not contain any implementation. So, we can define abstract methods
using the 'pass' statement' 
Example
from abc import ABC
class Shape(ABC): #abstract class
def calculate_area(self): #abstract method
pass
class Rectangle(Shape): # normal class
length = 5
breadth = 3
def calculate_area(self): #normal method
return self.length * self.breadth
class Circle(Shape):
radius = 4
def calculate_area(self):
return 3.14 * self.radius * self.radius
rec = Rectangle() #object created for the class 'Rectangle'
cir = Circle() #object created for the class 'Circle'
print("Area of a rectangle:", rec.calculate_area()) #call to 'calculate_area' method defined
inside the class 'Rectangle'
print("Area of a circle:", cir.calculate_area()) #call to 'calculate_area' method defined
inside the class 'Circle'.
Output:
Area of a rectangle: 15
Area of a circle: 50.24

Here, calculate_area is the abstract method of the abstract class 'Shape'.


The implementation of this abstract class can be defined in the sub-classes that inherit the class
'Shape'.
In the example, 'Rectangle' and 'Circle' are the two sub-classes that inherit the abstract class
'Shape'.
If the implementation of the abstract method is not defined in the derived classes, then the
Python interpreter throws an error.
2. Data encapsulation:
Encapsulation is the process of wrapping up variables and methods into a single entity.
In programming, a class is an example that wraps all the variables and methods defined
inside it.
In the real world, consider your college as an example. Each and every department's
student records are restricted only within the respective department.
CSE department faculty cannot access the ECE department student record and so on.
Here, the department acts as the class and student records act like variables and
methods.

Abstraction and Encapsulation are complementary concepts, where –

abstraction focuses upon the observable behaviour of an object and

encapsulation focuses upon the implementation that gives rise to this behaviour.
In Python, Encapsulation can be achieved by declaring the data members of a class either as

private or protected.

In Python, 'Private' , 'Protected' and ‘public’ are called Access Modifiers, as they modify the
access of variables or methods defined in a class.
The access modifiers supported are:
1. Private:
A private variable can only be accessed by a method that is of the same class and not
outside of the class. These variables start with __ (private members are preceded by two
underscores).
For Example:
__engineno, __modelname
A private method can be called by a method of the same class. These methods start
with __.
For Example:
def __setmodelname()
In the below example, 'length' and 'breadth' are the two private variables declared and can
be accessed within the class 'Rectangle‘.
class Rectangle:
  __length = 0  #private variable
  __breadth = 0 #private variable
  def __init__(self):  #constructor
    self. __length = 5
    self.__breadth = 3 #printing values of the private variable within the class
    print(self.__length)
    print(self.__breadth)
rec = Rectangle()  #object created for the class 'Rectangle'
#printing values of the private variable outside the class using the object created 
for the class 'Rectangle'
print(rec.__length)
print(rec.__breadth)
output
5
3
AttributeError: 'Rectangle' object has no attribute ‘__length'

Since we have accessed private variables in the main() method, i.e., outside the class
'Rectangle', we got an error.

Hence in the above program, Encapsulation is achieved using the private variables 'length' and
'breadth'.
2. protected :
In Python, Protected members can be accessed within the class in which they are
defined and also within the derived classes.
protected members are preceded by a single underscore. In the below example, ‘_length'
and ‘_breadth' are the two protected variables defined inside the class 'Shape'.

class Shape: #protected variables


_length = 10
_breadth = 20
class Circle(Shape):
def __init__(self): #printing protected variables in the derived class
print(self._length)
print(self._breadth)
cr = Circle()
#printing protected variables outsidethe class 'Shape' in which they are defined
print(cr.length)
print(cr.breadth)
output
10
20
AttributeError: 'Circle' object has no attribute 'length'

When we try to access protected variables in the derived class, we got output. But, in the
main() method, we got an error.

Hence in the above example, Encapsulation is achieved using the protected variables 'length'
and 'breadth'.
3. Public:
A public variable can be accessed from anywhere.
A public method can be called from anywhere.
There is no specific word or character to represent the public access modifier. Anything
that does not have a __ is a public variable or method.
Ex:
class MyClass:
num = 10
def add(self, a):
sum = self.num + a
print(sum)
Output:
ob = MyClass()
10
ob.add(20)
20
print(ob.num)
7. Polymorphism
polymorphism refers to the ability of a real-time object to represent itself in many
forms.

For example. When you are at college, you act as a student. When are at your home, you
act like a child. You are a single person, but you represent yourself differently in different
places.

Similarly in the OOPs concept, polymorphism refers to the ability of a method to


process objects differently depending on their data type or class. 

Polymorphism is used in Python programs when you have commonly named methods in
two or more classes or subclasses.

It allows these methods to use objects of different types at different times. So, it provides
flexibility, using which a code can be extended and easily maintained over time.
Polymorphism in Built-In Method
In the below-given example, the built-in method 'len' processes two different objects, one
being a list & another a string.
#printing length of two different objects
print(len([2, 4, 6, 8, 9]))
print(len("FACE Prep"))
Output:
5
9
Here, the method 'len' prints the length of two different objects. In the first print statement,
it prints the length of a list object and in the second, it prints the length of a string object.
So, polymorphism is achieved using the built-in method 'len'.
Polymorphism in User-Defined Method
In the below diagram, 'calculate_area' is the user-defined method created with different
operations in both the classes 'Rectangle' and 'Circle'.
class Rectangle:
  length = 5
  breadth = 3
output
  def calculate_area(self):
Area of a rectangle: 15
    return self.length * self.breadth
Area of a circle: 50.24
class Circle:
  radius = 4
  def calculate_area(self):
    return 3.14 * self.radius * self.radius
rec = Rectangle()  #object created for the class 'Rectangle'
cir = Circle()  #object created for the class 'Circle'
print("Area of a rectangle:", rec.calculate_area()) 
#call to 'calculate_area' method defined 
inside the class 'Rectangle'
print("Area of a circle:", cir.calculate_area()) 
 Here, polymorphism is achieved using the method 'calculate_area' that works differently in
#call to 'calculate_area' method defined 
different classes.
Constructors in Python:
Constructors are special methods that are defined inside a class. They are invoked
when an object is created for the class.

Constructors are generally used for instantiating an object.

The task of constructors is to initialize(assign values) to the data members(variables and


methods)  of the class when an object of class is created.

They also verify whether there are enough variables and methods available for an object
to perform a task defined in the class.
Syntax of constructor declaration :

Similar to Functions, a constructor is defined with the keyword 'def' followed by a constructor

def __init__(self):

# body of the constructor

 A constructor always has the name 'init' and the name is prefixed, suffixed with a

double underscore(__).

The first parameter of the constructor must be 'self'. This parameter is used to store the

object passed from the main() method.

In Python the __init__() method is called the constructor and is always called when an

object is created.
Types of constructors :
In Python, we have two types of constructors.

1) Default constructor

2) Parameterized constructor

1.default constructor :

The default constructor does not have any parameters other than 'self'. It will not accept any

arguments other than the object created for the class in which it is defined.
class Employee:
  age = 0  #class variable
  def __init__(self): # default constructor used to initialize 'age' with the value 22
    self.age = 22
#main() method
John = Employee() 
#creating object (John) for the class 'Employee'. Once the object is created, the Python inte
rpreter calls the default constructor
print(John.age)  # printing the value stored in the variable 'age' using the object 'John‘
Output
22
If the user did not define a constructor inside a class, then the Python interpreter implicitly
defines a default constructor that does not do any operations.

We can pass arguments while creating an object and those arguments get stored in a
parameterized constructor.
class Employee:
output
  def __init__(self, age, salary):
John age: 22
    self.age1 = age
John salary: 20000
    self.salary1 = salary
Alex age: 30
#main() method
Alex salary: 27000
John = Employee(22, 20000)
Alex = Employee(30, 27000)
print("John age:", John.age1)
print("John salary:", John.salary1)
print("Alex age:", Alex.age1)
print("Alex salary:", Alex.salary1)

Here, the values 22 and 20000 are passed as the arguments during the object creation to the
parameterized constructor defined inside the class 'Employee'.
These values get stored in the parameters 'age' and 'salary'. Later, both the values get
assigned to the variables 'age1' and 'salary1'.
We can also create another object for the same class and pass the arguments.
2. parameterized constructor :
constructor with parameters is known as parameterized constructor. The parameterized
constructor take its first argument as a reference to the instance being constructed known
as self and the rest of the arguments are provided by the programmer.

This constructor accepts and stores arguments passed from the main() method during
object creation
Ex
class Employee:
  def __init__(self, age, salary):
    self.age1 = age
    self.salary1 = salary
#main() method
John = Employee(22, 20000)  #passing arguments to the parameterized constructor
Output
print(John.age1)
22
print(John.salary1)
20000
Example of parameterized constructor :
class Addition:
def __init__(self, f, s): # parameterized constructor
self.first = f Output :
self.second = s
def display(self): First number = 1000
print("First number = " + str(self.first)) Second number = 2000
print("Second number = " + str(self.second)) Addition of two numbers = 3000
print("Addition of two numbers = " + str(self.answer))
def calculate(self):
self.answer = self.first + self.second
obj = Addition(1000, 2000) # creating object of the class
obj.calculate() # perform Addition
obj.display() # display result
Python - Built-in Class Attributes
We can access the built-in class attributes using the . operator.
Following are the built-in class attributes.
1. __doc__ class attribute
In the following Python program we are creating Awesome class with documentation
Program
class Awesome: # class
    'This is a sample class called Awesome.'
    def __init__(self):
        print("Hello from __init__ method.") # class built-in attribute
print(Awesome.__doc__)
Output
This is a sample class called Awesome.
2. __name__ class attribute
In the following example we are printing the name of the class
Program
class Awesome:
    'This is a sample class called Awesome.'
    def __init__(self):
        print("Hello from __init__ method.")
# class built-in attribute
print(Awesome.__name__)
Output
Awesome
3. _module__ class attribute
In the following example we are printing the module of the class
Program
class Awesome:
    def __init__(self):
        print("Hello from __init__ method.")
# class built-in attribute
print(Awesome.__module__)
Output
__main__
4. __bases__ class attribute
In the following example we are printing the bases of the class.
program
class Awesome:
    def __init__(self):
        print("Hello from __init__ method.")
# class built-in attribute
print(Awesome.__bases__)
Output
(<class 'object'>,)
5. __dict__ class attribute
In the following example we are printing the dict of the class.
Program
class Awesome:
    def __init__(self):
        print("Hello from __init__ method.")
# class built-in attribute
print(Awesome.__dict__)
Output
{'__module__': '__main__', '__init__': <function Awesome.__init__ at 0x7f16e62c27a0>,
'__dict__': <attribute '__dict__' of 'Awesome' objects>, '__weakref__': <attribute '__weakref__'
of 'Awesome' objects>, '__doc__': None}
Method overriding:
Overriding is the property of a class to change the implementation of a method provided
by one of its base classes.

The method overriding means creating two methods with the same name but differ in
the programming logic.

The concept of Method overriding allows us to change or override the Parent Class
function in the Child Class.

In python, inheritance involves a relationship between parent and child classes.
Whenever both the classes contain methods with the same name and arguments or
parameters it is certain that one of the methods will override the other method during
execution. The method that will be executed depends on the object.
If the child class object calls the method, the child class method will override the parent class
method. Otherwise, if the parent class object calls the method, the parent class method will be
executed.
Example
class Animal():
    def sound(self, a): output
        print("This is parent class") Dogs bark
class Dogs(Animal):
    def sound(self):
        print("Dogs bark")
d1 = Dogs()
d1.sound()
In the above example, the class Dogs and its parent class Animal have methods with the same
name sound. When the object d1 of the class Dogs calls this method, then the method of the
child class Dogs gets called, not that of the parent class. Thus, the method of the child class
overrides the method of the parent class when called by an object of the child class. This is
GUI Programming:
Introduction:
What Is A Graphical User Interface (GUI)?
Graphical User Interface (GUI) is nothing but a desktop application which helps you to
interact with the computers. They are used to perform different tasks in the desktops,
laptops and other electronic devices.

GUI apps like Text-Editors are used to create, read, update and delete different types of
files.

GUI apps like Sudoku, Chess and Solitaire are games which you can play.

GUI apps like Google Chrome, Firefox and Microsoft Edge are used to browse through


the Internet.
Python Libraries To Create Graphical User Interfaces:
Python provides several different options/libraries for writing GUI based programs.
These are listed below:
1. Tkinter: It is the easiest among all libraries. It is Python's standard GUI (Graphical
User Interface) package. It is the most commonly used toolkit for GUI Programming in
Python.

2. JPython: It is the Python platform for Java that is providing Python scripts seamless
access o Java class Libraries for the local machine.

3. wxPython: It is open-source, cross-platform GUI toolkit written in C++. It one of the


alternatives to Tkinter, which is bundled with Python.

There are many other interfaces(Kivy ,Python QT) available for GUI. Among all of
these, Tkinter is preferred by a lot of learners and developers just because of how simple
and easy it is.
What Are Tcl, Tk, and Tkinter?

Tkinter is Python's default GUI library. It is based on the Tk toolkit, originally


designed for the Tool Command Language (Tcl).

Due to Tk's popularity, it has been ported to a variety of other scripting languages,
including Perl (Perl/Tk), Ruby (Ruby/Tk), and Python (Tkinter).

tkinter is an inbuilt Python module used to create simple GUI apps. It is the most


commonly used module for GUI apps in the Python.

You don’t need to worry about installation of the Tkinter module as it comes


with Python default.
>>> import Tkinter-------------python 2.x
>>> import tkinter-------------python 3.x
If your Python interpreter was not compiled with Tkinter enabled, the module import fails:
>>> import Tkinter

Traceback (innermost last):


File "<stdin>", line 1, in ?
File "/usr/lib/python1.5/lib-tk/Tkinter.py", line 8, in ?
import _tkinter # If this fails your Python may not
be configured for Tk
ImportError: No module named _tkinter
Tkinter and Python Programming:
Creating a GUI application using Tkinter is an easy task. All you need to do is perform the
following steps −
1.importing tkinter
It is same as importing any other module in the python code. Note that the name of the
module in Python 2.x is ‘Tkinter’ and in Python 3.x is ‘tkinter’.
import tkinter
2. Create the GUI application main window.
we are performing operations and displaying visuals and everything basically.
3. Add one or more of the widgets to the GUI application.
4. Enter the main event loop to take action against each event triggered by the user.
An event loop is basically telling the code to keep displaying the window until we
manually close it. It runs in an infinite loop in the back-end.
To create a simple window with the text Hello World!.
import tkinter
window = tkinter.Tk()
window.title("GUI") # to rename the title of the window
# pack is used to show the object in the window
label = tkinter.Label(window, text = "Hello World!").pack()
window.mainloop()
Steps:-
1.import the module tkinter.
2.Initialize the window manager with the tkinter.Tk() method and assign it to a
variable window. This method creates a blank window with close, maximize and minimize
buttons.
Tk(screenName=None,  baseName=None,  className=’Tk’,  useTk=1) 
To create a main window, tkinter offers a method ,to change the name of the
window, you can change the className to the desired one.
The basic code used to create the main window of the application is-
window = tkinter.Tk()
3.(optional) Rename the title of the window as you like with the 
window.title(title_of_the_window).

4. Label is used to insert some objects into the window. Here, we are adding a Label with
some text.
 pack() attribute of the widget is used to display the widget in a size it requires.

5. Finally, the mainloop() method to display the window until you manually close it.


Tkinter Geometry
geometry() method.
This method is used to set the dimensions of the Tkinter window and is used to set the
position of the main window on the user’s desktop

Tkinter window without using geometry method. 

import tkinter
window = tkinter.Tk()
window.title("GUI")
label = tkinter.Label(window, text = "Hello World!").pack()
window.mainloop()

As soon as you run the application, you’ll see the position of the Tkinter window is at the
north-west position of the screen and the size of the window is also small as shown in the output. 
Tkinter window using geometry method. 
import tkinter
window = tkinter.Tk()
window.title("GUI")
window.geometry('500x500')
label = tkinter.Label(window, text = "Hello World!").pack()
window.mainloop()

After running the application, you’ll see that the size of the Tkinter window is changed, but the
position on the screen is same. 
geometry manager
 In order to organize or arrange or place all the widgets in the parent window, Tkinter
provides us the geometric configuration of the widgets.

 The GUI Application Layout is mainly controlled by Geometric Managers of Tkinter.

 It is important to note here that each window and Frame in your application is allowed
to use only one geometry manager.

 Also, different frames can use different geometry managers, even if they're already
assigned to a frame or window using another geometry manager.

There are mainly three methods in Geometry Managers:


1. pack()
This method geometry manager organizes widgets in blocks before placing them in the
parent widget. It uses the options fill, expand and side.
Syntax
widget.pack(option)
Fill
Determines if the widget keeps the minimal space needed or takes up any extra space
allocated to it. Attributes: NONE (default), X (fill horizontally), Y (fill vertically), or BOTH
(fill both horizontally and vertically).
Expand
When set to YES, the widget expands to fill any space not used in widget's parent.
Attributes: YES, NO.
Side
Determines which side of the widget's parent it packs to. Attributes: TOP (default),
BOTTOM, LEFT, or RIGHT.
Example
from tkinter import *
root = Tk()
btn_fill = Button(root, text="Button")
btn_fill.pack(fill=X)
btn_expand = Button(root, text="Button")
btn_expand.pack(expand=YES)
btn_side = Button(root, text="Button")
btn_side.pack(side=RIGHT)
root.mainloop()
Output
2. grid()
 The grid() geometry manager organises widgets in a table-like structure in the parent
widget. The master widget is split into rows and columns, and each part of the table can
hold a widget. It uses column, columnspan, ipadx, ipady, padx, pady, row, rowspan and
sticky.
Syntax
widget.grid(options)
Column
The column to put widget in. The default column is 0, which is the leftmost column.
Columnspan
How many columns widget takes up. The default is 1.
ipadx
How many pixels to pad widget horizontally inside the widget's borders.
ipady
How many pixels to pad widget vertically inside the widget's borders.
Padx
How many pixels to pad widget horizontally outside the widget's borders.
Pady
How many pixels to pad widget vertically outside the widget's borders.
Row
The row to put widget in. The default row is 0, which is the topmost column.
Rowspan
How many rows the widget takes up. The default is 1.
Sticky
When the widget is smaller than the cell, sticky is used to indicate which sides and corners
of the cell the widget sticks to. The direction is defined by compass directions: N, E, S, W,
NE, NW, SE, and SW and zero. These could be a string concatenation, for example, NESW
make the widget take up the full area of the cell.
program
from tkinter import *
root = Tk()
btn_column = Button(root, text="I'm in column 3")
btn_column.grid(column=2)
btn_columnspan = Button(root, text="I have a columnspan of 3")
btn_columnspan.grid(columnspan=3)
btn_ipadx = Button(root, text="ipadx of 4")
btn_ipadx.grid(ipadx=4)
btn_ipady = Button(root, text="ipady of 4")
btn_ipady.grid(ipady=4)
btn_padx = Button(root, text="padx of 4")
btn_padx.grid(padx=4)
btn_pady = Button(root, text="pady of 4")
btn_pady.grid(pady=4)
btn_row = Button(root, text="I'm in row 2")
btn_row.grid(row=2)
btn_rowspan = Button(root, text="Rowspan of 2")
btn_rowspan.grid(rowspan=2)
btn_sticky = Button(root, text="I'm stuck to north-east")
btn_sticky.grid(sticky=NE)
root.mainloop()
output
3. place()
The place() manager organises widgets by placing them in a specific position in the
parent widget. This geometry manager uses the options anchor, bordermode, height,
width, relheight, relwidth,relx, rely, x and y.
Anchor
Indicates where the widget is anchored to. The options are compass directions: N, E, S,
W, NE, NW, SE, or SW, which relate to the sides and corners of the parent widget. The
default is NW (the upper left corner of widget)
Bordermode
Bordermode has two options: INSIDE, which indicates that other options refer to the
parent's inside, (Ignoring the parent's borders) and OUTSIDE, which is the opposite.
Height
Specify the height of a widget in pixels.
Width
Specify the width of a widget in pixels.
Relheight
Height as a float between 0.0 and 1.0, as a fraction of the height of the parent widget.
Relwidth
Width as a float between 0.0 and 1.0, as a fraction of the width of the parent widget.
Relx
Horizontal offset as a float between 0.0 and 1.0, as a fraction of the width of the parent
widget.
Rely
Vertical offset as a float between 0.0 and 1.0, as a fraction of the height of the parent
widget.
X
Horizontal offset in pixels.
Y
Vertical offset in pixels.
from tkinter import *
root = Tk()
root.geometry("500x500")
btn_height = Button(root, text="50px high")
btn_height.place(height=50, x=200, y=200)
btn_width = Button(root, text="60px wide")
btn_width.place(width=60, x=300, y=300)
btn_relheight = Button(root, text="Relheight of 0.6")
btn_relheight.place(relheight=0.6)
btn_relwidth= Button(root, text="Relwidth of 0.2")
btn_relwidth.place(relwidth=0.2)
btn_relx=Button(root, text="Relx of 0.3")
btn_relx.place(relx=0.3)
btn_rely=Button(root, text="Rely of 0.7")
btn_rely.place(rely=0.7)
btn_x=Button(root, text="X = 400px")
btn_x.place(x=400)
btn_y=Button(root, text="Y = 321")
btn_y.place(y=321)
root.mainloop()
Output
Tk Widgets:
Widgets are something like elements in the HTML. You will find different types of widgets to
the different types of elements in the Tkinter.

1. Button  11. Message


2. Canvas 12. MessageBox
3. Scale widget 13. Radiobutton
4. Label 14. Scrollbar
5. Checkbutton 15. Text
6. Entry 16. spinbox
7. Frame
8. Listbox
9. Menu
10. Menubutton
1. Button :
It is used to add buttons in a Python application. 
w = Button ( master, option=value, ... )
master − This represents the parent window.
options − Here is the list of most commonly used options for this widget.

These options can be used as key-value pairs separated by commas.


Command--Function or method to be called when the button is clicked.
Activebackground--Background color when the button is under the cursor.
Activeforeground---Foreground color when the button is under the cursor.
Bd-----Border width in pixels. Default is 2.
Bg--Normal background color.
Ex:
from tkinter import *
from tkinter import messagebox
top = Tk()
top.geometry("100x100")
def helloCallBack():
msg = messagebox.showinfo( "Hello Python", "Hello World")
B = Button(top, text = "Hello", command = helloCallBack)
B.place(x = 100,y = 100)
top.mainloop()
2. Canvas:
The Canvas is a rectangular area intended for drawing pictures or other complex
layouts. You can place graphics, text, widgets or frames on a Canvas.
Syntax;
w = Canvas ( master, option=value, ... )
master − This represents the parent window.
options − Here is the list of most commonly used options for this widget.
These options can be used as key-value pairs separated by commas.
bd--Border width in pixels. Default is 2.
bg--Normal background color.
confine--If true (the default), the canvas cannot be scrolled outside of the
scrollregion.
Cursor--Cursor used in the canvas like arrow, circle, dot etc.
height--Size of the canvas in the Y dimension.
Highlightcolor--Color shown in the focus highlight.
Ex:

import tkinter

top = tkinter.Tk()

C = tkinter.Canvas(top, bg="blue", height=250, width=300)

coord = 10, 50, 240, 210

arc = C.create_arc(coord, start=0, extent=150, fill="red“)

C.pack()

top.mainloop()
3. Scale widget:
 Scale widget is used to implement the graphical slider to the python application so that
the user can slide through the range of values shown on the slider and select the one among
them.
We can control the minimum and maximum values along with the resolution of the scale.
Syntax
w = Scale(top, options)   
A list of possible options is given below:
from_: It is used to represent one end of the widget range.
to: It represents a float or integer value that specifies the other end of the
range represented by the scale.
orient: It can be set to horizontal or vertical depending upon the type of the scale.
bd: The border size of the widget. The default is 2 pixel.
bg: The background color of the widget.
font: The font type of the widget text.
fg: The foreground color of the text
Ex:
from tkinter import *
master = Tk()
w = Scale(master, from_=0, to=100)
w.pack()
w = Scale(master, from_=0, to=200, orient=HORIZONTAL)
w.pack()
mainloop()
4. Label:
The Label is used to specify the container box where we can place the text or images. This
widget is used to provide the message to the user about other widgets used in the python
application.
There are the various options which can be specified to configure the text or the part of the
text shown in the Label.
Syntax:
w = Label (master, options)
•master is the parameter used to represent the parent window.
•There are number of options which are used to change the format of the widget.
bg: to set he normal background color.
bg to set he normal background color.
command: to call a function.
font: to set the font on the button label.
image: to set the image on the button.
width: to set the width of the button.
height” to set the height of the button.
Ex:
from tkinter import *
root = Tk()
var = StringVar()
label = Label( root, textvariable=var, relief=RAISED )
var.set("Hey!? How are you doing?")
label.pack()
root.mainloop()

relief
Specifies the appearance of a
decorative border around the
label. The default is FLAT.
5. Checkbutton:
This widget is used to display a number of options to a user as toggle buttons. The
user can then select one or more options by clicking the button corresponding to each
option. (similar to HTML checkbox input)
Ex: checkbutton
from tkinter import *
import messagebox
import tkinter
top = tkinter.Tk()
CheckVar1 = IntVar()
CheckVar2 = IntVar()
C1 = Checkbutton(top, text = "Music", variable = CheckVar1, onvalue = 1, offvalue
= 0, height=5, width = 20)
C2 = Checkbutton(top, text = "Video", variable = CheckVar2, onvalue = 1, offvalue
= 0, height=5, width = 20)
C1.pack() C2.pack() top.mainloop()
6. Entry
The Entry widget is used to provide the single line text-box to the user to accept
a value from the user.
If you want to display multiple lines of text that can be edited, then you should
use the Text widget.
If you want to display one or more lines of text that cannot be modified by the
user, then you should use the Label widget.

Ex: Entry Widget


from tkinter import *
top = Tk()
L1 = Label(top, text="User Name")
L1.pack( side = LEFT)
E1 = Entry(top, bd =5)
E1.pack(side = RIGHT)
top.mainloop()
7. Frame:
It is used to organize the group of widgets. It acts like a container
which can be used to hold the other widgets. The rectangular areas
of the screen are used to organize the widgets to the python
application.

8. Listbox:
The Listbox widget is used to display a list of items from which a
user can select a number of items.

9. Menu:
The goal of this widget is to allow us to create all kinds of menus
that can be used by our applications. The core functionality provides
ways to create three menu types: pop-up, top-level and pull-down.
Ex: frame widget
Ex: Listbox widget

from tkinter import *


import messagebox
import tkinter
top = Tk()
Lb1 = Listbox(top)
Lb1.insert(1, "Python")
Lb1.insert(2, "Perl")
Lb1.insert(3, "C")
Lb1.insert(4, "PHP")
Lb1.insert(5, "JSP")
Lb1.insert(6, "Ruby“)
Lb1.pack()
top.mainloop()
Ex: Menu
from tkinter import *
import messagebox
import tkinter
top = Tk()
mb= Menubutton ( top, text="File", relief=RAISED )
mb.grid()
mb.menu = Menu ( mb, tearoff = 0 )
mb["menu"] = mb.menu
Var1 = IntVar()
Var2 = IntVar()
mb.menu.add_checkbutton ( label="New“, variable=Var1 )
mb.menu.add_checkbutton ( label="open“, variable=Var2 )
mb.menu.add_checkbutton ( label="Save", variable=Var2 )
mb.menu.add_checkbutton ( label="Save as", variable=Var2 )
mb.menu.add_checkbutton ( label="Close“, variable=Var2 )
mb.menu.add_checkbutton ( label="Exit", variable=Var2 )
mb.pack()
10. Menubutton
It can be defined as the drop-down menu that is shown to the user
all the time. It is used to provide the user a option to select the
appropriate choice exist within the application.
11. Message:
It is used to show the message to the user regarding the behavior
of the python application.
It shows the text messages to the user which can not be edited.
The message text contains more than one line. However, the
message can only be shown in the single font.
12. MessageBox:
It is used to display message boxes in your applications.
It provides a number of functions that you can use to display an
appropriate message.
Some of these functions are showinfo, showwarning, showerror,
askquestion, askokcancel, askyesno, and askretryignore.
Ex: Message widget

from tkinter import *

root = Tk()

var = StringVar()

label = Message( root, textvariable=var, relief=RAISED )

var.set("Hey!? How are you doing?")

label.pack()

root.mainloop()
Ex: Message box widget
from tkinter import *
from tkinter import messagebox
top = Tk()
top.geometry("100x100")
def helloCallBack():
msg = messagebox.showinfo( “Say Hello", "Hello World")
B = Button(top, text = “Say Hello", command = helloCallBack)
B.place(x = 100,y = 100)
top.mainloop()
13. Radiobutton:
Set of buttons of which only one can be "pressed" (similar to
HTML radio input)

14. Scrollbar:
The scrollbar widget is used to scroll down the content of the
other widgets like listbox, text, and canvas. However, we
can also create the horizontal scrollbars to the Entry widget.

15. Text
It is used to show the text data on the Python application.
However, Tkinter provides us the Entry widget which is used
to implement the single line text box.
The Text widget is used to display the multi-line
formatted text with various styles and attributes.
The Text widget is used to provide the text editor to the
Ex: Radio button
from tkinter import *

def sel():
selection = "You selected the option " + str(var.get())
label.config(text = selection)

root = Tk()
var = IntVar()
R1 = Radiobutton(root, text=“C", variable=var, value=1,
command=sel)
R1.pack( anchor = W )

R2 = Radiobutton(root, text=“C++", variable=var, value=2,


command=sel)
R2.pack( anchor = W )

R3 = Radiobutton(root, text=“PYTHON", variable=var, value=3,


command=sel)
R3.pack( anchor = W)

label = Label(root)
label.pack()
root.mainloop()
Ex: scroll bar:

from tkinter import *

root = Tk()

scrollbar = Scrollbar(root)

scrollbar.pack( side = RIGHT, fill = Y )

mylist = Listbox(root, yscrollcommand = scrollbar.set )

for line in range(50):

mylist.insert(END, "This is line number " + str(line))

mylist.pack( side = LEFT, fill = BOTH )

scrollbar.config( command = mylist.yview )

mainloop()
Ex: text
from tkinter import *
def onclick():
pass
root = Tk()
text = Text(root)
text.insert(INSERT, "Hello.....")
text.insert(END, "Bye Bye.....")
text.pack()
text.tag_add("here", "1.0", "1.4")
text.tag_add("start", "1.8", "1.13")
text.tag_config("here", background="yellow", foreground="blue")
text.tag_config("start", background="black", foreground="green")
root.mainloop()
17. spinbox:
The Spinbox widget is a variant of the standard Tkinter Entry widget, which can be
used to select from a fixed number of values.
Ex:
from tkinter import *
master = Tk()
w = Spinbox(master, from_=0, to=10)
w.pack()
mainloop()

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy