0% found this document useful (0 votes)
33 views379 pages

Python Notes

The document provides an overview of scripting and programming languages, highlighting the differences between client-side and server-side scripting. It focuses on Python as a multi-paradigm programming language, detailing its features, installation process, and various applications. Additionally, it covers Python's IDEs, particularly PyCharm, and includes examples of code usage and debugging techniques.

Uploaded by

hemantbankar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views379 pages

Python Notes

The document provides an overview of scripting and programming languages, highlighting the differences between client-side and server-side scripting. It focuses on Python as a multi-paradigm programming language, detailing its features, installation process, and various applications. Additionally, it covers Python's IDEs, particularly PyCharm, and includes examples of code usage and debugging techniques.

Uploaded by

hemantbankar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Python Notes

What is Scripting?
SCRIPT is light weight programming. (memory)
OR
SCRIPT is loosely/weakly typed programming. (Data types declaration)
OR
SCRIPT is Simple & Easy to Learn (Less Lines Of Code)

Why Scripting?
Scripting Languages are becoming more popular due to the emergence of web-based
applications.

Types of Scripting Languages:


Scripting Languages are classified into the following two types:
1. Client Side Scripting Languages
The script which is running within the browser is called as client side scripting.
Example:
1. HTML/HTML5 2. CSS/CSS3 3. JavaScript
4. DHTML 5. TypeScript 6. ActionScript

Server Side Scripting Languages


The Script which is running within the web server is called as server side scripting.
Example:
PYTHON=>Gunicorn "Green Unicorn", WSGI (WebServerGatewayInterface), Tornado
ASP ==>IIS (Internet Information Services)
JSP ==>Tomcat/Sun Java System Web Server
PHP ==>Apache
NodeJS ==> Any Server Side JavaScript (SSJS)

Programming
It is a kind of Logic implementation to solve client business requirements. This solution can
provide in two ways:
1. Programming Languages, C, C++, JAVA, C#...!!
1. More Lines of Code 2. More Time taking
3. More Errors 4. Less Qualtiy
5. Less Productvity

2. Scritping Languages, JavaScript, PYTHON, Ruby, PERL.!


1. Less Lines of Code 2. Less Time Taking
3. Less Errors 4. More Qualtiy
5. More Productvity

Difference between SLs & PLs


1. Only Interpreted based (Read Line by Line)
2. Implicit Declaration of DataTypes(No Declaration)
3. Easily Integrated with other Technologies
Programming Languages:
1. Compiler,Interpreted,both based
2. Explicit Declaration of data types(Must Declare)
3. Difficult to Integrate with Other Technologies

SourceCode:
Source code is the language or string of words, numbers, letters and symbols that a computer
programmer uses. Code written by a programmer in a high-level language and readable by
people but not computers.

Compiler:
Compiler is software that translates source code written in a high-level language into a set of
machine-language instructions. Compilers are very large programs, with error-checking and
other abilities.

UseCase:
Compiler define some rules those are called syntaxes in the programming. It never check any
logic, for example a+b area if you write a-b it produce output.

Machine Code:
Machine language, or machine code, is a low-level language comprised of binary digits.

Output:
It is nothing but result, what a programmer expected..!

Interpreter:
It translates just one statement of the program at a time into machine code. It get executed the
program line by line. If any error in second line it never move to third line. Here no machine
code, it get executes directly. The process occured internally as follows:

Compiler => Converting


Virtual Machine==> Mapping Library files as per syntax

Types of programming Language Paradigms:


There are two types of Programming Language Paradigms:
1. Imperative Paradigm: Statements that change a programs's state.
1. Procedural Programming Paradigm
It is based on the concept of using procedures. Example: C, Pascal

2. Object-oriented Programming Paradigm


It is based on the concept of "objects",
Example: C++, JAVA

Declarative Paradigm: A style of building the structures and elements of programs


1. Functional Programming Paradigm
It is the process of building software by composing pure functions.
Example: LISP (List Processing)

2. Logical Programming Paradigm:


It is largely based on formal logic Example: PROLOG (Programming in Logic)

What is Python?
Python is a multi-paradigm Programming Language invented by [Link] VAN
ROSSUM, Named based on Monty Python's Flying Circus. It was broadcasted in BBC from
1969 to 1974.
OR
WriteLess, Create More, Run Every Where..!!

PYTHON VERSIONS:
Python 1.0 ==> 1994
Python 2.0 ==> 2000
Python 3.0 ==> Py3K 2008

PYTHON Features:
1) Easy to Learn and Use
2) Expressive Language
3) Interpreted Language
4) Cross-platform Language
5) Free and Open Source (GPL)
6) Object-Oriented Language
7) Extensible
8) Large Standard Library
9) GUI Programming Support
10) Integrated

Technology & Its Purpose:


1. C lang. => Embedded Systems
2. C++ Lang. => Graphics & Gaming Implementation
3. JAVA Lang. => Web & Gaming Development
4. .NET => Console & Windows programming
5. PHP => Web Programming
6. JavaScript => Client Side Validations
7. PYTHON => Complex data Processing & General Purpose Language.

Why Python is General Language?


PYTHON is used to develop the following software Apps:
1) WebApps=>Django, Pyramid, Flask, CherryPY..!
2) DesktopGUIApps=>TKinter,wxWidgets,Kivy,pyqt
3) SoftwareDevelopment=>BuildControl & Testing
4) Scientific &Numeric=>SciPy,Pandas, NumPy!
5) Business Apps=>Tryton, Oodo
6) Console Based Apps =>IPython
7) Audio/Video Apps =>TimPlayer, cplay
8) 3D CAD Apps =>Fandango
9) Enterprise Apps =>OpenErp,Tryton,Picalo
10) Apps for Images =>VPython, Gogh, imgSeek

Python Installation Process in Windows


1. Goto [Link]
2. Download the latest version for Windows(3.9.0)
3. Double click on that .exe file
4. Select Install for all users, click on NEXT Button
5. Finally click on Finish button.

After successful Installation You will find:IDLE


(Integrated Development & Learning Environment)

1. What is Scripting?
Script is Easy to understand
Script is Simpler & Easier

2. Types of Scripts?
Scripts are classified into the following two types:
1. Client Side Scripting Languages
A Script which running within the web browser is called Client Side Scripting Language
Example:
HTML. CSS. JavaScript. jQuery. AngularJS. Angular. EmberJS. BackboneJS.
[Link]......!!

2. Server Side Scripting Languages


A Script which running within the web server is called Server Side Scripting Language
Example:
PYTHON ==> WSGI (WebServerGatewayInterface)
PHP ==> Apache
JSP ==> Tomcat
ASP ==> IIS (Internet Information Servies)
ROR ==>GlassFish
------------------------------------------------

3. Installation Process
[Link]

Select Latest version and click on that. It get download in ur local system. Double click on
that exe file, to install...!!

After successful installation the IDLE presented in ur local machine


IDLE ==> Integrated Development Learning Enviroment
>>> Triple Chevron (Prompt of PYTHON)

>>> copyright
Displays copyright info.

>>> credits
Displays credits related to PYTHON

>>> license()
Displays license information about PYTHON
>>> exit()
Exit from IDLE screen

>>> quit()
Quit from IDLE screen

1. print() function
>>> help(print)
Help on built-in function print in module builtins:

print(...)
print(value, ..., sep=' ', end='\n', file=[Link], flush=False)

Prints the values to a stream, or to [Link] by default.


Optional keyword arguments:
file: a file-like object (stream); defaults to the current [Link].
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.

Colors Meaning
Black Standard Input
Blue Standard Output
Red Error or Comment
Green String or Charater data
Purple/Orange Function/Statement/Keyword...!!

Value Parameter Examples:


>>> print("Welcome to PYTHON Coding")
Welcome to PYTHON Coding
>>> print('Welcome to PYTHON Coding')
Welcome to PYTHON Coding
>>> print("""Welcome to PYTHON Coding""")
Welcome to PYTHON Coding
>>> print('''Welcome to PYTHON Coding''')
Welcome to PYTHON Coding

NOTE:
In Python Coding all quotes are represented Strings.

More Examples:
>>> print("Welcome to 'PYTHON' Coding")
Welcome to 'PYTHON' Coding
>>> print('Welcome to "PYTHON" Coding')
Welcome to "PYTHON" Coding
>>> print("""Welcome to '''PYTHON''' Coding""")
Welcome to '''PYTHON''' Coding
>>> print('''Welcome to """PYTHON""" Coding''')
Welcome to """PYTHON""" Coding

More Examples:
>>> print("Welcome to "PYTHON" Coding")
SyntaxError: invalid syntax
>>> print('Welcome to 'PYTHON' Coding')
SyntaxError: invalid syntax
>>> print("""Welcome to """PYTHON""" Coding""")
SyntaxError: invalid syntax
>>> print('''Welcome to '''PYTHON''' Coding''')
SyntaxError: invalid syntax

1 Single lined comment. (In Line Comments)


In Python, we use the pound (#) symbol to start writing a comment. If developer want to only
specify one line comment than use single line comment, then comment must start with #

>>> #This is single line comment. (pound)


>>> #print("Hello")
>>> #print("Welcome to PYTHON Programming")

Multi-line comments
If we have comments that extend multiple lines, one way of doing it is to use pound (#) in the
beginning of each line.

>>> #This is a long comment and it extends to multiple lines, This is a long comment and it
extends to multiple lines.

Eample: As per RealTime Project(s) UseCase:


>>> #NameOfTheProject: BFSI
>>> #NameOfTheTask:GenerateWeeklyReports
>>> #TaskAssignedBy:TeamLead
>>> #TaskReviewedBy:TeamManager/TeamLead
>>> #ApproxTaskFinishedDate:01/11/2020
>>> #CommentsOnTask:
>>> #FeedBackFromClient:

Comments in PYTHON:
Comments in Python are used to improve the readability of the code. Comments are non
executable statements or ignore statements. Using these comments we can declare user
defined or customized statements in the source code. Python supports two types of
comments.
1 Single lined comment.
2 Multi lined Comment.
1 Single lined comment. (In Line Comments)
In Python, we use the pound (#) symbol to start writing a comment. If developer want to only
specify one line comment than use single line comment, then comment must start with #

>>> #This is single line comment. (pound)


>>> #print("Hello")
>>> #print("Welcome to PYTHON Programming")

Multi-line comments
If we have comments that extend multiple lines, one way of doing it is to use pound (#) in the
beginning of each line.

>>> #This is a long comment and it extends to multiple lines, This is a long comment and it
extends to multiple lines.

Eample: As per RealTime Project(s) UseCase:


>>> #NameOfTheProject: BFSI
>>> #NameOfTheTask:GenerateWeeklyReports
>>> #TaskAssignedBy:TeamLead
>>> #TaskReviewedBy:TeamManager/TeamLead
>>> #ApproxTaskFinishedDate:01/11/2020
>>> #CommentsOnTask:
>>> #FeedBackFromClient:

PYTHON SHELL PROGRAMMING:


ScriptRunMode/Dev. Mode
You can store code in a file and use the interpreter to execute the contents of the file, which is
called a script. Python scripts have names that end with .py Extension.

Example:
1. Goto IDLE, Select File and click on New or Ctrl+N (to Open New Window)
2. Enter required python statements or commands

print("Welcome to Script MODE")


print('Welcome to Dev MODE')
print("""It is a PYTHON Shelll""")
print('''Good Bye...!!''')
print(12345)

3. Save with .py Extension @ desired location


4. Hit the key F5 or Goto run menu click Run
5. The out put displayed in readonly format on the IDLE
6. Do required modifications in the saved file and re-run..!!

PYTHON File Other Extensions:


.py ==> Python File (Regular Scripts)
.py3 ==> (rarely used) Python3 script
.pyc==> This is the compiled bytecode/compiled scripts(Bytecode)
.pyd ==> This is basically a windows dll file
.pyo ==> This is optimized pyc file
.pyw==Python script for Windows
.pyz ==> Python script archive (Compressed or Zip formated)

SETTING PYTHON PATH IN Windows:


Right click on My Computer ==>Properties ==> Advanced System Settings
==>Environment Variable ==>NewIn Variable name write path and in Variable value.
>>> import os
>>> [Link]()
Displays PYTHON Installed Path, copy path without quotes ==> Click Ok ==>Ok.

Clear screen in Windows:


There is no python builtin command for IDLE to clear the screen in Windows platform. We
can perform through customized or userdefined commands..!!

>>> print("\n"*20)#displaying blank lines


>>> clear="\n"*20#Assign blank lines
>>> print(clear)#displaying blank lines

INSIDE PYTHON
After successful installation of Python, It is the combination of Interpreter and Support
Library.

Programmers View of Interpreter


Interpreter is a software, which takes source code, reads it line by line and executes it line by
line to produce the output.

Inside INTERPRETER
In Compiled languages are, compiler converts the source code into machine code or binary
code, which is directly executed by the machine. In PYTHON compiler is using to convert
the source code(.py) into byte code.(.pyc)

What is Byte Code in PYTHON?


Byte code is easily readable by PYTHON Virtual Machine and Source code easily
understandable by programmers.
1 Low Level
2 Platform Independent
3 Efficient
4 Intermediate
5 Representation of your source code

PVM is read the byte code line by line and execute every line and produce output. In that
process PVM uses all your Library Modules.

What are PYC files?


Python automatically compiles your script to compiled code, so called byte code, before
running it.
__pycache__:
It is a folder containing Python-3 byte-code compiled and ready to be executed.

Example:
import py_compile
print(dir(py_compile))

Example:
import compileall
print(dir(compileall))

Example:
import py_compile
py_compile.compile("[Link]")

Steps to Work with PYTHON INSIDE:


1. Create a Folder/Directory on the Desktop ( or in AnyLocation)
2. Create a py file in that folder
3. Go to command prompt, change to current Folder/Dir location
4. python and hit the return key
5. import py_compile
6.py_compile.compile("[Link]")
7. __pycache__ folder created automatically with byte code

PYTHON RealTime IDEs


Define IDE?
Integrated Development Environment is a software application, that provides comprehensive
facilities to computer programmers for software development.

What is PyCharm?
It is the best IDE for realtime PYTHON projects. It provides code analysis, a graphical
debugger, an integrated unit tester and supports web development with Django framework.

PyCharm Come in two editions:


1 Community Edition (Fully-Free)
2 Professional Edition (Commercial-$199)

PyCharm IDE Installation:


1 Go to [Link]
OR
2 [Link]
3 Install any Edition Community or Professional
4 It is cross-platform and works on Windows, macOS, and Linux.

PyCharm IDE Features List:


1 Intelligent Coding Assistance
2 Built-in Developer Tools
3 Web Development
4 Scientific Tools
Components of Pycharm:
It has maily the following Components:
1. Menu or Dashboard
2. Project Panel
3. Code Editor
4. Console or Output Window

How to create a project:


1. Goto file menu, click on New project, Enter name of the Project PYTHON_6AM
2. Select Current window
3. Right click on the project select Python file, enter name of the file.
4. Enter required python source code as follows

Example:
print("Hello Welcome to PYCHARM")
x=input("Enter any Number: ")
print(x)
import os
print([Link]())
import sys
print([Link])
print([Link])
import platform
print(platform.python_version())
import keyword
print([Link])

To run the code Ctrl+Shift+F10

Debugging in PYCHARM:
It is the process of identifying and fixing problems in Code. The following short-cut keys are
required to debug..!!

1 Step Over (F8)


2 Step Into (F7)
3 Force Step Into (Alt+Shift+F7)
4 Step Out (Shift+F8)
5 Run to Cursor (Alt+F9)

Example:
a=int(input("Enter Any Number: "))
b=int(input("Enter Any Number: "))
c=a+b
print("The Result is: ",c)
d=a-b
print("The Result is: ",d)
e=a*b
print("The Result is: ",e)
f=a/b
print("The Result is: ",f)
Tabnine for PyCharm (Fast, Effective & Accurate)
Tabnine is the world’s leading AI code completion tool. It is powerful Artificial Intelligence
assistant works right in your IDE, for easy, interruption-free coding. Tabnine supports over
30 languages.

Resoruces:
[Link]

What is Anaconda?
The Most Popular Python Data Science Platform.
It is a freemium open source distribution of the Python and R PLs for large-scale data
processing, predictive analytics and scientific computing.

How to Install Anaconda?


1. [Link]
2. Click on Python 3.7 version 64-Bit Installer download
3. After successful Installation of Anaconda Platform
4. Go to MSDOS Command Prompt type spyder or jupyter notebook
5. SPYDER(Scientific PYthon Development EnviRonment)
6. JUPYteR (formerly==>iPython(JUlia, PYthon and R)

Coding Environments
Anaconda comes with two popular IDEs :

Spyder:
It is a powerful IDE for the Python language with advanced editing, interactive testing,
debugging features..!!

Main Components in Spyder.


1 Dashboard 2 Project Explorer
3 Editor 4 Console 5 Help

What is Anaconda Navigator?


It is a desktop GUI, that allows you to launch applications and easily manage conda packages
without using command-line commands.

Jupyter Notebook:([Link]
Formerly known as the IPython Notebook. It is a server-client application that allows editing
and running notebook documents via a web browser.

Features of Jupyter Notebook:


1 Edit/Run code in the browser
2 It supports 40+ Programming Languages
3 Share notebooks: using email, Dropbox, GitHub
4 BigData Integration

Define Conda?
It is an open source package management system and environment management system for
installing multiple versions of software packages.

Goto Ancondata Prompt and do the follwing:


$conda update conda
$conda install numpy
$conda help
$conda help config
$conda help info

What is pip
It is a package manager for Python programming language.

Installation
$python [Link]
$pip install pip

Syntax:
pip list [options]

Upgrading pip: UNIX:


$pip install -U pip

pip Commands:
$pip list $pip help $pip help install
$pip search django $pip install pympler
$pip uninstall django $pip show django
$pip download django $pip install virtualenv
[Link]

What is Colaboratory?
Colaboratory, or "Colab" for short, allows you to write and execute Python in your browser,
with Zero configuration required, Free access to GPUs, Easy sharing Whether you're a
student, a data scientist or an AI researcher, Colab can make your work easier.

GoogleColab:
It is a free Jupyter notebook environment that runs entirely in the cloud. It Colab support
many popular machine learning libraries which can be easily loaded in your notebook.
[Link]

WORKING WITH CORE PYTHON PROGRAMMING


Variables in PYTHON
Define Variable?
A variable is a name that refers to a value. Variables point to the memory location where data
is read and modified.

What is an identifier?
An identifier is just the name of the variable.
Python Variable Name Rules
1 Python Variables Must begin with a letter (a - z, A - Z) or underscore (_)
2 Python Variables should be characters like letters, numbers or _
3 Python Variables are Case Sensitive
4 Python Variables can be any reasonable length
5 Python Variables must not be reserved word or Keyword.
6 The variable names should be written in camelCase or PascalCase

Illegal Variable Names:


76tones = 'Big Data'
#illegal because it begin with number

more@=1000000
#illegal because it contains special character

class = 'Advanced Theoretical'


#class is one of Python’s keywords.

camel & Pascal-Case:


In Real Time Projects, camelCase &PasCal are a naming convention in which a name is
formed of multiple words that are joined together as a single word for better readability.

Examples:
"iPhone ", "eBay", "FedEx", "PayPal", etc...!!

EXAMPLES:
>>> Age=10
>>> Age10=10
>>> 10Age=10
SyntaxError: invalid syntax
>>> _Age=10
>>> #Age=10
>>> Age.22=10#Special Character must not use
SyntaxError: invalid syntax
>>> for=10#It is a keyword
SyntaxError: invalid syntax

Constants:
Fixed values such as numbers, letters & strings,are called "constants"

What is Literal?
a literal is a notation for representing a fixed value.

Python supports the following literals:


I. String literals:
[Link] literals: 1 int 2 long 3 float 4 complex
III. Boolean literals: True or False
IV. Special literals:None ==> In Python is same as "null" , means non existent, not known, or
empty.
[Link] Collections: list, tuple, set & dict

NOTE:
Literals concept is not applicable in PYTHON, but it is convention to use only uppercase
characters. It is just convention but we can change the value.

Syntax:
MIN_VALUE, MAX_VALUE

Example:
MAX_VAL=10; MIN_VAL=1
print(MAX_VAL+MIN_VAL)
MAX_VAL=100
print(MAX_VAL+MIN_VAL)

Example:
PYSTR="HELLO"#String literals:
PYINT=10#Integer Literal
PYFLOAT=10.99#Float Literal
PYCOM=1+2j#Complex Literal
PYBOOL=True#Boolean Literal
PYBOOL=False#Boolean Literal
PYSPE=None#Special Literal
PYLIST=[1,2,3,4,5]#LIST Literal
PYTUPLE=(1,2,3,4,5)#Tuple Literal
PYSET={1,2,3,4,5}#Set Literal
PYDICT={1:"RajuSir"}#Dictionary Literal

Data types in Python:


Data Type represent the type of data present inside a variable. Every value in Python has a
datatype. Since everything is an object in Python programming, data types are actually
classes and variables are instances (objects) of these classes.

Some built-in Python data types are:


1 Numeric data types: int, float, complex
2 String data types: str
3 Sequence types: list, tuple, range
4 Binary types: bytes, bytearray, memoryview
5 Mapping data type: dict
6 Boolean type: bool
7 Set data types: set, frozenset

type() function: It returns type of the given object.

Syntax:
type(object)

Example:
#Numbers, Numerical Data type
#Integer
#Declartion is an Object or Instance or Ref.
PyInt=10#int Object
print(type(PyInt))#<class 'int'>
print(PyInt)#10
#Float
PyFloat=10.001#float Object
print(type(PyFloat))#<class 'float'>
print(PyFloat)#10.001
#String
PyStr="PYTHON"#string Object
print(type(PyStr))#<class 'str'>
print(PyStr)#PYTHON
#List
PyList=[1,2,3,4]#list Object
print(type(PyList))#<class 'list'>
print(PyList)#[1, 2, 3, 4]
#Tuple
PyTuple=(1,2,3,4)#tuple Object
print(type(PyTuple))#<class 'tuple'>
print(PyTuple)#(1, 2, 3, 4)
#Set
PySet={1,2,3}#set Object
print(type(PySet))#<class 'set'>
print(PySet)#{1, 2, 3}
#Dictionary
PyDict={1:"PY",2:"DS"}#Dictionary Object
print(type(PyDict))#<class 'dict'>
print(PyDict)#{1: 'PY', 2: 'DS'}

format() function:
It returns a formatted representation of the given value controlled by the format specifier.

Syntax:
format(value[, format_spec])

'<' The field will be left-aligned within the available space


'>' The field will be right-aligned within the available space
'^' Forces the field to be centered within the available space.

Example:
print(format(123, "d"))
print(format(123.4567898, "f"))
print(format(8/9,".3f"))

Example:
print(format(123,'d'))#d-digit, integer
print(format(123,'f'))#f-float
print(format(2/3,'f'))
print(format(2/3,'.3f'))#.3f 3-float values
print(format(2/3,'.1f'))#.1f 1-float value
print(format("Hello"))
print(format("Hello",'s'))
print(format("Hello",'.1s'))
print(format("Hello",'.4s'))
print(format("Hello",'.6s'))

Example:
print(format(123, "<40"))
print(format(123, ">40"))
print(format("Hello", "^40"))

Swap variables
In Python swap values in a single line and this applies to all objects in python.

Syntax
var1, var2 = var2, var1

Example :
x = 10;y = 20
print(x,y) #10 20
x, y = y, x
print(x,y) #20 10

Example:
PyStr1="Hello";PyStr2="Bye"
print(PyStr1,PyStr2)#Hello Bye
PyStr1,PyStr2=PyStr2,PyStr1
print(PyStr1,PyStr2)#Bye Hello

Example:
#Classic way to swapping
a=23;b=42
tmp=a
a=b
b=tmp
print(a,b)
#PYTHONIC Way
a=23;b=42
a,b=b,a
print(a,b)

Python del Keyword


It is used to delete objects. In Python everything is an object, so the del keyword can also be
used to delete variables, lists, tuples, sets..!!

Syntax
del var1[,var2[,var3[....,varN]]]]

Example:
a=10;del a
print(a)#NameError: name 'a' is not defined

Example:
x=1;y=2;z=3
print(x,y,z);1 2 3
del x,y,z#Remove multiple objects at a time

Mnemonic Variable Names


This can confuse beginning students because well-named variables often “sound” so good.
There is no use in realtime industry...!!

Example1:
x1q3z9ocd = 35.0
x1q3z9afd = 12.50
x1q3p9afd = x1q3z9ocd * x1q3z9afd
print(x1q3p9afd)

Example2:
a = 3;b = 2;print(a*b)

Writing numbers in Binary, Octal & HexaDecimal


Number System Prefix
Binary 0b or 0B
Octal 0o or 0O
Hexadecimal 0x or 0X

Binary literals (base 2)


Binary literals can easily be written as well. They have to be prefixed by a leading "0",
followed by a "b" or "B":

Syntax:
bin(number)

Example:
x = 0b101010
print(x )

Example
x = bin(65)
print(x)

Octal literals (base 8)


A number prefixed by 0o (zero and a lowercase "o" or uppercase "O") will be interpreted as
an octal number

Syntax:
oct(number)

Example
x = oct(65)
print(x)

Hexadecimal literals (base 16)


Hexadecimal literals have to be prefixed either by "0x" or "0X". (Zero followed by x or X)

Syntax:
hex(number)

Decimal ==> 0-9 (10)


Hexa ==> 6 ==> A/a =>10, B/b =>11, C/c =>12
D/d =>13, E/e =>14, F/f =>15
Hexa+Decimal=6+10=16

Example:
x = hex(19)
print(x)

Example:
x = hex(64)
print(x)

Example:Output of the following SCRIPT:


x=10;y=0o10;z=0X10
print(x);print(y);print(z)
a=0XAB;print(a)

None Data Type:


The None keyword is used to define a null value, or no value at all. If the value is not
available, then to handle such type of cases None introduced.

Example:
PySpe=None
print(type(PySpe))#<class 'NoneType'>
print(PySpe)#None

Order of Operations
When an expression contains more than one operator, the order of evaluation depends on the
order of operations. For mathematical operators, Python follows mathematical convention.
The acronym PEMDAS is a useful way.

PEMDAS
Parentheses Exponentiation Multiplication Division Addition Subtraction

Parentheses
2 * (3-1)
(1+1)**(5-2)

Exponentiation
1 + 2**3 ==> 9, not 27,
2 * 3**2 ==> 18, not 36.

Multiplication and Division have higher precedence than Addition and Subtraction.
2*3-1 ==> 5, not 4,
6+4/2 ==> 8, not 5.

Pdb Module (Python Debugger)


pdb is a debugging tool that is part of python’s standard library. It is an interactive source
code debugger for Python programs. Using pdb, we can set breakpoints at any point of our
program to stop it and check for errors or the status of our running program.

Syntax:
import pdb;

PDB Options:
l (list) - Display 11 lines around the current line.
r (return) - Continue execution until the current function returns.
b (break) - Set a breakpoint (depending on the argument provided).
n (next) - Continue execution until the next line in the current function is reached.
j (jump) - Jump to the next line to be executed.
q (quit) Quit from the debugger. The program being executed is aborted.

Open run command, enter cmd


C:\cd desktop
C:\desktop\ notepad [Link]
write required Python script, save it..!!
C:\desktop\python [Link]
C:\desktop\python -m pdb [Link] (m=> Module=> PythonProgram)
> the prompt of the debugger
(pdb) l
List the lines of code..!!

Type Conversion or Type Casting:


Since Python is dynamically-typed, you may want to convert a value into another type. Every
value in Python has a data type.

Python Explicit Data Type Conversion


Primitive Data Structures:
Integers Float Strings Boolean
Non-Primitive Data Structures:
Lists Tuples Sets Dictionary

List of PYTHON Functions


1 int(x [,base]) 2 bool() 3 float(x)
4 str(x) 5 list(s) 6 tuple(s)
7 set(s) 8 dict(d) 9 ord(x)
10 chr(x) 11 complex(real,img)
12 eval()
int(x [,base]):
It converts a number in given base to decimal.

Syntax:
int(string, base)

Parameter :
string : consists of Any Number
base : (integer value) base of the number.

Example:
print(int(123))
print(int(123.098))
print(int(123.001))

Example:
print(int("1010",2))#10
print(int("1110",2))#14
print(int("1111",2))#15

Example:
print(int("12",8))#10
print(int("123",8))#83
print(int("34",8))#28

Example:
print(int("19",16))#25
print(int("4f",16))#79
print(int("98",16))#152

NOTE:
ValueError: int() base must be >= 2 and <= 36, or 0

Example:
print(int("111",2))#7
print(int("111",3))#13
print(int("111",4))#21
print(int("111",5))#31

bool()
It converts the value into a boolean.

Syntax:
bool(value)

The following values are considered false in Python:


None
False
Zero of any numeric type. For example, 0, 0.0, 0j
Empty sequence. For example, (), [], ''.
Empty mapping. For example, {}

NOTE: All other values except these values are considered true

Example:
print(bool([])); print(bool(['a value']))
print(bool('')); print(bool('A string'))
print(bool(True)); print(bool(False))
print(bool(0)); print(bool(None))
print(bool(0.0)); print(bool(1))

float(x): To convert x to a floating-point number.

Syntax:
float(value)

Example:
a=100
print(float(a))

NOTE:
We can convert any value to float type except complex type.

str() : It is Used to convert integer into a string.

Syntax:
str(value)

Example:
a=100
print(type(a)) #<class 'int'>
print(str(a))
print(type(a)) #<class 'str'>

Example:
Python code to convert string to the float value
str1 = "10.23"
str2 = "1001"

#Printing str1 & str2 types


print("type of str1: ", type(str1))
print("type of str2: ", type(str2))

#Converting to float value


val1 = float(str1)
val2 = float(str2)

#Printing types and values of val1 & val2


print("type of val1: ", type(val1))
print("type of val2: ", type(val2))

print("val1 = ", val1)


print("val2 = ", val2)

list() :
It is used to convert any data type to a list type.

Syntax:
list(items)

Example:
MyStr="PYTHON"
print(type(MyStr))
MyList=list(MyStr)
print(type(MyList))
print(MyList)

tuple() : It is used to convert to a tuple.

Syntax:
tuple(items)

Example:
MyStr="PYTHON"
print(type(MyStr))
MyTuple=tuple(MyStr)
print(type(MyTuple))
print(MyTuple)

set() :
It returns the type after converting to set

Syntax:
set(items)

Example:
MyStr="PYTHON"
print(type(MyStr))
MySet=set(MyStr)
print(type(MySet))
print(MySet)

dict() :
It is used to convert a tuple of order (key,value) into a dictionary.

Syntax:
dict(key,value)

Example:
MyTup=(('a',1),('b',2),('c',3))
print(type(MyTup))
MyDict=dict(MyTup)
print(type(MyDict))
print(MyDict)

ord() :
It is used to convert a character to integer.

Syntax:
ord('Char')

Example:
MyChar='A'
print(ord(MyChar))#65

Example:
print(ord('स'))#2360
print(ord('ल'))#2354
print(ord('గ'))#3095
print(ord('‫))'ف‬#1601

chr(i)
Return the string representing a character whose Unicode code point is the integer i.

Syntax:
chr('number')

Example:
print(chr(65))#A
print(chr(90))#Z
print(chr(32))#
print(chr(49))#1
print(chr(123))#{

Example:
print(chr(2360))#स
print(chr(2354))#ल
print(chr(3095))#గ
print(chr(1601))#‫ف‬

complex : This function converts real numbers to complex number.

Syntax:
complex(real,imag)
Format: Real + Imaginary component j

Example:
a=1
print(type(a))#<class 'int'>
print(a)#1
b=complex(a)
print(type(b))#<class 'complex'>
print(b)#(1+0j)

Example:Output of the following Script


a=complex(1,2)
b=complex(2,3)
c=a+b;print(c)
d=a-b;print(d)

Example:Output of the following Script


print(complex(20))
print(complex(10.5))
print(complex(True))
print(complex(False))
print(complex("10"))
print(complex("10.5"))

Example:Output of the following Script


print(complex(True,False))
print(complex(1,-2))
print(complex(1,-0))

What is Indentation:
Indentation is a way of telling the Python interpreter that a series of statements belong to a
particular block of code. In languages like C, C++, Java, we use curly braces { } to indicate
the start and end of a block of code. In Python, we use space/tab as indentation to indicate the
same to the compiler.

1 Increase indent after an if statement or for statement (after : )


2 Maintain indent to indicate the scope of the block
3 Blank lines are ignored - they do not affect indentation
4 Comments on a line by themselves are ignored with regard to indentation

Example:
if True:
print("True")
else:
print("False")

WORKING WITH PYTHON OPERTAORS


An operator is a character that represents an action. Python Supports different types of
Operators:

1 Arithmetical Operators
2 Comparison (Relational) Operators
3 Assignment Operators
4 Logical Operators
5 Membership Operators
6 Identity Operators
7 Bitwise Operators
8 Ternary Operator

Python Arithmetical Operators:


Arithmetic operators are used to perform various arithmetic / mathematical operations
Operator Name
+ Addition Operator
- Subtraction Operator
* Multiplication Operator
** Power Operator
/ Division Operator
% Modulus Operator
// Floor Division Operator

Syntax:
exp1 + exp2
exp1 - exp2
exp1 * exp2
exp1 ** exp2
exp1 / exp2
exp1 // exp2
exp1 % exp2

Example:
x = 15
y=4
print('x + y =',x+y)
print('x - y =',x-y)
print('x * y =',x*y)
print('x / y =',x/y)
print('x // y =',x//y)
print('x ** y =',x**y)

Example:
x=int(input("Enter Any Number: "))
y=int(input("Enter Any Number: "))
z=x+y
print("Sum is: ",z)
z=x-y
print("Diff is: ",z)
z=x*y
print("Product is: ",z)
z=x/y
print("Div is: ",z)
z=x%y
print("Mod is: ",z)
z=x**y
print("Expo is: ",z)
z=x//y
print("Fdiv is: ",z)

Python Comparison Operators


These operators are used to compare values. They are also called Relational operators.

Operator Meaning Example


> Greater that - True if left operand is greater than the right x>y
< Less that - True if left operand is less than the right x<y
== Equal to - True if both perands are equal x == y
!= Not equal to - True if operands are not equal x != y
>= True if left operand is greater than or equal to the right x >= y
<= True if left operand is less than or equal to the right x <= y

Example:
A=1;B=2
print(A==B)#False
print(A!=B)#True
print(A<B)#True
print(A>B)#False
print(A<=B)#True
print(A>=B)#False

Example:
x = 10
y = 12
# Output: x > y is False
print('x > y is',x>y)
# Output: x < y is True
print('x < y is',x<y)
# Output: x == y is False
print('x == y is',x==y)
# Output: x != y is True
print('x != y is',x!=y)
# Output: x >= y is False
print('x >= y is',x>=y)
# Output: x <= y is True
print('x <= y is',x<=y)

Python Assignment Operators


Operator Description
Example
= Assigns values from right side operands to left side operand
c = a + b assigns value of a + b into c
+= Add AND It adds right operand to the left operand and assign the result to left
operand c += a is equivalent to c = c + a
-= Subtract AND It subtracts right operand from the left operand and assign the result
to left operand c -= a is equivalent to c = c - a
*= Multiply AND It multiplies right operand with the left operand and assign the result
to left operand c = a is equivalent to c = c a
/= Divide AND It divides left operand with the right operand and assign the result to
left operand c /= a is equivalent to c = c / a
%= Modulus AND It takes modulus using two operands and assign the result to left
operand c %= a is equivalent to c = c % a
**= Exponent AND Performs exponential (power) calculation on operators and assign
value to the left operand c = a is equivalent to c = c a
//= Floor Division It performs floor division on operators and assign value to the left
operand c //= a is equivalent to c = c // a

Example:
a = 21
b = 10
c=0

c=a+b
print ("Line 1 - Value of c is ", c)

c += a
print ("Line 2 - Value of c is ", c )

c *= a
print ("Line 3 - Value of c is ", c )

c /= a
print ("Line 4 - Value of c is ", c )

c =2
c %= a
print ("Line 5 - Value of c is ", c)

c **= a
print ("Line 6 - Value of c is ", c)

c //= a
print ("Line 7 - Value of c is ", c)

Python Logical(Boolean) Operators


Python supports the following list of logical Operators:

Operator Meaning Example


and True if both the operands are true x and y
or True if either of the operands is true x or y
not True if operand is false (complements the operand) not x

Example:
x = True; y = False
# Output: x and y is False
print('x and y is',x and y)
# Output: x or y is True
print('x or y is',x or y)

# Output: not x is False


print('not x is',not x)

Example: With strings,


For "and" operator: If the first operand is True, it checks the second operand and returns the
second operand.
For "or" operator: If the first operand is False, it checks the second operand and returns the
second operand.
For "and" operator: If the operand is an empty string, it returns True; False, otherwise.

Example:
PyStr1 = "Hello"; PyStr2 = "World"

# and operator on string


print("PyStr1 and PyStr2: ", PyStr1 and PyStr2)
print("PyStr2 and PyStr1: ", PyStr2 and PyStr1)
print()

# or operator on string
print("PyStr1 or PyStr2: ", PyStr1 or PyStr2)
print("PyStr2 or PyStr1: ", PyStr2 or PyStr1)
print()

# not operator on string


print("not PyStr1: ", not PyStr1)
print("not PyStr2: ", not PyStr2)
print()

Example:
Python repr()
It returns a printable representation of the given object.

Syntax:
repr(obj)

Example:
PyStr = 'Hello Python'
print (repr(PyStr))

Example:
PyStr1 = "" # empty string
PyStr2 = "World" # non-empty string

# and operator on string


print("PyStr1 and PyStr2: ", repr(PyStr1 and PyStr2))
print("PyStr2 and PyStr1: ", repr(PyStr2 and PyStr1))
print()
# or operator on string
print("PyStr1 or PyStr2: ", repr(PyStr1 or PyStr2))
print("PyStr2 or PyStr1: ", repr(PyStr2 or PyStr1))
print()

# not operator on string


print("not PyStr1: ", not PyStr1)
print("not PyStr2: ", not PyStr2)
print()

Python Special Operators:


Python Scripting Language offers two types of Special Operators:
1. Membership operators 2. Identity operators

Python Membership Operators


They are used to test whether a value or variable is found in a sequence (string, list, tuple, set
and dictionary).

NOTE: In a dictionary we can only test for presence of key, not the value.

Operator Meaning
in True if value/variable is found in the sequence
not in True if value/variable is not found in the sequence

Examle:
PyStr="PYTHON"
print('P' in PyStr)
print('P' not in PyStr)
print('p' not in PyStr)
print('N' not in PyStr)

Example:
x = 'Hello world'
y = {1:'a',2:'b'}
print('H' in x)
print('hello' not in x)
print(1 in y)
print('a' in y)

Python Identity Operators


They are used to check if two values (or variables) are located on the same part of the
memory. Identity operators compare the memory locations of two objects.

Operator Meaning
is True if the operands are identical
is not True if the operands are not idenical

Syntax:
operand1 is operand2
operand1 is not operand2

Example:
a = b = [1,2,3]
c = [1,2,3]
print( a is b)
print( a is c)

Difference between "is" vs "=="


The is operator may seem like the same as the equality operator but they are not same. The is
checks if both the variables point to the same object whereas the == sign checks if the values
for the two variables are the same.

Example:
a=[1,2,3];b=a;print(b)
print(a is b);print(a == b)
c=list(a);print(c)
print(a is c);print(a == c)

id() function:
It is used to return the identity of an object

Syntax:
id(object)

Example:
a=[1,2,3]
print(id(a))#72563690248
b=a
print(id(b))#72563690248
print(b)#[1,2,3]
print(a is b)#True
print(a==b)#True

NOTE:
Avoid using 'is' operator for immutable types such as strings and numbers, the result is
unpredictable

String Formatting in Python:


In Python a string of required formatting can be achieved by different methods.
1) Using %
2) Using {}

Using %: The formatting using % is similar to that of ‘printf’ in C programming language.


%d ==> integer
%f ==> float
%s ==> string
%x ==> hexadecimal
%o ==> octal
Syntax:
print("formatted string" %(variable list))

Example:
print("%s having %s Years Experience in IT." %("KSRAJU","15+"))
print("%s having %d Years Experience in IT." %("KSRAJU",15))

Example:
name = "RaaJ"

print("Hello, %s!" % name)

Example:
name = "RaaJ"

age = 23

print("%s is %d years old." % (name, age))

Example:
a=10; b=20; c=30
print("a value is %i" %a)
print("b value is %d and c value is %d" %(b,c))

Formatting Strings:
We can format strings with variable values by using replacement operator {} and format()
method.

Syntax:
{ } .format(value)

value :
Can be an integer, floating point numeric constant, string, characters or even variables.

Example:
name='python'
print("Hello {}".format(name))

Syntax :
{ } { } .format(value1, value2)

Example:
name='ksraju';dept='Software'
print("Hello {} You are {} department".format(name,dept))

Syntax :
{ } { } { } .format(value1, value2,value3)

Example:
PyName='SMITH';PySal="$10000";PyLoc="HYDERABAD"
print("{}'s Sal is: {} & His Loc is: {}".format(PyName,PySal,PyLoc))
print("{0}'s Sal is: {1} & His Loc is: {2}".format(PyName,PySal,PyLoc))

Printing multiple variables


There are following methods to print multiple variables,
Method 1: Passing multiple variables as arguments separating them by commas
Method 2: Using format() method with curly braces ({})
Method 3: Using format() method with numbers in curly braces ({0})
Method 4: Using format() method with explicit name in curly braces ({v})
Method 5: Using string concatenation

Method 1:
To print multiple variables using the print() function, we need to provide the variable names
as arguments separated by the commas.

Syntax:
print(variable1, varaible2, variable3, ...)

Example:
# Python program to print multiple variables
name = "RajuSir"; age = 45; country = "INDIA"
#Printing variables one by one
print("Printing Normally...")
print(name, age, country)
print() # prints a new line
# Printing with comma seprator
print("Printing with comma seprator...")
print(name, age, country, sep=',')
print() # prints a new line
# printing variables with messages
print("Printing with messages...")
print("Name:", name, "Age:", age, "Country:", country)

Method 2:
By using the new-style string formatting (format() method), we can also print the multiple
variables. Here, we have to specify the curly braces ({}) where we have to print the values
and in the format() method, provide the multiple variables separated by the commas.

Syntax:
print("{} {} {}".format(variable1, variable2, variable2)

Example:
# Python program to print multiple variables
# using format() method
name = "RajuSir"; age = 45; country = "INDIA"
print("{} {} {}".format(name, age, country))
print("Name: {}, Age: {}, Country: {}".format(name, age, country))

Method 3:
By using the new-style string formatting with numbers (format() method), we can also print
the multiple variables. This is similar to method 2 but here we can use the numbers inside the
curly braces ({0}), it will help for reordering the values.

NOTE
Number 0 represents the first variable in format() method, 1 represents the second, and so on.

Syntax:
print("{0} {1} {2}".format(variable1, variable2, variable2)

Example:
# Python program to print multiple variables
# using format() method with numbers
name = "RajuSir"; age = 45; country = "INDIA"
print("{0} {1} {2}".format(name, age, country))
print("Name: {0}, Age: {1}, Country: {2}".format(name, age, country))
print("Country: {2}, Name: {0}, Age: {1}".format(name, age, country))
# printing all values 2-2 times
print("{0} {0} {1} {1} {2} {2}".format(name, age, country))

Method 4:
By using the new-style string formatting with explicit names (format() method), we can also
print the multiple variables. This is similar to method 3 but here we can use the explicit
names inside the curly braces ({n}), it will help for remembering the order and variable
names.

Syntax:
print("{v1} {v2} {v3}".format(v1=variable1, v2=variable2, v3=variable2)

Example:
# Python program to print multiple variables
# using format() method with explicit names
name = "RajuSir"; age = 41; country = "INDIA"
print("{n} {a} {c}".format(n=name, a=age, c=country))
print("Name: {n}, Age: {a}, Country: {c}".format(n=name, a=age, c=country))
print("Country: {c}, Name: {n}, Age: {a}".format(n=name, a=age, c=country))
# printing all values 2-2 times
print("{n} {n} {a} {a} {c} {c}".format(n=name, a=age, c=country))

Method 5:
We can print multiple variables by concatenating them as a string.

Syntax:
print(str(variable1) + str(variable2) + str(variable3))

Note:
If we want to display any message or separator, we can also concatenate them with the
variables.
If a variable is a string, then there is no need to use str().
Example:
# Python program to print multiple variables
# using string concatenation

name = "RajuSir"; age = 45; country = "INDIA"


print("Without separator...")
print(name + str(age) + country)
print("Separating by commas...")
print(name + "," + str(age) + "," + country)
print("Printing with messages...")
print("Name: " + name + " Age: " + str(age) + " Country: " + country)

Python Bitwise Operators


These are used to perform bit operations. All the decimal values will be converted into binary
values and bitwise operators will work on these bits.

OPERATOR MEANING
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
~ Bitwise complement
<< Shift left
>> Shift right

bitwise AND (&)


It compares each bit of the first operand to the corresponding bit of the second operand. If
both bits are 1, the corresponding result bit is set to 1.

Truth Table for Bitwise AND (&)


A B &(Result)
0 1 0
1 0 0
1 1 1
0 0 0

NOTE: Both are True the result will be True..!!

Example:
a=10;b=20

ANALYSIS
We declared 2 integers a and b, The binary form of
10 = 00001010 ==> for 1 Byte ==> 8 bits
20 = 00010100 ==> for 1 Byte ==> 8 bits
0000 1010 & 0001 0100 ==> 0000 0000=> Result is 0

Example:
a=10;b=20
print(a&b)#0

Example:
a=10;b=20
print(bin(a))#0b1010
print(bin(b))#0b10100
#0000 1010 & 0001 0100
print(0b00000000)#0
print(a&b)#0

Example:
a=9;b=65
print(bin(a))#0b1001
print(bin(b))#0b1000001
#0000 1001 & 0100 0001
print(0b00000001)#1
print(a&b)#1

bitwise OR
It takes two bit patterns of equal length. The result in each position is 0 if both bits are 0,
while otherwise the result is 1 (Any One 1 the Result is 1)

Syntax:
Bitwise OR Operation = a | b

Truth Table for Bitwise OR


A B |(Result)
0 1 1
1 0 1
1 1 1
0 0 0

NOTE:Any '1' the result is 1.

ANALYSIS
We declared 2 integers a and b, The binary form of
10 = 00001010 ==> for 1 Byte ==> 8 bits
20 = 00010100 ==> for 1 Byte ==> 8 bits
0000 1010 | 0001 0100 ==> 0001 1110=> Result is 30

Example:
a=10;b=20
print(a|b)#30

Example:
a=9;b=65
print(bin(a))#0b1001
print(bin(b))#0b1000001
#0000 1001 | 0100 0001
#01001001
print(a|b)#73
print(0b1001001)#73

The bitwise exclusive OR operator (^) :


It compares each bit of its first operand to the corresponding bit of its second operand. If one
bit is 0 and the other bit is 1, the corresponding result bit is set to 1. Otherwise, the
corresponding result bit is set to 0. (Identical is 0)

Syntax:
Bitwise Exclusive OR Operation = a ^ b

Truth Table for Bitwise exclusive OR(^)


A B ^(Result)
0 1 1
1 0 1
1 1 0
0 0 0

NOTE: Identical is 0

ANALYSIS
We declared 2 integers a and b, The binary form of
10 = 00001010 ==> for 1 Byte ==> 8 bits
20 = 00010100 ==> for 1 Byte ==> 8 bits
0000 1010 ^ 0001 0100 ==> 0001 1110=> Result is 30

Example:
a=10;b=20
print(a^b)

EXAMPLE:
a=9;b=65
print(bin(a))#0b0000 1001
print(bin(b))#0b0100 0001
#0000 1001 ^ 0100 0001
#0100 1000
print(0b01001000)#72
print(a^b)#72

EXAMPLE:
print(True & False)
print(True | False)
print(True ^ False)

Bitwise Complement:(~)
It is popularly known as bitwise not operator. It is unary operator. It is flipping bits.
Input Output
0 1
1 0
>>> a=20
>>> ~a
-21

Formula is:
~x = -x-1
~20=-20-1=-21
~30=-30-1=-31

Binary Ones Complement (Mathematically)


It is unary and has the effect of 'flipping' bits. Given number should be convert into binary
number. That binary number converting '0' to '1' and '1' to '0' is called Binary Ones
Complement.

In Mathematical Approach:
x=10 ==> 0000 1010 (is Binary Number)
Binary Ones Complement is ==> 1111 0101

Binary Twos Complement:


Add '1' to Binary Ones Complement is called Binary Twos Complement.
1111 0101
+1
-------------
1111 0110
-------------
NOTE: Binary Addition computations are the following:
1+1=10, 1+0=1, 0+1=1,0+0=0,1+1+1=11

Binary Ones Complement in PYTHON Solution:


It is unary and has the effect of 'flipping' bits. Given number should be convert into binary
number. That binary number converting '0' to '1' and '1' to '0' is called sign of a number
(Plus+ or Minus-).

STEP1:
x=10 ==> 0000 1010 (is Binary Number)
0000 1010

If converted number starts with 1 sign is Minus-


If converted number starts with 0 sign is Plus+

1111 0101 ===> Sign is -(Minus)

NOTE:
Mathematically binary ones complement is signature (+ or -) in PYTHON step1..!

STEP2:
Binary Ones Complement:
In PYTHON adding '1' to given binary number is called Binary Ones Complement.

x=10 ==> 0000 1010 (is Binary Number)


0000 1010
+1
-----------------
0000 1011 ==> -11 (Sign(-) from Step 1)
----------------

NOTE: Bitwise NOT (~) operator


Example:
a=10;print(~a)#-11

STEP3:
Binary TWOs Complement:
In PYTHON adding '1' to Binary Ones Complement is called Binary TWOs Complement.

0000 1011
+1
-----------------
0000 1100 ==> -12
----------------

<< Binary Left Shift


The left operands value is moved left by the number of bits specified by the right operand.
a = 10 # 10=1010
a << 2; # 40=101000==>Add Two digits right side

>> Binary Right Shift


The left operands value is moved right by the number of bits specified by the right operand.
a = 10 #10=1010
a >> 2; #2=10==>Remove two digits right side

EXAMPLE:
a=10
print(a<<2)#40
print(a>>2)#2

EXAMPLE:Output of the following Script:


print(~True)
print(True<<2)
print(True>>2)

PYTHON Control Structures:


In PYTHON Programming Control Structures are classified into:
1. Sequential Control Structures
2. Selection Control Structures
3. Iterative Control Structures

1. Sequential Control Structures:


It get excutes the lines of code in sequential order.
Example:
print("First Line")
print("Second Line")
print("Third Line")

Example:
print("First Line");print("Second Line");print("Third Line")

2. Selection Control Structures: (Conditional Control Statements)


It is popularly known as Python Decision Making. Python programming language provides
following types of decision making statements.
1 if statement (One-Way Decisions)
2 if .. else statement (Two-Way Decisions)
3 if .. elif .. else statement (Multi-Way Decisions)
4 Nested if .. else (inner Decisions)
5 Negative Conditions (Using Member-Ship Operators)

In Conditions, the following Comparison or Relational Operators Commonly Using:


1 > greater than

2 >= greater than equalto

3 < less than

4 <= less than equalto

5 == equal
6 != not equal

Python 'if' Statement


It executes a set of statements conditionally, based on the value of a logical expression.

Syntax:
if expression :
statement_1
statement_2
....

Example:
num = 3
if num > 0:
print(num, "It is a Positive Number.")
print("This is always printed.")

num = -1
if num > 0:
print(num, "It is a Positive Number.")
print("This is also always printed.")
Example:
num=input("Enter any Number: ")
if int(num) > 0:
print(num, "It is a Positive number.")

Example:
x=int(input("Enter Any Number: "))
if x>0:
print("Value is +VE");
print("It is always get Executed");
y=int(input("Enter Any Number: "))
if y<0:
print("Value is -VE");
print("It is always get Executed");

Example:(Try in 2.x)
num=input("Enter Any Data: ")
print("Type of the Data is: ")
print(type(num))

2 if .. else Statement
An else statement can be combined with an if statement. An else statement contains the block
of code that executes if the conditional expression in the if statement resolves to 0 or a
FALSE value.

Syntax
if expression:
Statement(s)_1
Statement(s)_2
else:
Statement(s)_3
Statement(s)_4

Example:
num=input("Enter any Number: ")
if int(num) > 0:
print(num, "It is a Positive number.")
else:
print(num, "It is a Negative number.")

Example:
num=input("Enter any Number: ")
print(type(num))
if int(num) > 0:
print(num, "It is a Positive number.")
else:
print(num, "It is a Negative number.")

Example:
num = 3
if num > 0:
print(num, "It is a Positive Number.")
print("This is always Printed.")
else:
print(num, "It is a Negative Number.")
rint("This is also Printed.")

Example:
num = int(input("Enter a number: "))
if (num % 2) == 0:
print("is Even")
else:
print("is Odd")

Python if...elif...else
The elif statement allows you to check multiple expressions for TRUE and execute a block of
code as soon as one of the conditions evaluates to TRUE.

Syntax
if Expression1:
statement(s)_1
statement(s)_2
elif Expression2:
statement(s)_3
statement(s)_4
elif Expression3:
statement(s)_5
statement(s)_6
else:
statement(s)_7
statement(s)_8

NOTE:
Core Python does not supports switch or case statements as in other languages.

Example:
num=input("Enter any Number: ")
print(type(num))
if int(num) > 0:
print(num, "It is a Positive number.")
elif int(num)<0:
print(num, "It is a Negative number.")
else:
print(num, "It is a ZERO.")

Example:
a=200;b=2
if b>a:
print("b is bigger")
elif a==b:
print("Both are equal")
else:
print("a is Bigger")

Example:
x=int(input("Enter Any Number: "))
y=int(input("Enter Any Number: "))
if x>0 and y>0:
print("X and Y are Positives: ")
elif x==0 and y==0:
print("Values are ZEROS")
else:
print("Values are Negatives")
print("Thank U")

Example:
grade=int(input("Enter Your Marks: "))
if grade >= 90:
print("Your Grade is A+")
elif grade >=80:
print("Your Grade is A")
elif grade >=70:
print("Your Grade is B+")
elif grade >=60:
print("Your Grade is B")
elif grade >=50:
print("You are Pass")
else:
print("Sorry You Failed")

Example:
Marks=int(input("Enter Valid Marks: "))
if Marks>=90 and Marks<=100:
print("Grade is A+")
elif Marks>=80 and Marks<=89:
print("Grade is A")
elif Marks>=70 and Marks<=79:
print("Grade is B+")
elif Marks>=60 and Marks<=69:
print("Grade is B")
elif Marks>=50 and Marks<=59:
print("Grade is C")
elif Marks>=40 and Marks<=49:
print("JUST PASS")
else:
print("Invalid Marks/Failed")

EXAMPLE:
First=int(input("Enter Any Number:"))
Second=int(input("Enter Any Number:"))
Third=int(input("Enter Any Number:"))
if First>Second and First>Third:
print("Biggest Number is:",First)
elif Second>Third:
print("Biggest Number is:",Second)
else:
print("Biggest Number is:",Third)

Nested if .. else statement


In general nested if-else statement is used when we want to check more than one conditions.
Conditions are executed from top to bottom and check each condition whether it evaluates to
true or not.

Syntax:
if expression1 :
if expression2 :
Statement_3
Statement_4
....
else :
Statement_5
Statement_6
....
else :
Statement_7
Statement_8

Example:
num = int(input("Enter a number: "))
if num >= 0:
if (num == 0):
print("ZERO")
else:
print("Positive number")
else:
print("Negative number")

Example:
x=int(input("Enter Any Number: "))
if x!=0:
if x<0:
print("-VE")
else:
print("+Ve")
else:
print("ZERO")

Example:
x=int(input("Enter Any Number: "))
if x==0:
print("ZERO")
else:
if x>0:
print("+VE")
else:
print("-VE")

Example:
x=int(input("Enter Any Number: "))
if x>=0:
if not x==0:
print("+VE")
else:
print("ZERO")
else:
print("-VE")

Example:
grade=int(input("Enter Your Marks: "))
if grade >= 90:
print("Your Grade is A+")
else:
if grade >=80:
print("Your Grade is A")
else:
if grade >=70:
print("Your Grade is B+")
else:
if grade >=60:
print("Your Grade is B")
else:
if grade >=50:
print("You are Pass")
else:
print("Sorry You Failed")

Example:
year =int(input("Enter Any Year: "))
if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
print("is a leap year")
else:
print("is not a leap year")
else:
print("is a leap year")
else:
print("is not a leap year")

Example: Use the and operator in an if statement


x = False
y = True
if x and y:
print('Both x and y are True')
else:
print('x is False or y is False or both x and y are False')

Negative Conditions in PYTHON:


If a condition is true the not operator is used to reverse the logical state, then logical not
operator will make it false.

Example:
x = int(input("Enter Any Number: "))
print(x)
if not x == 50:
print('the value of x different from 50')
else:
print('the value of x is equal to 50')

Example:
x=int(input("Enter Any Number: "))
if not x>0:
print("Value is -VE")
else:
print("Value is +VE")

RealTime Case Studies:


Example:
# Python example of "in" and "not in" Operators
PyStr = "Hello world"
PyList = [10, 20, 30, 40, 50]
# Check 'w' (capital exists in the str1 or not
if 'w' in PyStr:
print("Yes! w found in ", PyStr)
else:
print("No! w does not found in " , PyStr)
# check 'X' (capital) exists in the str1 or not
if 'X' not in PyStr:
print("yes! X does not exist in ", PyStr)
else:
print("No! X exists in ", PyStr)
# check 30 exists in the list1 or not
if 30 in PyList:
print("Yes! 30 found in ", PyList)
else:
print("No! 30 does not found in ", PyList)
# check 90 exists in the list1 or not
if 90 not in PyList:
print("Yes! 90 does not exist in ", PyList)
else:
print("No! 90 exists in ", PyList)

Example2:
x=1
print(--x)#1
print(++x)#1
print(x--) #SyntaxError: invalid syntax

NOTE:
The reason for this is, in python integers are immutable and hence cannot be changed. So, we
will have to do the following for incrementing.

x = 1; x=x+1
print(x)

x=x-1
print(x)

x+=2
print(x)

x-= 1
print(x)

Ternary Operator in Python


Ternary operators also known as conditional expressions. It was added to Python in version
2.5. It allows to test a condition in a single line.

Syntax:
[on_true] if [expression] else [on_false]

Example:
a,b =10,20
Min = a if a < b else b
print(Min)
Max = a if a > b else b
print(Max)

Example:
a=int(input("Enter Any Number:"))
b=int(input("Enter Any Number:"))
Max=a if a>b else b
print("Max Value is:",Max)

NOTE:
Nesting of ternary operator is possible.
Example:
x=int(input("Enter First Number:"))
y=int(input("Enter Second Number:"))
z=int(input("Enter Third Number:"))
Min=x if x<y and x<z else y if y<z else z
print("Minimum Value:",Min)

Python Operators Precedence (PEMDAS)


1 Parentheses are always respected
2 Exponentiation (raise to a power)
3 Multiplication, Division, and Remainder
4 Addition & Subtraction
5 Left to right

Operator Description
** Exponentiation (raise to the power)
~+- Complement, unary plus and minus
* / % // Multiply, divide, modulo and floor division
+- Addition and subtraction
>> << Right and left bitwise shift
& Bitwise 'AND'
^| Bitwise exclusive 'OR' and regular 'OR'
<= < > >= Comparison operators
== != Equality operators
= %= /= //= -= += *= **= Assignment operators
is,is not Identity operators
in,not in Membership operators
not or and Logical operators

Example:
a = 20;b = 10;c = 15;d = 5;e = 0
e = (a + b) * c / d #( 30 * 15 ) / 5
print("Value of (a + b) * c / d is ", e)

e = ((a + b) * c) / d # (30 * 15 ) / 5
print( "Value of ((a + b) * c) / d is ", e)

e = (a + b) * (c / d); # (30) * (15/5)


print( "Value of (a + b) * (c / d) is ", e)

e = a + (b * c) / d; # 20 + (150/5)
print ("Value of a + (b * c) / d is ", e)

Iterative Control Structures (Python Loops)

What is a Loop?
A loop is a sequence of instructions that is continually repeated until a certain condition is
reached.
Why Loop?
In a loop structure, the loop asks a question. If the answer requires an action, it is executed.
The same question is asked again and again until no further action is required. Each time the
question is asked is called an iteration.

TYPES OF LOOPS in PYTHON:


1. for 2. while
3. nested loops 4. break and continue (Loop Control Statements)

for loop in PYTHON:


It is used to iterate over the items of any sequence including the Python list, string, tuple etc.

Syntax
for variable_name in sequence :
statement_1
statement_2

Example:
for char in "PYTHON":
print("The Character is: ",char)

Explanation:
for ==> Keyword or Iterator
char ==> Variable
in ==> Operator
"PYTHON" ==> String or Iterable
for char in "PYTHON": ==> Iteration(s)

Example:
course_list = ["Big Data", "Hadoop", "Spark", "Scala"]
for list in course_list:
print(list)

Example:
primes = [2, 3, 5, 7]
for prime in primes:
print(prime)

Example:
languages = ["C", "C++", "Perl", "Python"]
for x in languages:
print(x)

Example:
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
Sum = 0
for val in numbers:
Sum = Sum+val
print("The sum is", Sum)
Example:
for num in [10,20,30,40,50]:
if num >=40:
print("Greater Than equal 40 is: ",num)
else:
print("Lesser Than 40 is: ",num)

Example:
dataset = ['BigData', 'python', 'Deep Learning']
for data in dataset:
print([Link]())

Collection Controlled Loops


These are also implemented with the help of for [Link] need a collection object as a source.
Python have various collection class like: list, tuple, set, dict.

Example:
# with list
data = [12,45,67,23,15]
for item in data:
print(item)

Example:
# with tuple
data = (12,45,67,23,15)
for item in data:
print(item)

Example:
# with set
data = {12,45,67,23,15}
for item in data:
print(item)

Example:
# with dictionaies
data = {1:"PY",2:"DS",3:"ML",4:"DL",5:"AI"}
for item in data:
print(item)

Example:
# Program to iterate through a list using indexing
genre = ['pop', 'rock', 'jazz','hindustani']
# iterate over the list using index
for i in range(len(genre)):
print("I like", genre[i])

range() and xrange() functions in PYTHON:


xrange() –PYTHON-2.x Version ==> Renamed as range()
range() -PYTHON-3.x Version

Range Controlled Loops:


Range Function
It generates lists containing arithmetic progression. It returns a list of consecutive integers.
The function has one, two or three parameters where last two parameters are optional. It is
widely used in for loops.

3 variations of range() function:


range(stop) - Starts from O till (stop - 1)
range(start,stop) - Ends at (stop - 1)
range(start,stop,step) - Step can not be 0, default is 1

Syntax:
range(a) range(a,b) range(a,b,c)

range(a) : Generates a sequence of numbers from 0 to a, excluding a, incrementing by 1.

Syntax
for <variable> in range(<number>):

Example:
list(range(5))

Example:
for a in range(4):
print(a)

Example:
MyItems=[1,2,3,4]
for i in range(len(MyItems)):
print(MyItems[i])

Example:
MyData=int(input("Enter Any Number in Range: "))
for data in range(MyData):
print(data)

Example:
print(range(10))#range(0, 10)
print(list(range(10)))#[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(tuple(range(10)))#(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
print(set(range(10)))#{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
print(frozenset(range(10)))#frozenset({0, 1, 2, 3, 4,5, 6, 7, 8, 9})

range(a,b) : Generates a sequence of numbers from a to b excluding b, incrementing by 1.

Syntax
for "variable" in range("start_number", "end_number"):
Note: Start Value must be less than end Value..!!

Example:
range(5,10)

Example:
for a in range(2,7):
print(a)

Example:
snumber=int(input("Enter Any Start Number: "))
enumber=int(input("Enter Any End Number: "))
for data in range(snumber,enumber):
print(data)

range(a,b,c) : Generates a sequence of numbers from a to b excluding b, incrementing by c.

Syntax
for "variable" in range("start_number", "end_number",increment):

Note:
Start Value must be less than end value, If it is increment..!!
Start Value must be bigger than end value, If it is decrement...!!

Example:
range(0,10,2)

Example:
for a in range(2,19,5):
print(a)

Example:
snumber=int(input("Enter Any Start Number: "))
enumber=int(input("Enter Any End Number: "))
incre=int(input("Enter Any increment Number: "))
for data in range(snumber,enumber,incre):
print(data)

Example: Multiplication Table


n=int(input("Enter Any Number: "))
for num in range(1, 11):
print(n, "X", num, "=", n * num)

for loop with else clause


A for loop can have an optional else block as well. The else part is executed if the items in
the sequence used in for loop exhausts. break statement can be used to stop a for loop. In such
case, the else part is ignored.

Syntax:
for <variable> in <sequence>:
<statements>
<statements>
else:
<statements>
<statements>

Example:
digits = [0, 1, 5, 7]
for i in digits:
print(i)
else:
print("No items left.")

Example:
for i in range(5):
print(i)
else:
print('Iterated over everything :)')

LOOPING CONTROL STATEMENTS/ TRANSFER STATEMENTS


A statement that alters the execution of a loop from its designated sequence is a loop control
statement.

break
To break out from a loop, you can use the keyword "break".

Syntax
for variable_name in sequence :
statement_1
statement_2
......
if expression:
break

Example:
digi = [0, 1, 5, 7]
for data in digi:
if data==4:
break
print(data)
else:
print("Loop Success")

Example:
for i in range(5):
if i==2:
break
print(i)
else:
print('Iterated over everything :)')

NOTE:
if we stop the loop, say with a break statement, then the else suite will not be executed

Example:
for x in "PYTHON":
if(x=='O'):
break
print(x)
else:
print("Loop Completed")

Continue
The continue statement is used to tell Python to skip the rest of the statements in the current
loop block and to continue to the next iteration of the loop.

Syntax:
continue;

Syntax
for variable_name in sequence :
statement_1
statement_2
......
if expression:
continue;

Example:
for i in range(1,10):
if i == 3:
continue
print(i)

Example:
digi=[1,2,3,4,5]
for data in digi:
if data==4:
continue
print(data)
else:
print("Loop Success")

Python while Loop Statements:


while Loop is used to execute number of statements or body till the condition passed in while
is true. Once the condition is false, the control will come out of the loop.

Syntax:
while <expression>:
Body
Syntax
while (expression) :
statement_1
statement_2

Example:
x=1
while x<=5:
print(x)
x=x+1
print("loop Finished")

Example: Reverse Numbers


n=5
while(n>0):
print(n)
n-=1
print("Good Bye")

Example:
# Program to add natural # sum = 1+2+3+...+n
sum = 0
i=1
while i <= 10:
sum = sum + i
i = i+1 # update counter
print("The sum is", sum)

Example:
#The following program uses a nested for loop to find the prime numbers from 2 to 100
i=2
while(i < 100):
j=2
while(j <= (i/j)):
if not(i%j): break
j=j+1
if (j > i/j) : print (i," is prime")
i=i+1
print ("Good bye!")

Example:
x=int(input("Enter Any Number less than 10: "))
while(x<=10):
print(x)
x+=1
print("Loop OK")

NOTE: Any infinite loop hit Ctrl+C to Exit from infinite loop..!!
Python: while and else statement
There is a structural similarity between while and else statement. Both have a block of
statement(s) which is only executed when the condition is true.

Syntax:
while (expression) :
statement_1
statement_2
......
else :
statement_3
statement_4

Example:
x=1
while x<=5:
print(x)
x=x+1
else:
print("loop Finished")

Example:
a=10
while a>0:
print("Value of a is",a)
a=a-1
else:
print("Loop is Completed")

Python nested loops


Python programming language allows to use one loop inside another loop.

Syntax
for [first iterating variable] in [outer loop]: # Outer loop
[do something] # Optional
for [second iterating variable] in [nested loop]: # Nested loop
[do something]

In nested loops find the following facts:


1. X-axis always contains Y-axis
2. Y-axis contains actual data
3. A row contains n number of columns
4. A column contains n number characters
5. Outer loop represents X-axis (Rows)
6. Inner loop represents Y-axis (Columns)
7. Mathematically we are representing width, height (x,y)

Example:
for a in range(1,3):
for b in range(1,3):
print(a,b)

Example:
for x in range(1, 4):
for y in range(1, 4):
print('%d * %d = %d' % (x, y, x*y))

Example:
pattern=int(input("Enter Number of Rows: "))
for i in range(1, pattern+1):
for j in range(1,i+1):
print("*",end=" ")
print()

Example: Reverse Pattern


pattern=int(input("Enter Number of rows: "))
for i in range(pattern,0,-1):
for j in range(0,i):
print("*",end="")
print()

Example:Reverse Pattern
pattern=int(input("Enter Number of rows: "))
for i in range(1,pattern+1):
for j in range(1,pattern+2-i):
print("*",end="")
print()

Example:(Printing Stars in Pyramid Shape)


pattern=int(input("Enter Number of rows: "))
for i in range(0,pattern):
for j in range(0,pattern-i-1):
print(end=" ")
for j in range(0,i+1):
print("*",end=" ")
print()

Example:(Printing Stars in Reverse Pyramid Shape)


pattern=int(input("Enter Number of rows: "))
for i in range(pattern,0,-1):
for j in range(0,pattern-i):
print(end=" ")
for j in range(0,i):
print("*",end=" ")
print()

PYTHON PASS KEYWORD


It is used when a statement is required syntactically but you do not want any command or
code to execute. The pass statement is a null operation; nothing happens when it executes.
The pass is also useful in places where your code will eventually go, but has not been written
yet.

Why Pass?
It is an empty statement
It is null statement
It results into no operation (NOP)

Syntax
pass

Example:
for letter in 'Python':
if letter == 'h':
pass
print( 'This is pass block')
print( 'Current Letter :', letter)

Example:
x=1
while(x<=3):
if(x==1):
print("1. PYTHON is SCRIPTING");
elif(x==2):
pass
else:
print("3. It is Fun to learn");
x+=1

Armstrong number:
Number of n digits which are equal to sum of nth power of its digits.

Example: 5
n(Number of Digits)=1
5 power of 1 =5 ==> It is a armstrong number

Example:7
n(Number of Digits)=1
7 power of 1 =7 ==> It is a armstrong number

Armstrong numbers are : 0 1 2 3 4 5 6 7 8 9

Example:22
n(Number of Digits)=2
2 power of 2 =4
2 power of 2 =4
4+4=8
22!=8 ==> It is not a armstrong number

Example: 153
n(Number of Digits)=3
1 power of 3 =1
5 power of 3 =125
3 power of 3 =27
1+125+27=153 ==> It is a armstrong number

Example(Armstrong Number-in PYTHON):


x=int(input("Enter Any Number: "))
for i in range(x):
num=i
result=0
n=len(str(i))
while(i!=0):
digit=i%10
result=result+digit**n
i=i//10
if num==result:
print(num)

Command Line Arguments


The command line arguments must be given whenever we want to give the input before the
start of the script. argv is not Array, it is a List. It is available sys Module. The Argument
which are passing at the time of execution are called Command Line Arguments.

Example:
from sys import argv
print(type(argv))#<class 'list'>

NOTE:
Run PYTHON Script at the command prompt of Any OS.
C:\>cd desktop

Example:
C:\>notepad [Link]
import sys
ArgList=[Link]
print(ArgList)
print([Link][0])

Executing The Script:


C:\>python [Link]
C:\>python [Link] 1 2

Example:
C:\>notepad [Link]
from sys import argv
print("Number of Command Line Arguments:", len(argv))
print("List of Command Line Arguments:", argv)
print("Line Arguments Are:",end=" ")
for x in argv:
print(x,end=" ")

Executing The Script:


C:\>python [Link]
C:\>python [Link] 1 2 3

Example:
C:\>notepad [Link]
from sys import argv
Total=0
args=argv[1:]
for x in args :
n=int(x)
Total=Total+n
print("The Total is: ",Total)

Executing The Script:


$python [Link]
$python [Link] 10 20 30 40

Example:
from sys import argv
print(argv[0])
print(argv[1])

Executing The Script:


$python [Link]

What is Data?
Data is a set of values of qualitative or quantitative variables.
Qualitative data is descriptive information (it describes something)
Quantitative data, is numerical information (numbers).

What is Information?
If we arrange some data in an appropriate sequence, then it forms a Structure and gives us
meaning. We found two things in Information: One is Data and the other is Structure.

Define Data Structure?


A data structure is a specialized format for organizing and storing data.

A data structure is classified into two categories:


1 Linear data structures
2 Non-Linear data structures

Linear data structure:


A data structure which is sequential and continues in nature.
Example: array,linked list,stack and queue.

Non Linear data structures


These are arranged in random manner. It can be used to hierarchical relationship among data
elements.
Example: Tree, Hash tree, Binary tree, Heap and graph.

Data Structures/Collections in PYTHON:


In PYTHON builtin Data Structures are Four types:
1 List is a collection which is ordered and changeable. Allows duplicate members. enclosed
[]
2 Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
enclosed in parentheses()
3 Set is a collection which is unordered and unindexed. No duplicate members. enclosed in
curly brackets {,}
4 Dictionary is a collection which is unordered, changeable and indexed. No duplicate
members. Enclosed with curly brackets {}

For Data Structures in PYTHON:


Hashable is ==> Immutable (Readonly)
Unhashable is ==> Mutable (Read&Write)
LIST is Unhashable ==> Mutable (Read&Write)
TUPLE is Hashable => Immutable (Readonly)
SET is Unhashable ==> Mutable (Read&Write)
FROZENSET is Hashable=>Immutable(Readonly)
DICTIONARY :
KEY ==> Hashable(Readonly)
Value ==> Unhashable(Read&Write)

String operations in PYTHON:


In general, you can’t perform mathematical operations on strings, even if the strings look like
numbers. The + operator performs string concatenation, which means it joins the strings by
linking them end-to-end.

Example:
first="First"; second="Second"
fullstr=first+" "+second
print(fullstr)

Example:String Repetition
print('Spam'*3)

Example: Different Quotes in PYTHON:


PyStr="PYTHON"
print(type(PyStr))#<class 'str'>
PyStr='PYTHON'
print(type(PyStr))#<class 'str'>
PyStr="""PYTHON"""
print(type(PyStr))#<class 'str'>
PyStr='''PYTHON'''
print(type(PyStr))#<class 'str'>

Assigning and Re-Assigning:


To assign a value to Python variables, type the value after the equal sign(=).

Example:
MyStr="PYTHON"
print(MyStr)#PYTHON
MyStr="Machine Leaning"
print(MyStr)#Machine Leaning

Example:
PyStr="python"
print(PyStr)
print(PyStr+PyStr)
print(PyStr+" "+PyStr)
print(PyStr*3)
print(PyStr[0])
PyStr[0]='P'
print(PyStr)

Multiple Assignment
You can assign values to multiple python variables in one statement.

Example:
a=b=c=5
print(a);print(b);print(c)

Define String Slicing?


To cut a substring from a string is called string slicing.

Here two indices are used separated by a colon (:). A slice 3:7 means indices characters of
3rd, 4th, 5th and 6th positions. The second integer index i.e. 7 is not included. You can use
negative indices for slicing.

Example:
PyStr="PYTHON IS FUN"
#P Y T H O N I S F U N
#0 1 2 3 4 5 6 7 8 9 10 11 12
#-13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
print(PyStr[0:2])
print(PyStr[2:6])
print(PyStr[7:10])
print(PyStr[1:8])

String Indices or Indexing


Strings are arrays of characters and elements of an array can be accessed using indexing.
Indices start with 0 from left side and -1 when starting from right side.

string1 ="PYTHON"
Character P Y T H O N
Index (from left) 0 1 2 3 4 5
Index (from right) -6 -5 -4 -3 -2 -1

Example:
PyStr="Naresh i Technologies"
print(PyStr[0])
print(PyStr[-1])
print(PyStr[-4])
print(PyStr[4])

Python Raw String


Python raw string is created by prefixing a string literal with ‘r’ or ‘R’. Python raw string
treats backslash (\) as a literal character. This is useful when we want to have a string that
contains backslash and don’t want it to be treated as an escape character.

Example:
PyStr='Hi\nHello'
print(PyStr)

How raw string helps us in treating backslash as a normal character?


Example:
PyStr=r'Hi\nHello'
print(PyStr)

Example:
PyStr='Hi\xHello'
print(PyStr)#SyntaxError: (unicode error)

NOTE: Python doesn’t know how to decode ‘\x’ as it doesn’t have any special meaning

Example:
PyStr=r'Hi\xHello'
print(PyStr)

Example: On-Console

NOTE:
The output having two backslashes. It’s just to show it as a normal python string where
backslash is being escaped.
>>> PyStr=r'Hi\xHello'
>>> PyStr

Unicode String
Normal strings in Python are stored internally as 16-bit Storing ASCII characters in an 8-bit
byte. while Unicode strings are stored as 16-bit Unicode.

Example:
str1=r"Normal String"
print("PYTHON Normal String is: ",str1)
str2=u"Unicode String"
print("PYTHON Unicode String is: ",str2)

Example: Indexing with Unicode Chracters


PyStr=u"हिन्दीहिन्दीहिन्दीहिन्दीहिन्दी"
print(PyStr[0])#ह
print(PyStr[-1])#ी
print(PyStr[4])#द
print(PyStr[-4])#न

Example:Slicing with Unicode Characters


PyStr=u"हिन्दीहिन्दीहिन्दीहिन्दीहिन्दी"
print(PyStr[0:1])#ह
print(PyStr[1:3])#िन
print(PyStr[4:7])#दीह

Example:
PyUString=u"नमस्ते आप कैसे हैं?"
print(PyUString)
print(PyUString[0])
print(PyUString[4])
print(PyUString[-4])
print(PyUString[-2])

NOTE:
As you can see, Unicode strings use the prefix u, just as raw strings use the prefix r.

PYTHON-String built-in Methods:

capitalize() Method
It returns a copy of the string with only its first character capitalized.

Syntax
[Link]()

Example:
str1="naresh i Technologies"
print([Link]())
str2="HELLO HOW ARE U"
print([Link]())

Python String isdigit() Method


It checks whether the string consists of digits only.

Syntax
[Link]()

Example:
str1="PYTHON"
print([Link]())
str2="12345"
print([Link]())
str3="Hello123"
print([Link]())

islower() Method
It checks whether all the case-based characters of the string are lowercase.

Syntax
[Link]()

Example:
PyStr="PYTHON"
print([Link]())
PyStr="python"
print([Link]())
PyStr="pYthOn"
print([Link]())

len() function:
It returns the length of the string.

Syntax
len( str )

Example:
PyStr="PYTHON"
print(len(PyStr))
PyStr="DataScience is ROCKING"
print(len(PyStr))

Joining of Strings:
join() Method
It is a string method and returns a string in which the elements of sequence have been joined
by str separator.

Syntax
[Link](iterable)

Example:
PyList=['1','2','3','4']
Sep="-"
print([Link](PyList))

Example:
PyList=["H","E","L","L","O"]
Sep="__"
print([Link](PyList))
Python String max() Function
It returns the max alphabetical character from the string str.

Syntax
max(str)

Example:
PyStr="abcd"
print(max(PyStr))
PyStr="abcddcba"
print(max(PyStr))
PyStr="Maximum"
print(max(PyStr))

Python String replace() Method


It returns a copy of the string in which the occurrences of old have been replaced with new,
optionally restricting the number of replacements to max.

Syntax:
[Link](old, new[,count])

Example:
str = "Hello How are You"
print([Link]("You", "U"))
print([Link]("are", "R"))
str = "Hello How are are You"
print([Link]("are", "R"))
print([Link]("are", "R",1))

title() Method
It returns a copy of the string in which first characters of all the words are capitalized.

Syntax:
[Link]();

Example:
PyStr = "this is powerful python";
print([Link]())

zfill() Method
It pads string on the left with zeros to fill width.

Syntax:
[Link](width)

Example:
PyStr="PYTHON"
print([Link](10))#0000PYTHON
print([Link](15))#000000000PYTHON
PyStr="MLDL"
print([Link](10))#000000MLDL

Python String isalnum() Method


It checks whether the string consists of alphanumeric characters.

Syntax
[Link]()

Example:
PyStr="2009";
print([Link]())
PyStr="this";
print([Link]())
PyStr="this2009";
print([Link]())
PyStr="this string example....wow"
print([Link]())

String rjust()
It returns a new string of given length after substituting a given character in left side of
original string.

Syntax:
[Link](length, fillchar)

String ljust()
It returns a new string of given length after substituting a given character in right side of
original string.

Syntax:
[Link](length, fillchar)

center() method
It will center align the string, using a specified character as the fill character.

Syntax:
center( length, fillchr )

Example:
PyStr="PYTHON"
length=10;fillchar="*"
print([Link](length,fillchar))
print([Link](length,fillchar))
print([Link](length,fillchar))

Removing spaces from a string:


rstrip()
It removes characters from the right based on the argument

Syntax:
[Link]([chars])

lstrip()
It removes characters from the left based on the argument

Syntax:
[Link]([chars])

strip()
It is used to remove all the leading and trailing spaces from a string.

Syntax :
[Link]([chars])

NOTE:
chars (optional) - a string specifying the set of characters to be removed.

Example:
PyStr=' Python For DataScience '
print([Link]())
print([Link]())
print([Link]())

isspace()
It returns True if there are only whitespace characters in the string. If not, it return False.

Syntax:
[Link]()

Example:
PyStr="Python"
print([Link]())
PyStr="Python is"
print([Link]())
PyStr=""
print([Link]())

Example:
PyStr="\t\t"
print([Link]())
PyStr="\n"
print([Link]())
PyStr=" "
print([Link]())

isprintable()
It returns True if all characters in the string are printable or the string is empty. If not, it
returns False.

Syntax:
[Link]()

Example:
PyStr='Space is a printable'
print([Link]())
PyStr='\nNew Line is printable'
print([Link]())
PyStr=''
print([Link]())

WORKING WITH PYTHON LIST DATA STRUCTURE


A list is a container which holds comma-separated values (items or elements) between square
brackets[ ] where items or elements need not all have the same type. It can have any number
of items and they may be of different types (integer, float, string etc.).

List has the following five characteristics:


1. MUTABLE
2. Linear Data Structure
3. Mixed Type Elements
4. Variable Length
5. Zero Based Indexing

NOTE: Traditional arrays can not be created in Python.

Types of lists :
Empty List: A list without any element is called an empty list

Example:
PyList = []
print(PyList)#[]

Number List:
1 Integers List:
A list with only numbers is called an integer list

Example:
PyList=[1,2,3,4,5]
print(type(PyList))#<class 'list'>
print(PyList)#[1,2,3,4,5]

Float List:
A list with only decimal numbers is called float list

Example:
PyList=[1.1,2.88,3.33,4.1,5.0]
print(type(PyList))#<class 'list'>
print(PyList)#[1.1,2.88,3.33,4.1,5.0]

String List:
A list with only Strings & Chars is called a string list

Example:
PyList = ["Sara", "David", "Raju", "Sandy"]
print(PyList)#['Sara', 'David', 'Raju', 'Sandy']
print(type(PyList))#<class 'list'>

Mixed List:
A list with different datatypes is called Mixed list.

Example:
PyList=["Sara", 1, 2.03,'A']
print(type(PyList))#<class 'list'>
print(PyList)#['Sara', 1, 2.03,'A']

Nested List:
A list with in another list is called Nested List.

Example:
PyList=["Mouse", [8, 4, 6], ['a']]
print(PyList)#['Mouse', [8, 4, 6], ['a']]
print(type(PyList))#<class 'list'>

casefold()
It convert strings to casefolded strings for caseless matching.

Syntax:
[Link]()

Example:
PyStr = "PYTHON IS AWESOME"
print([Link]())

Python String swapcase()


It converts all uppercase characters to lowercase and all lowercase characters to uppercase
characters of the given string, and returns it.

Syntax:
[Link]()

Example:
PyStr = "THIS SHOULD ALL BE LOWERCASE."
print([Link]())
PyStr="this should all be uppercase."
print([Link]())
PyStr= "ThIs ShOuLd Be MiXeD cAsEd."
print([Link]())
PyStr="UPPER lower"
print([Link]())
Python String expandtabs()
It returns a copy of string with all tab characters '\t' replaced with whitespace characters until
the next multiple of tabsize parameter.

Syntax:
[Link](tabsize) #default tab is 4-8 spaces

Example:
PyStr='xyz\t123\tabc'
print([Link]())
print([Link](10))
print([Link](15))

Finding Substrings:
In PYTHON programming to find sub strings we can use the following 4 methods:
Forward direction:
1 find() 2 index()
Backward direction:
1 rfind() 2 rindex()

find():
Returns index of first occurrence of the given substring. If it is not available then we will get
-1

Syntax:
[Link](substring,begin,end)

Example:
PyStr="Learning Python is Simpler"
print([Link]("Python"))
print([Link]("Data"))
print([Link]("e"))

Example:
PyStr="Python is"
#[Link](substring,begin,end)
print([Link]('i'))
print([Link]('s'))
PyStr="Python is good one"
print([Link]('o'))
print([Link]('o',4))
print([Link]('o',5))
print([Link]('o',12,16))
print([Link]('o',13,16))
print([Link]('O',13,16))

Example:
PyStr="hellopythonisgreat"
print([Link]('a'))
print([Link]('b',7,15))
print([Link]('t',7,15))
print([Link]('t',8,15))

index() method:
It returns the index of a substring inside the string (if found). If the substring is not found, it
raises an exception.

Syntax:
[Link](sub[, start[, end]] )

Example:
PyStr='Python programming is fun'
print([Link]('is fun'))
print([Link]('ing', 10))
print([Link]('g is', 10, -4))

Backward direction:
1 rfind() 2 rindex()

rfind()
It returns the highest index of the substring (if found). If not found, it returns -1.

Syntax:
[Link](sub[, start[, end]] )

Example:
PyStr="Learning Python is Simpler"
print([Link]("S"))
print([Link]("e"))
print([Link]("o",10))
print([Link]("e",15,25))

rindex()
It returns the highest index of the substring inside the string (if found). If the substring is not
found, it raises an exception.

Syntax:
[Link](sub[, start[, end]] )

Example:
PyStr='Do small things with great love'
print([Link]('u'))
print([Link]('t', 2))
print([Link]('h', 6, 20))

count()
It returns the number of occurrences of a substring in the given string.

Syntax:
[Link](sub[, start[, end]])

Example
PyStr = "Python is Awesome, Yes or Not"
print([Link]('i'))
print([Link]('o',1))
print([Link]('s',10,25))

startswith()
It returns True if a string starts with the specified prefix(string). If not, it returns False.

Syntax:
[Link](prefix[, start[, end]])

Example:
PyTxt="Python programming is easy."
print([Link]('programming is', 7))
print([Link]('programming is', 7, 18))
print([Link]('programming is', 7, 21))

split():
It splits a string into a list.

Syntax:
[Link](separator, max)

Example:
PyStr="hello my name is Raju"
print([Link](" "))
O/P:
['hello', 'my', 'name', 'is', 'Raju']

Example:
PyStr="hello#my#name is Raju"
print([Link]("#"))
O/P:
['hello', 'my', 'name is Raju']

Example:
PyStr="hello#my#name is Raju"
print([Link]("#",1))
O/P:
['hello', 'my'#'name is Raju']

Example:
PyStr="Hello-Welcome-To-PYTHON"
Str=[Link]('-')
for x in Str:
print(x)
Example:Reading Multiple Inputs:
>>> x=input().split()
10 20 30
>>> x
['10', '20', '30']

Basic List Operations


We can perform the following basic operations on list data structure.
[Link]
2. Repetition
3. Membership
4. Iteration
5. Length

Len Example:(Length)
PyDataSet=[1,2,4,4]
print(len(PyDataSet))#4

Example2: Concatenation
PyDataSet1=[1,2,4,4]
PyDataSet2=['a','b','c','d']
PyDataSet3=PyDataSet1+PyDataSet2
print(PyDataSet3)#[1,2,4,4,'a','b','c','d']

Example: Repetition
PyDataSet=[1,2]
print(PyDataSet*4)#[1,2,1,2,1,2,1,2]

Example : Membership
PyDataSet=[1,2,3]
print(1 in PyDataSet)#True

Example: Iteration
PyList=['Raju','Smith','Sara','Scott']
for friend in PyList:
print("Say Hey : ",friend)

How to Access elements from a list?


There are various ways in which we can access the elements of a list.

List Index
We can use the index operator [] to access an item in a list. Index starts from 0. So, a list
having 5 elements will have index from 0 to 4. The index must be an integer. Nested list are
accessed using nested indexing.

NOTE:
We can't use float or other types as index, this will result into TypeError.

Example:
PyList=["Big Data", "Hadoop", "Spark", "IoT"]
Item Big Data Hadoop Spark IoT
Index (from left) 0 1 2 3
Index (from right) -4 -3 -2 -1

Example:
PyList = ['P','Y','T','H','O','N']
print(PyList[0])
print(PyList[4])
print(PyList[-1])
print(PyList[-4])

Negative indexing
Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2
to the second last item and so on.

Example:
PyList=["Big Data", "Hadoop", "Spark", "IoT"]
print(PyList[0])
print(PyList[0],PyList[3])
print(PyList[-1])
print(PyList[4])

Example:
MyList=["PYTHON",1,2,3,["Machine"]]
print(MyList)
print(MyList[1])
print(MyList[-2])
print(MyList[-1][-1][-1])
print(MyList[-1][-1][-3])
print(MyList[-2])
print(MyList[-5][-1])

Example:
PyList=[1,2,3,"HELLO",5,6,["PYTHON"]]
print(PyList)
print(PyList[6])
print(PyList[-6])
print(PyList[-2])
print(PyList[3])
print(PyList[6][0])
print(PyList[-1])
print(PyList[-1][-1])
print(PyList[-1][-1][-1])
print(PyList[-1][-1][-1][0])
print(PyList[-1][-1][-1][-1])
print(PyList[3][0])
print(PyList[3][-3])

List Slices
Lists can be sliced like strings and other sequences. We can access a range of items in a list
by using the slicing operator (colon).

Syntax :
sliced_list = List_Name[StartIndex:EndIndex]

Example:
PyList=["Big Data", "Hadoop", "Spark", "IoT"]
print(PyList[0:2])
print(PyList[1:2])
print(PyList[1:-2])
print(PyList[:3])
print(PyList[:])

How to use start,stop,step:


Example:
PyList=["Big Data", "Hadoop", "Spark", "IoT"]
#Start:Stop
print(PyList[1:3])
#Start:Stop:Step(Increment)
print(PyList[1:3:1])
#Start:Stop:Step(Increment)
print(PyList[1:4:2])#ALternate, Hadoop, IoT
#Start:Stop:Step(Increment)
print(PyList[1:4:3])#TwoElements, Hadoop
#Start:Stop:Step(decrement)
print(PyList[3:1:-1])#IoT, SPARK
#Start:Stop:Step(decrement)
print(PyList[3:1:-2])#IoT

Example:
listx=[1, 5, 7, 3, 2, 4, 6]
print(listx)
sublist=listx[2:7:2]
print(sublist)
sublist=listx[6:2:-1]
print(sublist)

Example:
listx=[1, 5, 7, 3, 2, 4, 6, 10, 11]
print(listx[7:1:-3])
print(listx[2:7:2])
print(listx[2:7])
print(listx[:4])
print(listx[3:])

Example:
PyList=[1,3,4,6,7,8,9]
print(PyList)
print(PyList[1:5])
print(PyList[1:5:1])
print(PyList[1:5:2])
print(PyList[1:5:3])
print(PyList[1:5:4])
print(PyList[5:1:-1])
print(PyList[5:1:-2])
print(PyList[5:1:-3])
print(PyList[6:0:-4])

Example:
listx=[1, 5, 7, 3, 2, 4, 6]
print(listx)
sublist=listx[2:7:2]
print(sublist)
sublist=listx[6:2:-1]
print(sublist)

Example:
listx=[1, 5, 7, 3, 2, 4, 6, 10, 11]
print(listx[7:1:-3])
print(listx[2:7:2])
print(listx[2:7])
print(listx[:4])
print(listx[3:])

Example:
PyList=[1,3,4,6,7,8,9]
print(PyList)
print(PyList[1:5])
print(PyList[1:5:1])
print(PyList[1:5:2])
print(PyList[1:5:3])
print(PyList[1:5:4])
print(PyList[5:1:-1])
print(PyList[5:1:-2])
print(PyList[5:1:-3])
print(PyList[6:0:-4])

Double Slice Operator:


PyList=[1,2,3,4,5,6,7,8,9,10]
print(PyList)
print(PyList[::1])
print(PyList[::2])
print(PyList[::3])
print(PyList[::4])
print(PyList[::-1])
print(PyList[::-2])
print(PyList[::-3])
print(PyList[::-4])
Example:
PyList=[1,2,3,4,5,6,7,8,9,10]
print(PyList[1::5])
print(PyList[0::6])
print(PyList[5::9])
print(PyList[0::9])
print(PyList[6::11])

Example:
PyStr="Malayalam"
if PyStr==PyStr[::-1]:
print("Yes,This is Palindrome")
else:
print("NO, This is not Palindrome")

Example:
PyStr="malayalam"
if PyStr==PyStr[::-1]:
print("Yes,This is Palindrome")
else:
print("NO, This is not Palindrome")

Python List Methods


In Python Scripting The following list of methods existed in List object.
1 append() 2 extend()
3 insert() 4 remove()
5 pop() 6 clear()
7 index() 8 count()
9 sort() 10 reverse()
11 copy()

append():Add an element to the end of the list

Syntax:
[Link](item)

Example:
py_list=["Big Data", "Hadoop", "Spark", "IoT"]
print(py_list)
py_list.append("PYTHON")
print(py_list)

Example:
alist = ['a', 'b', 'c']
[Link](['d', 'e','f'])
print(alist)

NOTE:We can Modify an element by using the index of the element


Example:
py_list=["Big Data", "Hadoop", "Spark", "IoT"]
print(py_list[0])
py_list[0]="DataScinece"
print(py_list)
print(py_list[0])

Example:
py_list=["Big Data", "Hadoop", "Spark", "IoT"]
print(py_list)
py_list[2]="PYTHON"
print(py_list)

Example:
PyList=["BigData"]
print(PyList)
[Link](("ML","BC"))
print(PyList)
[Link]({"AI"})
print(PyList)
[Link]({1:"PYTHON"})
print(PyList)

NOTE: A list can append with any Data Structure..!!

extend(): Add all elements of a list to the another list

Syntax:
[Link](iterable)

Example:
alist1 = ['a', 'b', 'c']
[Link](['d', 'e','f'])
print(alist1)

# Appending two lists


Countries = ["India", "Pakistan", "Sri Lanka"]
African_Countries = ["Egypt", "Kenya", "Namibia", "Zimbabwe"]
[Link](African_Countries)
print(Countries)

Python List insert()


It inserts the element to the list at the given index.

Syntax:
[Link](index, element)

Parameters:
index - Position where element needs to be inserted
element - this is the element to be inserted in the list
Example:
MyData = ['Big', 'Data', 'Hadoop', 'Spark']
[Link](2, 'TERADATA')
print('Updated List: ', MyData)

remove(): Remove an item from the list

Syntax:
[Link](item)

Example:
py_list=["Big Data", "Hadoop", "Spark", "IoT"]
print(py_list)
py_list.remove("IoT")
print(py_list)

Example:
# Removing an item from a specific position
Fruit_List = ["Apple", "Banana", "Cherry", "Jackfruit", "Grape"]
del Fruit_List[0]
print(Fruit_List)

clear(): Removes all items from the list

Syntax:
[Link]()

Example:
py_list=["Big Data", "Hadoop", "Spark", "IoT"]
print(py_list)
py_list.clear()
print(py_list) #Empty List Displayed

index():
It returns the index in the list of the first item whose value is x.

Syntax:
[Link](item[,start][,end])

Example:
#[Link](item[,start][,end])
PyList=[1,2,3,3,2,1,5,4]
print(PyList)
print([Link](1))
print([Link](3))
print([Link](4))
print([Link](3,3))
print([Link](1,3))
print([Link](2,4))
print([Link](4,4,10))

Example:
PyList=[1,2,3,1,4,5,2,5,6,1,4]
print(PyList)
print([Link](2))
print([Link](2,2))
print([Link](1,2,7))
print([Link](4,3,9))

Example:
PyList=["Data","ML","DL","Data","ML"]
print(PyList)#['Data','ML','DL','Data','ML']
print([Link]("ML"))
print([Link]("Data"))
print([Link]("Data",1))
print([Link]("ML",2,6))

Example:
listy = list("HELLO WORLD")
print(listy)
index = [Link]("L")
print(index)
index = [Link]("L", 4)
print(index)
index = [Link]("O", 3, 5)
print(index)

count():
It returns the count of number of items passed as an argument

Syntax:
[Link](item)

Example:
PyList=["Big Data", "Hadoop", "Spark", "IoT", "Hadoop"]
print([Link]("Hadoop"))

Example:
PyList=[1,2,3,1,2,3,3,3,1,2,33]
print([Link](2))
print([Link](3))
print([Link](1))

sort():Sort the items of the list in place.

Syntax:
[Link](reverse=True|False, key=myFunc)

Parameters:
reverse Optional. reverse=True will sort the list descending. Default is reverse=False
key Optional. A function to specify the sorting criteria(s)

NOTE:sort() doesn't supports mixed data lists..!!

Example:
PyList=["Big Data", "Hadoop", "Spark", "IoT","Big Data"]
print(PyList) #['Big Data','Hadoop','Spark','IoT','Big Data']
[Link]()
print(PyList)#['Big Data','Big Data','Hadoop','IoT','Spark']
[Link](reverse=True)
print(PyList)#['Spark','IoT','Hadoop','Big Data','Big Data']

NOTE: reverse - If true, the sorted list is reversed

Example:
PyList=['cc','b','aaa','eeee','ddddddd']
print(PyList)
[Link](key=len)
print(PyList)

Example: Nested List:Sorting on First Value default


PyList=[[1,2],[2,4],[4,5],[3,1]]
print(PyList)
[Link]()
print(PyList)

Example:Sorting based on second value..!!


PyList=[[1,2],[2,4],[4,5],[3,1]]
print(PyList)
def SortBySecondValue(item):
return item[1]
[Link](key=SortBySecondValue)
print(PyList)

reverse(): Reverse the order of items in the list


Syntax:
[Link]()

Example:
PyList=["Big Data", "Hadoop", "Spark", "IoT"]
print(PyList)
[Link]()
print(PyList)

copy(): Returns a shallow copy of the list

Syntax:
[Link]()
Example:
PyList=[1,2,3,1,2,3,3,3,1,2,33]
print(PyList)
[Link](333)
print(PyList)
PyList1=[Link]()
print(PyList1)
[Link](444)
print(PyList1)

Example:
# Copying the list to a different name
Flowers = ["Lotus", "Rose", "Lily", "Sunflower"]
New_List = [Link]()
print(New_List)

Using Lists as Stacks


A stack is a container of objects that are inserted and removed according to the last-in first-
out (LIFO) principle

pop():
It is used to remove elements from right to left

Syntax:
[Link]()

Example:
py_list=["Big Data", "Hadoop", "Spark", "IoT"]
print(py_list)
py_list.append("DataScinece")
py_list.append("PYTHON")
print(py_list)
py_list.pop()
py_list.pop()
print(py_list)

Differences between remove() and pop()


remove()
1) We can use to remove specific element
2) It never return any value.
3) If element not existed returns ' VALUE ERROR'

pop()
1) Remove last element from the List.
2) It will return removed element.
3) If List has no items then we get Error.

Using Lists as Queues: It is a FIFO( First in First Out ) structure.


A deque, also known as a double-ended queue, is an ordered collection of items similar to the
queue. It is important to note that even though the deque can assume many of the
characteristics of stacks and queues, it does not require the LIFO and FIFO orderings that are
enforced by those data structures.

Example:
from collections import deque
py_list = deque(["Big Data", "Hadoop", "Spark", "IoT"])
py_list.append("DataScinece")
print(py_list)
py_list.append("PYTHON")
print(py_list)
py_list.popleft()
print(py_list)
py_list.popleft()
print(py_list)

Convert a list to a tuple in Python


MyNumList=[1,2,3,4,5]
print(type(MyNumList))
print(MyNumList)
tup=tuple(MyNumList)
print(tup)
print(type(tup))

Compare two lists in Python


PyList1=["Data","BigData","Hadoop"]
print(PyList1)
PyList2=["BigData","Hadoop","Data"]
print(PyList2)
print(PyList1==PyList2)
[Link]()
[Link]()
print(PyList1==PyList2)

Example:
PyList=[]
for i in range(10):
if i%2==1:
[Link](i)
print(PyList)

Built-in Functions with List


all() any() enumerate()
len() list() max()
min() sum() sorted()

all() Function:
It returns True when all elements in the given iterable are true. If not, it returns False.
Syntax:
all(iterable)

all() Parameters
iterable - any iterable (list, tuple, dictionary, etc.) which contains the elements

The all() method returns:


True - If all elements in an iterable are true
False - If any element in an iterable is false

Truth table for all()


When Return Value
All values are true True
All values are false False
One value is true (others are false) False
One value is false (others are true) False
Empty Iterable True

NOTE: 0 and 1 are the binary values like False, True

Example:How all() works for tuple and lists?


s = [1, 3, 4, 5]
print(all(s))

s = [0, False]
print(all(s))

s = [0, False, 5]
print(all(s))

s = []
print(all(s))

Python any()
It Returns True if any element of an iterable is true. If not, this method returns False.

Syntax:
any(iterable)

The any method returns:


True if at least one element of an iterable is true
False if all elements are false or if an iterable is empty

When Return Value


All values are true True
All values are false False
One value is true (others are false) True
One value is false (others are true) True
Empty Iterable False
NOTE: 0 and 1 are the binary values like False, True

Example:
s =[1, 3, 4, 0]
print(any(s))

s = [0, False]
print(any(s))

s = [0, False, 5]
print(any(s))

s = []
print(any(s))

Python enumerate()
It adds counter to an iterable and returns it (the enumerate object).

Syntax
enumerate(iterable, start=0)

Parameters:
iterable: A sequence, an iterator, or objects that supports iteration
start(optional): It starts counting from this number. If start is omitted, 0 is taken as start.

How enumerate() works in Python?


BigData=['Big Data', 'Hadoop', 'Spark','Data Science']
eData = enumerate(BigData)
print(type(eData))
print(list(eData))

Looping Over an Enumerate object


bd = ['Big Data', 'Hadoop', 'Spark','Data Science']
for item in enumerate(bd):
print(item)

Example:
bd = ['Big Data', 'Hadoop', 'Spark','Data Science']
for count, item in enumerate(bd):
print(count, item)

Example:
bd = ['Big Data', 'Hadoop', 'Spark','Data Science']
for count, item in enumerate(bd, 100):
print(count, item)

Example:
names = ['Bob', 'Alice', 'Guido']
print(list(enumerate(names)))
Example:
names = ['Bob', 'Alice', 'Guido']
for index, value in enumerate(names):
print(f'{index}: {value}')

len() Function:
It displays length of characters in numeric format.

Syntax:
len(iterable)

Example:
PyList=[1,2,3,4,5]
print(len(PyList))

list():
It is converting into list data type.

Syntax:
list(iterable)

Example:
PyStr="Hello"
print(list(PyStr)) #['H', 'e', 'l', 'l', 'o']

max():
It is used to display max character based on ASCII or Unicode Value

Syntax:
max(iterable)

Example:
print(max(1,2,3,4))
print(max('a','b','c','d','E'))

min()
It is used to display min character based on ASCII or Unicode value.

Syntax:
min(iterable)

Example:
print(min(1,2,3,4))
print(min('a','b','c','d','E'))

sum()
It is used to display sum of values in the list, only for numeric values..

Syntax:
sum(iterable)
Example:
print(sum([1,2,3,4]))

sorted() for list, tupe & dictinary


It returns a sorted list of the specified iterable [Link] can specify ascending or
descending order. Strings are sorted alphabetically, and numbers are sorted numerically.

Note: You cannot sort a list that contains BOTH string values AND numeric values.

Syntax
sorted(iterable, key=key, reverse=reverse)

Parameters:
iterable Required. The sequence to sort, list, dictionary, tuple etc.
key Optional. A Function to execute to decide the order. Default is None
reverse Optional. A Boolean. False will sort ascending, True will sort descending. Default
is False

Example:
a = ["b", "g", "a", "d", "f", "c", "h", "e"]#List
x = sorted(a)
print(x)
a = ("b", "g", "a", "d", "f", "c", "h", "e")#Tuple
x = sorted(a)
print(x)
a = {"b":"g", "a":"d", "f":"c", "h":"e"}#Dictionary
x = sorted(a)
print(x)

Example:
a = ["b", "g", "a", "d", "f", "c", "h", "e"]
x = sorted(a,reverse=True)
print(x)
a = ("b", "g", "a", "d", "f", "c", "h", "e")
x = sorted(a,reverse=True)
print(x)
a = {"b":"g", "a":"d", "f":"c", "h":"e"}
x = sorted(a,reverse=True)
print(x)

Example:
a = ["bb", "ggg", "aaaa", "dddd", "ff"]
x = sorted(a,key=len)
print(x)
a = ("bb", "ggg", "aaaa", "dddd", "ff")
x = sorted(a,key=len)
print(x)
a = {"bb":"ggg", "aaaa":"d", "ff":"c"}
x = sorted(a,key=len)
print(x)

Example:
a = {"bb":"ggg", "aaaa":"d", "ff":"c"}
x = sorted(a,key=len)
print(x)
print(sorted([Link]()))
print(sorted([Link]()))
print(sorted([Link]()))

List_of_Lists
Example:
A=[1]*2
print(A)
B=[[1]*2]*5
print(B)
C=[[2,0]*1]*4
print(C)

Example:
A=[[1]*2]*5
print(A)
B=[[2,0]*1]*4
print(B)

Example:
#List_of_Lists
A=[2]*3
print(A)
B=[[2]*3]*2
print(B)
C=[[1,0]*1]*5
print(C)

Example:
List shortcuts
Fives = [5]*4
print(Fives)

Example:
A=[1,2,3,4,5]
print(A[0]*2)
print(A*2)
print(A[3]*3)
print(A[4]*1)
print(A*3)

Example:
PyList=[1,[2,[3,[4,[5]]]]]
print(PyList[0])
print(PyList[1][0])
print(PyList[1][1][0])

Example:
PyList=[1,[2,[3,[4,[5]]]]]
print(PyList)
print(PyList[0])
print(PyList[1])
print(PyList[1][0])
print(PyList[1][1])
print(PyList[1][1][0])
print(PyList[1][1][1])
print(PyList[1][1][1][0])
print(PyList[1][1][1][1])
print(PyList[1][1][1][1][0])

Example:
PyList=[1,[2,[3,[4,[5]]]]]
print(PyList)
print(PyList[0])
print(PyList[1])
print(PyList[1][1])
print(PyList[1][1][1])
print(PyList[1][1][1][1])
print(PyList[1][1][1][1][-1])
print(PyList[1][1][1][1][0])

List comprehension
In this method, we basically define the process through which the list needs to be created. We
specify what operation needs to be done and on what elements it needs to done.

Syntax:
[expression for item in iterable]

Example:
result=[x**2 for x in [3,4,5]]
print(result)

Example:
#[expression for item in iterable]
print([x*1 for x in [1,2,3,4]])
print([x*2 for x in [1,2,3,4]])
print([x**2 for x in [1,2,3,4]])
print([x**2 for x in [1,2,3,4] if x%2==0])
print([x**2 for x in [1,2,3,4] if x%2!=0])

Syntax:
[expression if conditional else stmt for item in iterable]
Example:
print([x if x>3 else x+1 for x in [1,2,3,4,5,6]])#[2, 3, 4, 4, 5, 6]
print([x if x>3 else x+3 for x in [1,2,3,4,5,6]])#[4, 5, 6, 4, 5, 6]
print([x if x<3 else x+3 for x in [1,2,3,4,5,6]])#[1, 2, 6, 7, 8, 9]

Example:
num=[1,2,3,4]
result=[x*10 for x in num]
print(result)

Example:
print([x for x in "Hello12345" if [Link]()])
print([x for x in "Hello12345" if [Link]()])

NOTE: If any character other than alpha, nums will be ignore...!!

Example:
words=['Hello',"Hai",'python']
result=[[Link]() for x in words]
print(result)

Example:
Sample_List = ["Sample", "List"]
Result = [item[0] for item in Sample_List]
print(Result)

Example:
a=[1,2,3,4,5,6]
b=[2,3]
result=[x+y for x in a for y in b]
print(result )

Hardcopy, shallowCopy and DeepCopy in python (Copy or Clone)


Hard Copy an Object in Python
In Python, we use = operator to create a copy of an object. You may think that this creates a
new object; it doesn't. It only creates a new variable that shares the reference of the original
object.

Example:
myList=[1,2,3,4,5,6]
print(myList)
yourList=myList
print(yourList)
myList[0]="NareshIT"
print(myList)
print(yourList)

In Python, there are two ways to create copies:


1 Shallow Copy or COPY
2 Deep Copy
Copy Module
We use the copy module of Python for shallow and deep copy operations. Suppose, you need
to copy the compound list say x.

Example:
import copy
print(dir(copy))

Shallow Copy ([Link]())


A shallow copy creates a new object which stores the reference of the original elements. So, a
shallow copy doesn't create a copy of nested objects, instead it just copies the reference of
nested objects. This means, a copy process does not recurse or create copies of nested objects
itself.

Example:
import copy
myList=[1,2,3,4,5,6]
print(myList)
yourList=myList
print(yourList)
myList=[Link](yourList)
myList[4]="PYTHON"
print(myList)
print(yourList)

Example:
import copy
old_list = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
new_list = [Link](old_list)
old_list.append([4, 4, 4])
print("Old list:", old_list)
print("New list:", new_list)

Deep Copy
A deep copy constructs a new compound object and then recursively inserts the copies into it
the objects found in the original.

Syntax:
[Link](x)

Example:
import copy
yourList=[1,2,3,4,['a','b','c']]
myList=[Link](yourList)
myList[4][1]="Hello"
print(myList)
print(yourList)

Example:
import copy
ys = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
zs = [Link](ys)
ys[1][1] = 'X'
print(ys)#[[1, 2, 3], [4, 'X', 6], [7, 8, 9]]
print(zs)#[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

zip() in Python
The purpose of zip() is to map the similar index of multiple containers so that they can be
used just using as single entity. Python Zip and Unzip lists, tuples.

Syntax :
zip(*iterators)

Parameters : Python iterables or containers ( list, string etc )


Return Value :
Returns a single iterator object, having mapped values from all the containers.

Example:
PyList1=["Hadoop","Spark","PYTHON","DataScience"]
PyList2=["Bigdata","Teradata","Pandas","SKLearn"]
z1=zip(PyList1,PyList2)
print(list(z1))

Example:
Pylist1=[1,2]
Pylist2=[2,3]
ziplist=zip(Pylist1,Pylist2)
ziptuple=zip(Pylist1,Pylist2)
zipset=zip(Pylist1,Pylist2)
zipdict=zip(Pylist1,Pylist2)
print(list(ziplist))
print(tuple(ziptuple))
print(set(zipset))
print(dict(zipdict))

Example:
PyList1=["Hadoop","Spark","PYTHON","DataScience"]
PyList2=["Bigdata","Teradata","Pandas","SKLearn"]
for l1,l2 in zip(PyList1,PyList2):
print(l1,l2)

Example:
PyList1=["Hadoop","Spark","PYTHON","DataScience"]
PyList2=["Bigdata","Teradata","Pandas","SKLearn"]
Dict_Zip=dict(zip(PyList1,PyList2))
print(Dict_Zip)

Example:
PyList1=[10,20,30,40]
PyList2=[50,60,70,80]
for a,b in zip(PyList1,PyList2):
print('{} + {}={}'.format(a,b,a+b))

How to unzip?
Unzipping means converting the zipped values back to the individual self as they were. This
is done with the help of “*” operator.

Example:
PyList1=["Hadoop","Spark","PYTHON","DataScience"]
PyList2=["Bigdata","Teradata","Pandas","SKLearn"])
z1=zip(PyList1,PyList2)
z2=zip(*(z1)
print(*z2)

Difference between del and None Keywords:


del
The variable will be removed and we cannot access that variable(unbind operation)

Example:
PyStr="PYTHON"
del PyStr
print(PyStr)#NameError: name 'PyStr' is not defined.

None:
None assignment the variable will not be removed but the corresponding object is eligible for
Garbage Collection(re-bind operation).

Example:
PyStr="PYHON"
print(PyStr)#PYTHON
PyStr=None
print(PyStr)#None

WORKING WITH PYTHON ARRAYS


It is the collection of elements of a single data type, eg. array of int, array of string. In Python,
there is no native array data structure. So, we use Python lists instead of an array.

Create an Array
We can create a Python array with comma separated elements between square brackets[].

How to create an array in Python?


We can make an integer array and store it to arr.
PyArr = [10, 20, 30, 40, 50]

Access elements of an Array


We can access individual elements of an array using index inside square brackets [].

Array Index
Index is the position of element in an array. In Python, arrays are zero-indexed. This means,
the element's position starts with 0 instead of 1.

Example: Accessing elements of array using indexing


PyArr = [10, 20, 30, 40, 50]
print(PyArr[0])
print(PyArr[1])
print(PyArr[2])

Find length of an Array


Python arrays are just lists, so finding the length of an array is equivalent to finding length of
a list in Python.

Example:
PyBrands=["Coke", "Apple", "Google", "Microsoft", "Toyota"]
NumBrands=len(PyBrands)
print(NumBrands)

Slicing of an Array
Python has a slicing feature,It allows to access pieces of an array. [x : y]

Example:
PyFruits=["Apple", "Banana", "Mango", "Grapes", "Orange"]
print(PyFruits[1:4])
print(PyFruits[ :3])
print(PyFruits[-4:])
print(PyFruits[-3:-1])

Multi-Dimensional Arrays
It is an array within an array. This means an array holds different arrays inside it.

Example:
MultArr = [[1,2], [3,4], [5,6], [7,8]]
print(MultArr[0])
print(MultArr[3])
print(MultArr[2][1])
print(MultArr[3][0])

Python Matrix
A matrix is a two-dimensional data structure. In python, matrix is a nested list.

Example:
PyArr=[['Roy',80,75,85,90,95],
['John',75,80,75,85,100],
['Dave',80,80,80,90,95]]
print(PyArr[0])
print(PyArr[0][1])
print(PyArr[1][2])
print(PyArr[2][2])
Python Arrays
Array is an idea of storing multiple items of the same type together and it makes easier to
calculate the position of each element by simply adding an offset to the base value. A
combination of the arrays could save a lot of time by reducing the overall size of the code. It
is used to store multiple values in single variable. If you have a list of items that are stored in
their corresponding variables like this:

The array can be handled in Python by a module named array. It is useful when we have to
manipulate only specific data values. Following are the terms to understand the concept of an
array:

Element - Each item stored in an array is called an element.


Index - The location of an element in an array has a numerical index

Array Representation
An array can be declared in various ways and different languages. The important points that
should be considered are as follows:
Index starts with 0.
We can access each element via its index.
The length of the array defines the capacity to store the elements.

Array operations
Some of the basic operations supported by an array are as follows:
Traverse - It prints all the elements one by one.
Insertion - It adds an element at the given index.
Deletion - It deletes an element at the given index.
Search - It searches an element using the given index or by the value.
Update - It updates an element at the given index.

The Array can be created in Python by importing the array module to the python program.
from array import *
arrayName = array(typecode, [initializers])

Accessing array elements


We can access the array elements using the respective indices of those elements.

import array as arr


a = [Link]('i', [2, 4, 6, 8])
print("First element:", a[0])
print("Second element:", a[1])
print("Second last element:", a[-1])

Arrays are mutable, and their elements can be changed in a similar way like lists.
import array as arr
numbers = [Link]('i', [1, 2, 3, 5, 7, 10])

# changing first element


numbers[0] = 0
print(numbers) # Output: array('i', [0, 2, 3, 5, 7, 10])
# changing 3rd to 5th element
numbers[2:5] = [Link]('i', [4, 6, 8])
print(numbers) # Output: array('i', [0, 2, 4, 6, 8, 10])

The length of an array is defined as the number of elements present in an array. It returns an
integer value that is equal to the total number of the elements present in that array.

Syntax
len(array_name)

Array Concatenation
We can easily concatenate any two arrays using the + symbol.

Example
a=[Link]('d',[1.1 , 2.1 ,3.1,2.6,7.8])
b=[Link]('d',[3.7,8.6])
c=[Link]('d')
c=a+b
print("Array c = ",c)

Example
import array as arr
x = [Link]('i', [4, 7, 19, 22])
print("First element:", x[0])
print("Second element:", x[1])
print("Second last element:", x[-1])

WORKING WITH PYTHON TUPLE DATA STRUCTURE


Tuple is readonly List
OR
It is a collection that cannot be modified. A tuple is defined using parenthesis.

Advantages of Tuple over List


1 We generally use tuple for heterogeneous (different) datatypes and list for homogeneous
(similar) datatypes.
2 Since tuple are immutable, iterating through tuple is faster than with list.
3 Tuples that contain immutable elements can be used as key for a dictionary. With list, this
is not possible.

More About Tuple:


[Link] can't add elements to a tuple.
[Link] can't remove elements from a tuple.

How to Create a tuple?


To create a tuple, just list the values within parenthesis separated by commas.

Creating Empty Tuple:


PyTuple = ()
print(type(PyTuple))#<class 'tuple'>
print(PyTuple)#()

Creating tuple having integers


PyTuple=(1, 2, 3)
print(type(PyTuple))#<class 'tuple'>
print(PyTuple)#(1, 2, 3)

Creating tuple having float values


PyTuple=(1.1, .1.2, 3.1)
print(type(PyTuple))#<class 'tuple'>
print(PyTuple)#(1.1, 1.2, 3.1)

Creating a tuple with mixed datatypes


PyTuple = (1, "Data Science", 3.4)
print(type(PyTuple))#<class 'tuple'>
print(PyTuple)#(1, 'Data Science', 3.4)

Creating a Nested tuple


PyTuple=("Data Science", (8, 4, 6), (1, 2, 3))
print(type(PyTuple))#<class 'tuple'>
print(PyTuple)#('Data Science', (8, 4, 6), (1, 2, 3))

Tuple Packing.
Creating tuple without parentheses, also called tuple packing.
PyTuple = 3, 4.6, "Data Science"
print(type(PyTuple))#<class 'tuple'>
print(PyTuple)#(3, 4.6, 'Data Science')
#Tuple Unpacking is also possible
a, b, c = PyTuple
print(a);print(b);print(c)

NOTE:
if a value is more, it dislays "Value Error",
if a variable is more, it displays "not enough values"

Creating a tuple with one element is a bit tricky.


Having one element within parentheses is not enough. We will need a trailing comma to
indicate that it is in fact a tuple.

Example:
PyTuple = ("Data Science")

print(type(PyTuple)) #<class 'str'>


PyTuple = ("Data Science",)

print(type(PyTuple))#<class 'tuple'>
PyTuple = "Data Science",

print(type(PyTuple)) #<class 'tuple'>


Example: #List Inside Tuple
MyTuple=('a',[1,2])
print(type(MyTuple))
print(MyTuple[0])
print(MyTuple[1])
print(MyTuple[1][1])
MyTuple[1][1]='4'
print(MyTuple)

Example:
PyTuple=(1,2,3,[4,5])
print(type(PyTuple))
print(PyTuple[0])
print(PyTuple[3])
print(PyTuple[3][0])
PyTuple[3][0]=40
print(PyTuple[3])
print(PyTuple[3][1])
PyTuple[0]=100
print(PyTuple)

Tuple Membership Test:


We can test if an item exists in a tuple or not, using the keyword in.

Example:
PyTuple=(1,2,3,[4,5])
print(type(PyTuple))#<class 'tuple'>
print(1 in PyTuple)
print(10 not in PyTuple)
print(5 in PyTuple)

Iterating Through a Tuple


Using a for loop we can iterate through each item in a tuple.

Example:
for name in ('KSRaju','Dinesh',"NareshIT"):
print("Hai",name)

Slice a Tuple:
We can access a range of items in a tuple by using the slicing operator - colon ":"

Example:
PyTuple = (2, 4, 3, 5, 4, 6, 7, 8, 6, 1)
print(PyTuple[3:5])
print(PyTuple[:6])
print(PyTuple[5:])
print(PyTuple[:])
print(PyTuple[-8:-4])

Slice of a tuple using step parameter


PyTuple = tuple("DATA SCIENCE")
print(PyTuple)
print(PyTuple[2:9:2])
print(PyTuple[::4])
print(PyTuple[9:2:-3])

How operators + and * are used with a Python tuple?


#+ Operator Concatenation
PyTuple1=(3, 6, 9, 12, 15)
PyTuple2=("P", "Y", "T", "H", "O", "N")
PyTuple3=(True, False)
PyTuple4=PyTuple1+PyTuple2+PyTuple3
print(PyTuple4)
#Repetation * Operator
PyTuple5=5,
print(PyTuple5*6)

Python Tuple Methods:


Tuple object supports the following list of Methods:
Method Description
count(x) Return the number of items that is equal to x
index(x) Return index of first item that is equal to x

In Python how to know the number of times an item has repeated


PyTuple = 2, 4, 5, 6, 2, 3, 4, 4, 7
print(PyTuple)
print([Link](4))
print([Link](7))
print([Link](5))

Find the index of an item of the tuple:


PyTuple=tuple("index tuple")
print(PyTuple)
print([Link]("p"))
print([Link]("e", 5))
print([Link]("e", 3, 6))

Add item in tuple!


Method-I
tuplez = (4, 6, 2, 8, 3, 1)
print(tuplez)
tuplez = tuplez + (9,)
print(tuplez)

Method-II
tuplez = (4, 6, 2, 8, 3, 1)
print(tuplez)
listx = list(tuplez)
[Link](30)
tuplez = tuple(listx)
print(tuplez)

Example:
PyTuple=(1,2,3,4)
[Link]((5,6,7))
print(len(PyTuple))

Deleting a Tuple:
We cannot change the elements in a tuple. That also means we cannot delete or remove items
from a tuple. But deleting a tuple entirely is possible using the keyword del.

Example:
PyTuple=('P','Y','T','H','O','N','S','C','R')
del PyTuple
print(PyTuple) #NameError: name 'PyTuple' is not defined

Example:
Remove an item from a tuple (Through List)
PyTuple="P", "Y", "T", "H", "O", "N", "S"
PyList=list(PyTuple)
[Link]("P")
PyTuple=tuple(PyList)
print(PyList)#['Y', 'T', 'H', 'O', 'N', 'S']

Built-in Functions with Tuple


all() any() enumerate() len() max() min() sorted() sum() tuple()

Python enumerate()
The enumerate() method adds counter to an iterable and returns it (the enumerate object).

Syntax
enumerate(iterable, start=0)

Example:
bd = ('Big Data', 'Hadoop', 'Spark')
enumerateData = enumerate(bd)
print(type(enumerateData))
print(tuple(enumerateData))
enumerateData = enumerate(bd, 10)
print(tuple(enumerateData))

Example:
bd = ('Big Data', 'Hadoop', 'Spark')
for item in enumerate(bd):
print(item)

Example:
for count, item in enumerate(bd, 100):
print(count, item)
all() Function:
It returns True when all elements in the given iterable are true. If not, it returns False.

Syntax:
all(iterable)

all() Parameters
iterable - any iterable (list, tuple, dictionary, etc.) which contains the elements

The all() method returns:


True - If all elements in an iterable are true
False - If any element in an iterable is false

Truth table for all()


When Return Value
All values are true True
All values are false False
One value is true (others are false) False
One value is false (others are true) False
Empty Iterable True

NOTE: 0 and 1 are the binary values like False, True

Example:How all() works for tuple and lists?


s = (1, 3, 4, 5)
print(all(s))

s = (0, False)
print(all(s))

s = [0, False, 5]
print(all(s))

s = []
print(all(s))

Python any()
It Returns True if any element of an iterable is true. If not, this method returns False.

Syntax:
any(iterable)

The any method returns:


True if at least one element of an iterable is true
False if all elements are false or if an iterable is empty

When Return Value


All values are true True
All values are false False
One value is true (others are false) True
One value is false (others are true) True
Empty Iterable False

NOTE: 0 and 1 are the binary values like False, True

Example:
s = (1, 3, 4, 0)
print(any(s))

s = (0, False)
print(any(s))

s = [0, False, 5]
print(any(s))

s = []
print(any(s))

Python len()
The len() function returns the number of items (length) of an object.

Syntax
len(s)

Example:
testList = []
print(len(testList))

Example:
#The size of a tuple
tuplez = tuple("PYTHON")
print(tuplez)
print(len(tuplez))

Example:
testRange = range(1, 10)
print(len(testRange))

Python sorted()
The sorted() method sorts the elements of a given iterable in a specific order - Ascending or
Descending.

Syntax
sorted(iterable[, reverse])

Parameters:
iterable - sequence (string, tuple, list) or collection (set, dictionary, frozen set) or any iterator
reverse (Optional) - If true, the sorted list is reversed (or sorted in Descending order)
Sort a given sequence: string, list and tuple
Example:
pyList = ['e', 'a', 'u', 'o', 'i']
print(sorted(pyList))

Example
pyString = 'Python'
print(sorted(pyString))

Example
pyTuple = ('e', 'a', 'u', 'o', 'i')
print(sorted(pyTuple))

Example
pyTuple = ('e', 'a', 'u', 'o', 'i')
print(sorted(pyTuple,reverse=True))

Python sum()
The sum() function adds the items of an iterable and returns the sum.

Syntax:
sum(iterable)

sum() Parameters
iterable - iterable (list, tuple, dict etc) whose item's sum is to be found. Normally, items of the
iterable should be numbers.

Example:
numbers = [2.5, 3, 4, -5]
numbers = sum(numbers)
print("Sum of Numbers is: " ,numbers)

Python tuple() Function


The tuple() built-in is used to create a tuple in Python.

Syntax:
tuple(iterable)

Parameter:
iterable (optional) an iterable (list, range etc.) or an iterator object

# creating a tuple from a list


t2 = tuple([1, 4, 6])
print(t2)

# creating a tuple from a string


t1 = tuple('Python')
print(t1)

#tuple to List
MyTuple=(1,2,3,4)
print(type(MyTuple))
print(MyTuple)
MyList=list(MyTuple)
print(type(MyList))
print(MyList)

Python Tuple vs List:


Lists are mutable while Tuples are immutable.
Lists have variable length while tuple has fixed length.
Lists has more functionality than tuple.
List object size is comparatively larger than Tuple.
Execution of tuple is faster than Lists.

WORKING WITH PYTHON SET DATASTRUCTURE..!!

Python Sets
SET is an unordered collection of unique elements

How to create a set?


1 Insertion order is not [Link] we can sort the elements.
2 Indexing and slicing not allowed for the set.
3 Heterogeneous elements are allowed.
4 We can represent set elements within curly braces and with comma seperation
5 We can apply mathematical operations like union,intersection,difference etc

There are currently two built-in set types:


1 set ==> The set type is mutable
2 frozenset. ==> It is immutable and hashable

Example:
FruitBasket={"Apple","Mango","orange","banana","Apple","Mango"}
print(type(FruitBasket))
print(FruitBasket)

Example:
We should not use empty curly brackets, treat as dict.!
PySet={}
print(type(PySet)) #<class 'dict'>

Set not allowed duplicates but list allows:


Numbers=[1,2,3,4,1,2,3,4,5]
UniqueNumbers=set(Numbers)
print(UniqueNumbers) #{1,2,3,4,5}

Iteration Over Sets


We can move over each of the items in a set using a loop. However, since sets are unorded

Example:
NumSet = set([0, 1, 2, 3, 4, 5])
for n in NumSet:
print(n)

Different Python Set Methods


1 add() 2 clear()
3 copy() 4 difference()
5 difference_update() 6 discard()
7 intersection() 8 intersection_update()
9 isdisjoint() 10 issubset()
11 issuperset() 12 pop()
13 remove() 14 symmetric_difference()
15 symmetric_difference_update()
16 union() 17 update()

Python Set add():


It adds a given element to a set. If the element is already present, it doesn't add that element.

Syntax:
[Link](elem)

Example:
PySet={}
print(PySet)
[Link](1)
print(PySet)#AttributeError: 'dict' object has no attribute 'add'

Example:
PySet={1}
print(PySet)#{1}
[Link](1)
print(PySet)#{1}

Example:
PySet={1}
print(PySet)
[Link](1,2)
print(PySet)
#TypeError: add() takes exactly one argument (2 given)

Example:
PySet={1}
print(PySet)
[Link]([1,2])
print(PySet)
#TypeError: unhashable type: 'list'

Example:
PySet={1}
print(PySet)#{1}
[Link]((1,2))
print(PySet)#{(1, 2), 1}

clear():
It is used to clear all elements from a set.

Syntax:
[Link]()

Example:
PySet={1}
print(PySet)#{1}
[Link]()
print(PySet)#set()

Python Set update():


It adds elements from a set to the set.
OR
A |= B or [Link](B)
Adds all elements of array B to the set A.

Syntax
[Link](B)

NOTE:
A and B are two sets. The elements of set B are added to the set A.

Example:
DataSet=set()
[Link](["Data Science", "Big Data"])
print(DataSet)

Example:
A={10,20,30}; B=[40,50,60,10]
[Link](B,range(5))
print(A)

Python Set pop()


It removes an arbitrary element from the set and returns the element removed.

Syntax:
[Link]()

Example:
A ={'a', 'b', 'c', 'd'}
print('Return Value is', [Link]())
print(A)

Example:
NumSet = set([0, 1, 2, 3, 4, 5])
[Link]()
print(NumSet)
[Link]()
print(NumSet)

Python Set remove()


It searches for the given element in the set and removes it, but not a member of the set, a
KeyError will be raised.

Syntax:
[Link](element)

Example:
NumSet = set([0, 1, 2, 3, 4, 5])
[Link](0)
print(NumSet)

Trying to Delete Element That Doesn't Exist


Example:
PyPets = {'cat', 'dog', 'rabbit'}
[Link]('cow')
print(PyPets)#KeyError

Python Set discard()


An element will be removed from the set, if it is contained in the set. If not a member of the
set, nothing will be done.

Syntax:
[Link](x)

Example:
NumSet = set([0, 1, 2, 3, 4, 5])
[Link](3)
print(NumSet)

Example:
PyNums={2, 3, 4, 5}
[Link](3)
print(PyNums)
[Link](10)
print(PyNums)

Example:
# Removing the elements of the set
# remove(), discard() and pop() can be used to remove the elements of a set
# If the element to be removed is not present in the set, remove() will raise an error while
discard() will not
# pop() removes the last item from the set. A set is unordered, so the element which will be
removed is not known
Colour = {"Black", "Blue", "Red", "Green", "Orange", "Violet"}
[Link]("Blue")
[Link]("Green")
print(Colour)
x = [Link]()
print(x)
print(Colour)

intersection(s) (AND)
A set with all the elements which are contained in both sets is returned.

Syntax:
[Link](set2)

Example:
x = {"a","b","c","d","e"}
y = {"c","d","e","f","g"}
print([Link](y))
print(x & y) #ampersand operator "&":

A &= B or A.intersection_update(B)
The intersection of two or more sets is the set of elements which are common to all sets.

Sytnax:
A.intersection_update(*Other_sets)

Example:
A = {1, 2, 3, 4}
B = {2, 3, 4, 5}
A.intersection_update(B)
print(A)
print(B)

Union of sets (OR)


A | B or [Link](B) Returns a set which is the union of sets A and B.

Syntax:
[Link](set2)

Example:
PySetx=set(["Big Data", "Data Science"])
PySety=set(["Data Science", "Spark"])
PySeta = PySetx |PySety #Union
print (PySeta)

Set difference() In set1 but not set2

Syntax
[Link](B)

Example:
A = {1, 2, 3, 4}
B = {2, 3, 9}
print([Link](B))
print([Link](A))

Example:
A = {'a', 'b', 'c', 'd'}
B = {'c', 'f', 'g'}
print([Link](B))# Equivalent to A-B
print([Link](A))# Equivalent to B-A

A -= B or A.difference_update(B)
Removes all elements of B from the set A.

Syntax:
A.difference_update(B)

Example:
A = {'a', 'c', 'g', 'd'}
B = {'c', 'f', 'g'}
A.difference_update(B)
print(A)

Set symmetric_difference() (XOR)


It returns a new set which is the symmetric difference of two sets. The symmetric difference
of two sets A and B is the set of elements which are in either of the sets A or B but not in
both. (A-B)UNION(B-A)

Syntax:
A.symmetric_difference(B)

Example:
A = {'a', 'b', 'c', 'd'}
B = {'c', 'd', 'e' }
print(A.symmetric_difference(B))

Example:
PySetx=set(["Big Data", "Data Science"])
PySety=set(["Data Science", "Spark"])
PySetc=PySetx.symmetric_difference(PySety)
print(PySetc)
PySetd=PySetx^PySety
print(PySetd)

A ^= B or A.symmetric_difference_update(B)
Writes in A the symmetric difference of sets A and B.

Syntax:
A.symmetric_difference_update(B)
Example:
A = {'a', 'c', 'd'}
B = {'c', 'd', 'e' }
A.symmetric_difference_update(B)
print(A)

Set issuperset(): set1 contains set2

Syntax:
[Link](B) or A >= B

Example:
A = {1, 2, 3, 4, 5}
B = {1, 2, 3}
C = {1, 2, 3}
print([Link](B))
print([Link](A))
print([Link](B))

Set issubset() set2 contains set1

Syntax:
[Link](B) or A <= B

Example:
A = {1, 2, 3, 4, 5}
B = {1, 2, 3}
C = {1, 2, 3}
print([Link](B))
print([Link](A))
print([Link](B))

isdisjoint()
It returns True, if two sets have a null intersection.

Syntax:
set_a.isdisjoint(set_b)

Example:
A = {1, 2, 3, 4}
B = {5, 6, 7}
C = {4, 5, 6}
print([Link](B))
print([Link](C))

Set copy(): It returns a shallow copy of the set.

Syntax:
[Link]()
Example:
PySetx = set(["Big Data", "Data Science"])
PySetd = [Link]()
print(PySetd)

Special Operators with set (Membership operators)


x={"a","b","c","d","e"}
print("a" in x)
print("d" in x)

Iterations with for loop:


x={"a","b","c","d","e"}
for i in x:
print(i)

Built-in Functions with Set


all() any() enumerate() len()
max() min() sorted()

Example:
PySet={4,5,8,2.2}
print(PySet)#{8, 2.2, 4, 5}
print(sorted(PySet))#[2.2, 4, 5, 8]

WORKING WITH PYTHON DICITIONARY..!!

Array
It is the collection of elements of a single data type

Example:
PyArray=[1,2,3,4,5,6]
PyArray=["Hello","Hei","PYTHON"]

Linked List :
A linked list is a linear collection of data elements.
32 ==> 15 ==> 36 ==> 56 ==> 24

Advantages over arrays


1) Dynamic size
2) Ease of insertion/deletion

Limitations:
1 Access Very Slow
2 No Index to access
3 We sholud travel sequentially

To avoid the above limitations, Hash table introduced...!!


What is Hash Table?
A hash table (hash map) is a data structure which implements an associative array abstract
data type.

Ele % Size=Location (Mod means remainder)


32 % 5=2
15 % 5=0
36 % 5=1
56 % 5=1
24 % 5=4

PYTHON HASHING (HASH TABLES AND HASHLIB)


What is Hash Table?
Hash Table is a data structure which stores data in an associative manner. In a hash table,
data is stored in an array format.
OR
1 Hash Tables or Hashmap
2 It is a set of key-value Pairs
3 No Duplicate keys
4 Also Called as dictionary, map, hash table, associative array
5. In PYTHON use dict keyword or dict() Method.

Components of Hashmap:
Array ==> Data structure used to store the data
Hash function ==> function to convert key into an array index
Collision Handling==> Multiple key value pairs Map the same cell of an Array.

Basic Operations:
I. Search II. Insert III. delete

Hash Function:
index=len(key)-1

Key-Value
Beans-1.85
Corn-2.38
Rice-1.92

A better Hash function in PYTHON


index=sum(ASCII value for each letter in key)%Size

Python Dictionaries
A dictionary is a sequence of items. Each item is a pair made of a key and a value.
Dictionaries are not sorted.

Why Dictionary?
1 Dictionaries are Python’s most powerful data collection
2 Dictionaries allow us to do fast database-like operations in Python
3 Associative Arrays - PERL / PHP, HashMap - Java, Property Bag - C# / .Net
How to create a dictionary?
Creating a dictionary is as simple as placing items inside curly braces {} separated by
comma. An item has a key and the corresponding value expressed as a pair, key: value.

Create a new Dictionary in Python:


#Empty dictionary
PyDict = {}
print(type(PyDict))#<class 'dict'>
print(PyDict)#{}

#Dictionary with integer keys


PyDict = {1: "Bigdata", 2: "Hadoop"}
print(type(PyDict))#<class 'dict'>
print(PyDict)#{1:'Bigdata',2:'Hadoop'}

#Dictionary with mixed keys


PyDict={'name': 'NareshIT', 1: [2, 4, 3]}
print(type(PyDict))#<class 'dict'>
print(PyDict)#{'name':'NareshIT',1:[2,4,3]}

Using dict Keyword:


PyDict=dict({1:'Bigdata', 2:'Hadoop'})
print(type(PyDict))#<class 'dict'>

# from sequence having each item as a pair


PyDict=dict([(1,'Bigdata'), (2,'Hadoop')])
print(type(PyDict))#<class 'dict'>

Add key/value to a dictionary in Python


PyDict={1:"Hadoop"}
print(PyDict)#{1: 'Hadoop'}
PyDict[2]="Spark"
print(PyDict)#{1: 'Hadoop', 2: 'Spark'}
PyDict[1]="H2O"
print(PyDict)#{1: 'H2O', 2: 'Spark'}

Loop Through a Dictionary


Looping through a dictionary, the return value are the keys of the dictionary.

Example:
PyCourses = {1: "PYTHON",2: "ML", 3: "DS" }
print(PyCourses)
for item in PyCourses:
print(item)

Examples:
PyCourses = {1: "PYTHON",2: "ML", 3: "DS" }
print(PyCourses)
for item in [Link]():
print(item)
Example:
PyCourses = {1: "PYTHON",2: "ML", 3: "DS" }
print(PyCourses)
for item in [Link]():
print(item)

Example:
PyCourses = {1: "PYTHON",2: "ML", 3: "DS" }
print(PyCourses)
for item in [Link]():
print(item)

Python Dictionary Methods


1 clear() 2 copy()
3 fromkeys(seq[, v]) 4 get(key[,d])
5 items() 6 keys()
7 pop(key[,d]) 8 popitem()
9 update([other]) 10 values()

clear()
It is used to clear all keys and values from a dictionary.

Syntax:
[Link]()

Example:
PyDict={1: 'PYDOOP', 2: 'Spark', 3: 'PYTHON'}
print(PyDict)#{1: 'PYDOOP', 2: 'Spark', 3: 'PYTHON'}
[Link]()
print(PyDict)#{}#empty dictionary

copy()
It is used to create duplicate dictionary or shallow dictionary

Syntax:
[Link]()

Example:
PyDict={1: 'PYDOOP', 2: 'Spark', 3: 'PYTHON'}
print(PyDict)#{1: 'PYDOOP', 2: 'Spark', 3: 'PYTHON'}
PyDict1=[Link]()
print(PyDict1)#{1: 'PYDOOP', 2: 'Spark', 3: 'PYTHON'}

The fromkeys() method


It creates a new dictionary from the given sequence of elements with a value provided by the
user.

Syntax:
[Link](sequence[, value])
fromkeys() Parameters
sequence - sequence of elements which is to be used as keys for the new dictionary
value (Optional) - value which is set to each element of the dictionary-Default-None

Example:
keys = {'a', 'e', 'i', 'o', 'u' }
vowels = [Link](keys)
print(vowels)

Example:
keys = {'a', 'e', 'i', 'o', 'u' }
value = 'vowel'
vowels = [Link](keys, value)
print(vowels)

Example:
# this method returns a dictionary with the specified keys and values
# if the value is not specified for the keys, then the default value is "NONE"
X = ('key1', 'key2', 'key3', 'key4', 'key5')
Y=1
This_Dict = [Link](X, Y)
print(This_Dict)

Dictionary get()
It returns the value for the specified key if key is in dictionary.

Syntax:
[Link](key[, value])

get() Parameters
key - key to be searched in the dictionary
value (optional) - Value to be returned if the key is not found. The default value is None.

Example:
person = {'name': 'NareshIT', 'Exper': 15}
print('Name: ', [Link]('name'))
print('Exper: ', [Link]('Exper'))
print('Salary: ', [Link]('salary'))
print('Salary: ', [Link]('salary', '$100000'))

Example:
PyDict={'a':"BigData",'b':"Data Science",'c':"PTYHON"}
print(PyDict)#{'a': 'BigData', 'b': 'Data Science', 'c': 'PTYHON'}
print([Link]('a'))#BigData
print([Link]('d'))#None
PyDict['d']="Machine Learning"
print([Link]('d'))#Machine Learning

Dictionary items()
It returns a view object that displays a list of dictionary's (key, value) tuple pairs.

Syntax:
[Link]()

Example:
PyDict={ 'Apple': 5, 'Orange': 4, 'Grapes': 2 }
print([Link]())

Dictionary update()
It updates the dictionary with the elements from the another dictionary object or from an
iterable of key/value pairs.

Syntax:
[Link]([other])

Example:
d = {1: "one", 2: "three"}
d1 = {2: "two"}
[Link](d1)
print(d)

Example:
# Adding one element / multiple elements to a set
Super_Heroes = {"Superman", "Batman", "Spiderman"}
Super_Heroes.add("Aquaman") # adding one element to the set
print(Super_Heroes)
Super_Heroes.update(["Wolverine", "Green Arrow", "Flash", "Ironman"])
# adding multiple elements to the set
print(Super_Heroes)

Example:
PyDict1={'a':"BigData",'b':"Data Science",'c':"PTYHON"}
PyDict2={'d':"Machine Learning",'e':"Deep Learning",'f':"Artificial Intelligence"}
[Link](PyDict2)
print(PyDict1)# {'a': 'BigData', 'b': 'Data Science', 'c': 'PTYHON', 'd': 'Machine Learning', 'e':
'Deep Learning', 'f': 'Artificial Intelligence'}

Dictionary keys()
It returns a view object that displays a list of all the keys in the dictionary

Syntax:
[Link]()

Example:
person = {'name': 'NareshIT', 'age': 15, 'salary': '$35000.0'}
print([Link]())
empty_dict = {}
print(empty_dict.keys())
Example:
PyDict1={'a':"BigData",'b':"Data Science",'c':"PTYHON"}
PyDict2={'d':"Machine Learning",'e':"Deep Learning",'f':"Artificial Intelligence"}
print([Link]())#dict_keys(['a', 'b', 'c'])
print([Link]())#dict_keys(['d', 'e', 'f'])

Example:
person = {'name': 'NareshIT', 'age': 15, }
print('Before dictionary is updated')
keys = [Link]()
print(keys)
[Link]({'salary': '$350000'})
print('\nAfter dictionary is updated')
print(keys)

Dictionary values()
The values() method returns a view object that displays a list of all the values in the
dictionary.

Syntax:
[Link]()

Example:
books = { 'BigData': 5, 'Hadoop': 6, 'Data Science': 4 }
print([Link]())

Example:
books = { 'BigData': 5, 'Hadoop': 6, 'Data Science': 4 }
print([Link]())
print('Original items:', books)
del[books['BigData']]
print('Updated items:', books)
print([Link]())

Example:
PyDict1={'a':"BigData",'b':"Data Science",'c':"PTYHON"}
PyDict2={'d':"Machine Learning",'e':"Deep Learning",'f':"Artificial Intelligence"}
print([Link]())#dict_values(['BigData', 'Data Science', 'PTYHON'])
print([Link]())#dict_values(['Machine Learning', 'Deep Learning', 'Artificial
Intelligence'])

Dictionary pop()
It removes and returns an element from a dictionary having the given key.

Syntax
[Link](key)

pop() Parameters
key - key which is to be searched for removal
Example:
books = { 'BigData': 2, 'Hadoop': 3, 'Data Science': 4 }
element = [Link]('BigData')
print('The popped element is:', element)
print('The dictionary is:', books)

Example:
PyDict1={'a':"BigData",'b':"Data Science",'c':"PTYHON"}
PyDict2={'d':"Machine Learning",'e':"Deep Learning",'f':"Artificial Intelligence"}
print([Link]('a'))#BigData
print([Link]('f'))#Artificial Intelligence

Example:
books = { 'BigData': 2, 'Hadoop': 3, 'Data Science': 4 }
element = [Link]('Spark')
#Key Error

Python Frozenset
It is a new class that has the characteristics of a set, but its elements cannot be changed once
assigned. While tuples are immutable lists, frozensets are immutable sets. Frozensets can be
created using the function frozenset().

Syntax:
PyFSet=frozenset(iterable)

Example:
PyFSet1=frozenset([1,2,3,4,5])
print(type(PyFSet1))
print(PyFSet1)
PyFSet2=frozenset({2,3,4,5,6})
print(type(PyFSet2))
print(PyFSet2)
print([Link]())
print([Link]())
print([Link](PyFSet2))
print([Link](PyFSet2))
print([Link](PyFSet2))
print([Link](PyFSet2))
print([Link](PyFSet2))
print(PyFSet2.symmetric_difference(PyFSet1))
print([Link](PyFSet1))

frozensets have less methods than sets.


There are some operators similar to sets intersection(), union(), symmetric_difference(),
difference(), issubset(), isdisjoint(), issuperset()) and a copy() method.

Example:
a = frozenset([1, 2, 3])
b = frozenset([2, 3, 4])
print([Link](b))
print(a & b)
print([Link](b))
print(a.symmetric_difference(b))
print([Link](b))
print([Link](b))

Set Comprehension: Set comprehension is possible.


Example:
PySet={x*x for x in range(5)}
print (PySet)
PySet={2**x for x in range(2,10,2)}
print (PySet)

NOTE: Set Objects won't support indexing and slicing:

Dictionary pop()
It removes and returns an element from a dictionary having the given key.

Syntax
[Link](key)

pop() Parameters
key - key which is to be searched for removal

Example:
books = { 'BigData': 2, 'Hadoop': 3, 'Data Science': 4 }
element = [Link]('BigData')
print('The popped element is:', element)
print('The dictionary is:', books)

Example:
PyDict1={'a':"BigData",'b':"Data Science",'c':"PTYHON"}
PyDict2={'d':"Machine Learning",'e':"Deep Learning",'f':"Artificial Intelligence"}
print([Link]('a'))#BigData
print([Link]('f'))#Artificial Intelligence

Example:
books = { 'BigData': 2, 'Hadoop': 3, 'Data Science': 4 }
element = [Link]('Spark')
#Key Error

Dictionary popitem()
It returns and removes an arbitrary element (key, value) pair from the dictionary.

Syntax:
[Link]()
Example:
person = {'name': 'NareshIT', 'age': 15, 'salary': '$35000.0'}
result = [Link]()
print('person = ',person)
print('Return Value = ',result)

Example:
PyDict1={'a':"BigData",'b':"Data Science",'c':"PTYHON"}
PyDict2={'d':"Machine Learning",'e':"Deep Learning",'f':"Artificial Intelligence"}
print([Link]())#('c', 'PTYHON')
print([Link]())#('f','Artificial Intelligence')

Other Dictionary Operations (Dictionary Membership Test)


We can test if a key is in a dictionary or not using the keyword in. Notice that membership
test is for keys only, not for values.

Example:
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
print(1 in squares)
print(2 not in squares)
print(49 in squares)

Example:
PyDict1={'a':"BigData",'b':"Data Science",'c':"PTYHON"}
PyDict2={'d':"Machine Learning",'e':"Deep Learning",'f':"Artificial Intelligence"}
print('a' in PyDict1)#True
print('A' not in PyDict1)#True
print('F' in PyDict2)#False

Built-in Functions with Dictionary


Function Description
all() Return True if all keys of the dictionary are true (or if the dictionary is empty).
any() Return True if any key of the dictionary is true. If the dictionary is empty, return
False.
len() Return the length (the number of items) in the dictionary.
sorted() Return a new sorted list of keys in the dictionary.

len()
It returns the number of items (length) of an object.

Syntax:
len(s)

Example:
fruits = {"mango": 2, "orange": 6}
print("Length:", len(fruits))

Python sorted()
The sorted() method sorts the elements of a given iterable in a specific order - Ascending or
Descending.
Syntax
sorted(iterable[key, reverse])

Example:
pyDict = {'e': 1, 'a': 2, 'u': 3, 'o': 4, 'i': 5}
print(sorted(pyDict))
print(sorted(pyDict,reverse=True))

Example:
a = {"bb":"ggg", "aaaa":"d", "ff":"c"}
x = sorted(a,key=len)
print(x)
print(sorted([Link]()))
print(sorted([Link]()))
print(sorted([Link]()))
PyDict={3:'e',2:'a',1:'c',7:'b',5:'d'}
PyResult=sorted([Link](),key=lambda x:x[1])
print(PyResult)

setdefault() Method:
It returns the value of the item with the specified key.

Syntax:
[Link](keyname, value)

Parameters:
keyname Required. The keyname of the item you want to return the value from
value Optional. If the key exist, this parameter has no [Link] the key does not exist, this
value becomes the key's value Default value None.

Example:
PyCourses = {1: "PYTHON",2: "ML", 3: "DS" }
print(PyCourses)
PyResult= PyCourses .setdefault(1)
print(PyResult)
PyResult= PyCourses .setdefault(4)
print(PyResult)
print(PyCourses)
PyCourses[4]="DL"
print(PyCourses)

Example:
Cars = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = [Link]("color", "White")
print(x)
print(Cars)

Nested Dictionaries
A dictionary can contain dictionaries, this is called nested dictionaries.

Example:
PyDict={'Courses1':
{"PY":"PYTHON","ML":"MachineLearning"},
'Courses2':
{"CY":"CYTHON","DL":"DeepLearning"}
}
print(PyDict)

Example:
PyDict={'Courses1':
{"PY":"PYTHON","ML":"MachineLearning"},
'Courses2':
{"CY":"CYTHON","DL":"DeepLearning"}
}
print(PyDict)
print(PyDict['Courses1'])
print(PyDict['Courses1']['PY'])

Example:
x={1:"PY"}
y={2:"ML"}
z={3:"DS"}
MyCourses={'First':x,'Second':y,'Third':z}
print(MyCourses)
print(MyCourses['First'])

# How to merge two dictionaries


x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}
z = {**x, **y}
print(z)

Example:
PyDict1={'a':"BigData",'b':"Data Science",'c':"PTYHON"}
PyDict2={'a':"Machine Learning",'b':"Deep Learning",'c':"Artificial Intelligence"}
PyDict3={**PyDict1,**PyDict2}
print(PyDict3)#{'a': 'Machine Learning', 'b': 'Deep Learning', 'c': 'Artificial Intelligence'}

Dictionary Comprehension:
Comprehension concept applicable for dictionaries also.

Example:
squares={x:x*x for x in range(1,6)}
print(squares)#{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
doubles={x:2*x for x in range(1,6)}
print(doubles)#{1: 2, 2: 4, 3: 6, 4: 8, 5: 10}

Accessing elements in a dictionary


This_Dict = {
"Brand" : "Ford",
"Model" : "Mustang",
"Year" : 1964
}
print(This_Dict["Year"])

# Looping through a dictionary


# while looping through a dictionary, the return value are the keys of the dictionary, but there
are methods to return the values as well
This_Dict = {
"Brand" : "Ford",
"Model" : "Mustang",
"Year" : 1964
}

# Loop for printing keys


for x in This_Dict:
print(x)

# Loop for printing values


for x in This_Dict:
print(This_Dict[x])
for x in This_Dict.values():
print(x)

# Loop for printing for keys and values


for x, y in This_Dict.items():
print(x, y)
print(This_Dict.get("Brand"))

# Removing items from a dictionary


This_Dict = {
"Brand" : "Ford",
"Model" : "Mustang",
"Year" : 1964,
"Color" : "Red",
"Tyre" : "Tubeless"
}
This_Dict.pop("Model")
print(This_Dict)
This_Dict.popitem()
print(This_Dict)
del This_Dict["Brand"]
print(This_Dict)
WORKING WITH PYTHON FUNCTIONS:

Function means Code [Link] performs a specific task


OR
A function is a block of organized, reusable code. Functions provide better modularity (high
degree of code reusing)

Types of Functions
Basically functions are two types:

Built-in functions:
Functions that are built into Python like:
all(), any(), bin(), bool(), bytes(), callable(), chr(), print(), file(),len(), input()...etc.!

User-defined functions (Building our Own Functions)


Functions defined by the users themselves as per client or business requirements..!!

Simple rules to define a function in Python:


1 Function blocks begin with the keyword 'def', the function name & parentheses ( ).
2 Any input parameters or arguments should be placed within these parentheses.
3 The first statement of a function can be an optional statement, It is docstring.
4 The code block within every function starts with a colon (:) and is indented.
5 A return statement with no arguments is the same as return None.

SYNTAX:
def Function_Name( argument1, argument2,....,argumentN):
Statement1
Statement2
return [expression]

Example:
#Definition of the function
#Name of the function
def MyMsgs_Shows():#Indentation of the function (right)
#Body of the function
#Logical part of the function
#Called Part of the function
#Argument declaration section
print("Hey Welcome to Functions")
print('Good One')
#End of the function
#Always Optional
#It is the statement
return()
#Calling Part
#Passing Parameters
#Passed values are parameters
#Code recalling/Reusable
MyMsgs_Shows()
MyMsgs_Shows()

Example:
def MyMsgs_Shows():
print("Hey Welcome to Functions")
print('Good One')
return()
MyMsgs_Shows()

The Return statement in function


It is used to return a value from a function, return statement without an expression argument
returns none.

Syntax:
def function_name(argument1, argument2, ...) :
statement_1
statement_2
....
return expression
function_name(arg1, arg2)

Example:
def Sum( arg1, arg2 ):
total = arg1 + arg2
print("The Total is:",total)
return;
total = Sum(30,20);

Example:
def Tot_Sub(a,b):
Tot=a+b
Sub=a-b
return(Tot,Sub)
x,y=Tot_Sub(10,20)
print("The Sum is :",x)
print("The Subtraction is :",y)

Example:
def Input():
x=input("Enter Any Number: ")
y=input("Enter Any Number: ")
z=int(x)+int(y);
print(z)
return()
Input()

Various Forms of Function Arguments


You can call a function by using the following types of formal arguments:
1 Required Arguments or Positional Arguments
2 Keyword Arguments
3 Default Arguments
4 Variable-Length/Arbitary Arguments

Positional Arguments
Arguments passed should match the function parameter from left to right

Syntax:
def FunName(arg1,arg2):
SuiteOfTheFunction

Example:
def fun(a,b,c):
print(a,b,c)
fun(1,2,3)

Example:
def printMy( str ):
print(str)
return;
printMy()

NOTE:
TypeError: printMy() missing 1 required positional argument: 'str'

Keyword Arguments(Parameters)
We can call a function by specifying the keyword argument in the form argument name=
value

Syntax:
def FunctionName(arg1,arg2,arg3):
SuiteOfStatements

Example:
def fun(a,b,c):
print(a,b,c)
fun(c=3,b=2,a=1)

Example:
def printMy(str):
print(str)
return;
printMy(str = "RoboticProcessAutomation-RPA")

Example:
def printinfo( name, exp ):
print("Name: ", name)
print("Experience: ", exp)
return;
printinfo( exp='15+Yrs', name="KSRaju" )
Example:
def nsquare(x, y = 2):
return (x*x+y*y)
print("The square of the sum of 2 and 3 is : ", nsquare(2))
print("The square of the sum of 2 and 3 is : ", nsquare(2,4))

Default Argument Values


We can assign default value for arguments to receive if the call passes too few values
OR
A default value can be written in the format "argument1 = value", therefore we will have the
option to declare or not declare a value for those arguments.

Syntax:
def Default_Args(arg=value,arg=value):
Suite of Statements

Example:
def fun(a,b=2,c=3):
print(a,b,c)
fun(1)

Example:
def printinfo( name, exp = '15+' ):
print("Name: ", name)
print("Experience: ", exp)
return;
printinfo( exp=14, name="KSRaju" )
printinfo( name="NareshIT" )

Example:
def Scores(BigData,Hadoop=85,Spark=80):
print(BigData,Hadoop,Spark)
Scores(71,77)
Scores(65,Spark=74)
Scores(BigData=70,Hadoop=90,Spark=75)

Arbitrary Argument lists or Variable-length arguments


Add an arbitary argument in the function definition start the variable name with *

Syntax:
def functionname([formal_args,] *var_args_tuple ):
"doc_string"
function_suite
return [expression]

Example:
def fun(*arr):
for val in arr:
print(val)
fun(1,2,3,4)
Example:
def fun1(*var):
for x in var:
print(x)
fun( 70, 60, 50 )

Scope and Lifetime of variables


All variables in a program may not be accessible at all locations in that program. This
depends on where you have declared a variable.

Local Variables
1 The variables defined within the function has a local scope and hence they are called local
variables
2 Local scope means they can be accessed within the function only

Global variables
1 The variables defined outside the function has a global scope and hence they are called
global variables
2 Global scope means they can be accessed within the function as well as outside the
function
3 The value of a global variable can be used by referring the variable as global inside a
function

Example:
total = 0; #Global Variable
def sum( arg1, arg2 ):
total = arg1 + arg2; # Here total is local variable.
print("Inside the function local total : ", total)
return total;
sum( 10, 40 );
print("Outside the function global total : ", total)

Example:
x=40#Global Scope
print(id(x))
def Scope_Variables1():
x=200#Local Scope
print(id(x))
print(x+x)#Local+Local
return
Scope_Variables1()
def Scope_Variables2():
z=600#Local SCope
print(id(z))
print(x+z)#Global+Local
return
Scope_Variables2()
global
It is used to declare that a variable inside the function is global (outside the function). If we
need to read the value of a global variable, it is not necessary to define it as global. If we need
to modify the value of a global variable inside a function, then we must declare it with global.

Example:
x=100
def MyFun():
global x
x=5
y=20
print(x+y)
def MyFun1():
y=10
print(x+y)
MyFun()
MyFun1()

Example:Output of the following Script..!!


x=1
def Compute():
global x
for i in (1,2,3):
x+=1
Compute()
print(x)

Example: Output of the following Script..!!


def f():pass
print(type(f()))

Function Aliasing:
For the existing function we can give other name, which is nothing but function aliasing.

Example:
def Hello_World(name):
print("Great:",name)
MyWorld=Hello_World
Hello_World('Machine Learning')
MyWorld("PYTHON")
print(id(MyWorld))
print(id(Hello_World))

NOTE:
If we delete one name still we can access that function by using Alias Name

Example:
def Hello_World(name):
print("Good Morning:",name)
MyWorld=Hello_World
Hello_World('Machine Learning')
del Hello_World
MyWorld("PYTHON")

NOTE:
Fun_One = Outer _Fun ==> It is Function Aliasing.
Fun_One = Outer_Fun() ==> It is calling Outer_Fun() Function

Function is an object:
In Python every thing is an object. Functions are also objects.

Example:
def MyFun():
print("Say Hey PYTHON")
print(MyFun)
print(id(MyFun))

Nested Functions or Inner Functions:


Functions can be defined within the scope of another function.

Example:
def Outer(): #outer function
print ("Hello Welcome TO")
def Inner(): #inner function
print ("Nested Functions")
Inner()
Outer()

Example:
def Outer_Fun():
print("Say Hey Outer Function")
def Inner_Fun():
print("Bye Hey Inner Function")
print("OuterOneCallingInnerFunction")
Inner_Fun()
Outer_Fun()

Example:
def Outer_Fun():
print("Hey Outer")
def inner():
print("Bye Inner")
print("Outer Returns Inner")
return inner
Outer_Fun()

Example:
def Outer_Fun():
print("Hey Outer")
def inner():
print("Bye Inner")
print("Outer Returns Inner")
return inner
Inn=Outer_Fun()
Inn()

Example:
def Outer(): #outer function
x = 1 #variable defined in Outer function
def Inner(a): #inner function
print (a+x) #able to acces the variable of outer function
Inner(2)
Outer()

Example:
def Outer(): #outer function
x = 1 # variable defined in the outer function
def Inner(a): #inner function
#will create a new variable in the inner function
#instead of changing the value of x of outer function
x=4
print (a+x)
print (x) # prints the value of x of outer function
Inner(2)
Outer()

nonlocal
It is used to declare that a variable inside a nested function is not local to it. If we need to
modify the value of a non-local variable inside a nested function, then we must declare it with
nonlocal.

Example:
def Outer_Function():
a=5
def Inner_Function():
nonlocal a
a = 10
print("Inner Function: ",a)
Inner_Function()
print("Outer Function: ",a)
Outer_Function()

Example:
def Outer_Function():
a=5
def Inner_Function():
a = 10
print("Inner Function: ",a)
Inner_Function()
print("Outer Function: ",a)
Outer_Function()

PYTHON Recursive Functions:


A function calls itself one or more times in its body.
OR
If a function calls itself is called as recursive function

Example:
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
print(factorial(5))

Example:
def counter(c):
if c<=0:
return c
else:
return c + counter(c-1)
print(counter(5))

Example:Output of the following Script


def MyFunc(*args):
for i in args:
print(i*2,end=" ")
input_num=[1,2,3,4,5]
MyFunc(*input_num)

Example:Output of the following Script


def MyFunc(*args):
PyList=[]
for i in args:
[Link](i*2)
return PyList
input_num=[1,2,3,4,5]
print(MyFunc(*input_num))

Example:
# Sorting the elements of the list using a certain function
def func(x):
return len(x)
Cars = ["Ford", "BMW", "Ferari", "Mitsubishi", "Audi"]
[Link](reverse = True, key = func)
print(Cars)
# prints the elements of the list in the descreasing order of character length
Anonymous Functions (Not identified by name or Unknown name)
It has the following alias Names:
1 Lambda functions
2 Lambda Forms
3 One Line function
4 Implict functions
5 Simple functions
6 Throw-away functions
7 Short period functions
.................................!!
It is a function that is defined without a name. No def and return keywords..!!

Syntax
lambda [arg1 [,arg2,.....argn]]:expression

Example:
n=lambda x:2*x
n ==> It is a variable or identifier
lambda ==> It is a keyword
x ==> Argument
: ==> Delimiter
2*x ==> It is an Expression

Example:
def add(x,y):
return(x+y)
add(1,2)

Example:
add=lambda x,y:x+y
add(4,3)

Example:
print((lambda x,y:x+y)(2,3))

Example
g=lambda x:x*x
print(g(5))

Example:
def average(x, y):
return (x + y)/2
print(average(4, 3))

Example:
print((lambda x, y: (x + y)/2)(4, 3))

Example:
def max(x,y):
if x>y:
return x
else:
return y
print(max(15,6))

Example:
max=lambda x,y: x if x>y else y
print(max(5,6))

Example:
print((lambda x,y: x if x>y else y)(2,3))

Example:
max=lambda x,y: x if x<y else y
print(max(5,6))

Lambda functions:
These are as follows:
1 map() 2 filter() 3 reduce()

We can pass function as argument to another function

Example:
map(function,sequence)
filter(function,sequence)
reduce(function,sequence)

map() function
Apply same function to each element of a sequence and return the modified list.

Syntax:
list=[m,n,p]
function(),f ==> MAP ==> New list,[f(m),f(n),f(p)]

Example:
n=[4,3,2,1]
print(list(map(lambda x:x**2,n)))

Example:
my_list = [1, 5, 4, 6, 8]
new_list = list(map(lambda x: x * 2 , my_list))
print(new_list)

Example:
num=[1.1,2.3,4.5]
Result=list(map(lambda x :int(x),num))
print(Result)

Example: WithOut Lambda:


PyTuple=(1,2,3,4,5)
def Compute(x):
return x**2
PyTuple1=tuple(map(Compute,PyTuple))
print(PyTuple1)

filter() function: filter items out of a sequence, return filtered list

Syntax:
list,[m,n,p]
condition,c() ==> filter ==> New list [m,n]
if(m==condition)

Example:
n=[4,3,2,1]
print(list(filter(lambda x:x>2,n)))

Example:
my_list = [1, 2, 3, 5, 6, 8,10, 12,15]
Even_list = list(filter(lambda x: (x%2 == 0),my_list))
print(Even_list)
Odd_list = list(filter(lambda x: (x%2 != 0),my_list))
print(Odd_list)

Example: WithOut Lambda


def Even_Number(x):
if x%2!=0:
return True
else:
return False
PyList=[1,2,3,4,5,6,7,8,9,10]
PyList1=list(filter(Even_Number,PyList))
print(PyList1)

reduce() function:
1. Applies same operation to items of a sequence
2. Uses result of operation as first param of next operation
3. Returns an item, not a list, This function is defined in “functools” module.

Syntax:
list,[m,n,p]
function f() ==> reduce() ==> f(f(m,n),p)

Example:
import functools
n=[4,3,2,1]
print([Link](lambda x,y:x*y,n))

Example:
import functools
print([Link](lambda x,y:x+y,[1,2,3,4]))
result=sum([x for x in [1,2,3,4]])
print(result)

Python *args and **kwargs


In programming, we define a function to make a reusable code that performs similar
operation. To perform that operation, we call a function with the specific value, this value is
called a function argument in Python.

Example: Function to Sum of 2 numbers


def Add(x,y):
print("Addition is: ",x+y)
return()
Add(10,12)

Output: Addition is: 22

NOTE:
Lets see what happens when we pass more than 3 arguments in the Add() function.
TypeError: adder() takes 2 positional arguments but 3 were given

Introduction to *args and **kwargs in Python


In Python, we can pass a variable number of arguments to a function using special symbols.
There are two special symbols:
1. *args (Non Keyword Arguments)
2. **kwargs (Keyword Arguments)

We use *args and **kwargs as an argument when we are unsure about the number of
arguments to pass in the functions.

Python *args
As in the above example we are not sure about the number of arguments that can be passed to
a function. Python has *args which allow us to pass the variable number of non keyword
arguments to function. In the function, we should use an asterisk * before the parameter name
to pass variable length arguments.

Example:
def Add(*num):
Sum = 0
for n in num:
Sum=Sum+n
print("Sum is:",Sum)
Add(3,5)
Add(4,5,6,7)
Add(1,2,3,5,6)

Understanding **kwargs
The double asterisk form of **kwargs is used to pass a keyworded, variable-length argument
dictionary to a function. Again, the two asterisks (**) are the important element here, as the
word kwargs is conventionally used, though not enforced by the language.
Example:
def print_kwargs(**kwargs):
print(kwargs)
print_kwargs(kwargs1="KORA", kwargs2="Subba Raju")
print_kwargs(kwargs1="KORA", kwargs2="Subba Raju",kwargs3="20-Years")

Example:
def print_values(**kwargs):
for key, value in [Link]():
print("The value of {} is {}".format(key, value))
print_values(MyName="Raju", YourName="Ravi")

Example:
def print_values(**kwargs):
for key, value in [Link]():
print("The value of {} is {}".format(key, value))
print_values(
Name1="Alex",
Name2="Gray",
Name3="Harper",
Name4="Raju",
Name5="SARA",
Name6="SCOTT"
)

PYTHON ITERATORS
An iterator is an object that contains a countable number of values. In Python, which
implements the iterator protocol, which consist of the methods __iter__() and __next__().

Iterator vs Iterable
Lists, tuples, dictionaries, and sets are all iterable objects. They are iterable containers which
you can get an iterator from. All these objects have a iter() method which is used to get an
iterator.

Example:
for x in range(5):
print(x)

Looping Through an Iterator


We can also use a for loop to iterate through an iterable object:

Example:
PyTuple = ("Apple", "Banana", "Cherry")
for item in PyTuple:
print(item)

Example:
PyList=[1,2,3,4]
x=iter(PyList)
print(x)#just it retruns object memory location
print(next(x))

Example:
PyList=[1,2,3,4]
x=PyList.__iter__()
print(x)#just it retruns object memory location
print(x.__next__())
print(x.__next__())

Example:
PyTuple = ("Apple", "Banana", "Cherry")
PyIt = iter(PyTuple)
print(next(PyIt))
print(next(PyIt))
print(next(PyIt))

Strings are also iterable objects, containing a sequence of characters


Example:
Pystr="Banana"
PyIt= iter(Pystr)
print(next(PyIt))
print(next(PyIt))
print(next(PyIt))
print(next(PyIt))
print(next(PyIt))

Create an Iterator
The __iter__() method must always return the iterator object itself.
The __next__() method also allows you to do operations, must return the next item in the
sequence.

Example:
class MyNumbers:
def __iter__(self):
self.a = 1
return self

def __next__(self):
x = self.a
self.a += 1
return x

myclass = MyNumbers()
myiter = iter(myclass)
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
StopIteration
The example above would continue forever if you had enough next() statements, or if it was
used in a for loop. To prevent the iteration to go on forever, we can use the StopIteration
statement.

In the __next__() method, we can add a terminating condition to raise an error if the iteration
is done a specified number of times:

Example:
class MyNumbers:
def __iter__(self):
self.a = 1
return self

def __next__(self):
if self.a <= 10:
x = self.a
self.a += 1
return x
else:
raise StopIteration

myclass = MyNumbers()
myiter = iter(myclass)
for x in myiter:
print(x)

Implementing Own Iterator Class:


Implementing Remote Control class that allows you to press next button to go to next
channel.

Example:
class RemoteControl():
def __init__(self):
[Link]=['HBO','CNN','STAR','ABC','ESPN']
[Link]=-1
def __iter__(self):
return self
def __next__(self):
[Link]+=1
if [Link]==len([Link]):
raise StopIteration
return [Link][[Link]]
r=RemoteControl()
itr=iter(r)
print(next(itr))
print(next(itr))
print(next(itr))
print(next(itr))
print(next(itr))

PYTHON GENERATORS
Python provides a generator to create your own iterator function. A generator is a special type
of function which does not return a single value, instead, it returns an iterator object with a
sequence of values. In a generator function, a yield statement is used rather than a return
statement.

Differences between Generator function and a Normal function


1. Generator function contains one or more yield statement.
[Link] with class level iterators, generators are very easy to use
[Link] memory utilization and performance.
[Link] are best suitable for reading data from large number of large files
[Link] work great for web scraping and crawling.

Yield vs. Return


The Yield statement is responsible for controlling the flow of the generator function.
The Return statement returns a value and terminates the whole function.

Example:
def MultipleYield():
str1 = "First String"
yield str1
str2 = "Second string"
yield str2
str3 = "Third String"
yield str3
Obj= MultipleYield()
print(next(Obj))
print(next(Obj))
print(next(Obj))

Example:
def MultipleYield():
str1 = "First String"
return str1
str2 = "Second string"
yield str2
str3 = "Third String"
yield str3
Obj= MultipleYield()
print(next(Obj))
print(next(Obj))
print(next(Obj))

Example:
def Cube():
n=1
while n<=10:
result=n**3
n+=1
return(result)
x=Cube()
print(x)

Example:
def Cube():
n=1
while n<=10:
result=n**3
n+=1
yield result
x=Cube()
for i in x:
print(i)

Example: Generating Genetrator Object


def Remote_Control():
yield "CNN"
yield "ABC"
yield "ESPN"
itr=Remote_Control()
print(itr) #<generator object Remote_Control at 0x000000F7D12EFC50>

Example:Generator as Interator
def Remote_Control():
yield "CNN"
yield "ABC"
yield "ESPN"
itr=Remote_Control()
print(next(itr))
print(next(itr))
print(next(itr))

Example:
def table(n):
for i in range(1,11):
yield n*i
i = i+1
for i in table(15):
print(i)

Example:
def table(n):
for i in range(1,11):
return n*i
i = i+1
print(table(5))

Example:
def NumGen(n):
x=1
while x<=n:
yield x
x=x+2
Nums=NumGen(4)
for i in Nums:
print(i)

Example:
def FebGen():
x,y=0,1
while True:
yield x
x,y=y,x+y
for i in FebGen():
if i<100:
print(i)
else:
break

Example:
from random import *
def NumGen():
Nums="0123456789"
while True:
patt=''
for i in range(4):
patt+=choice(Nums)
yield patt
for i in NumGen():
print(i)

List Comprehension vs Generators Expression in Python


List Comprehension
It is one of the best ways of creating the list in one line of Python code. It is used to save a lot
of time in creating the list.
Example:
print([j**2 for j in range(1,11)])

Generator Expression
It is one of the best ways to use less memory for solving the same problem that takes more
memory in the list compression.
Example:
PyGe=(j**2 for j in range(1,11))
for j in PyGe:
print(j, end=' ')

Example:
def infinite_sequence():
num = 0
while True:
yield num
num += 1
for i in infinite_sequence():
print(i)

Example:
def infinite_sequence():
num = 0
while True:
return num
num += 1
print(infinite_sequence())

PYTHON CLOSURES:
A Closure is a function object that remembers values in enclosing scopes even if they are not
present in memory.

Example:
def OuterFun():
x=10
def InnerFun():
print(x)
InnerFun()
OuterFun()

Example:
def OuterFun():
x=10
def InnerFun():
print(x)
InnerFun()
OuterFun()

Example:
def OuterFun():
x=10
def InnerFun():
print(x)
return InnerFun()

OO=OuterFun()
print(OO)

Example:
def OuterFun():
x=10
def InnerFun():
y=20
Total=x+y
return Total
return InnerFun()#Executing function definition

OO=OuterFun()
print(OO)

Example:
def OuterFun():
x=10
def InnerFun():
y=20
Total=x+y
return Total
return InnerFun #Returing function reference

OO=OuterFun()
print(OO)

Example:
def OuterFun():
x=10
def InnerFun():
y=20
Total=x+y
return Total
return InnerFun #Returing function reference

OO=OuterFun()
print(OO.__name__)

Example:
def OuterFun():
x=10
def InnerFun():
y=20
Total=x+y
return Total
return InnerFun #Returing function reference

OO=OuterFun()
print(OO())

NOTE:
We executed inner function body outside its scope, this technique is called Closure.

Example:
def Outer_Func():
Msg="PYTHON"
def Inner_Func():
print(Msg)
return Inner_Func
My_Func=Outer_Func()
My_Func()

Example:
def Outer_Func(msg):
message=msg
def Inner_Func():
print(message)
return Inner_Func
hi_func=Outer_Func("Hi")
hello_func=Outer_Func("Hello")
hi_func()
hello_func()

When we create closures:


1. Nested Functions
2. Nested Function must refer values in enclosing scope
3. Enclosing function must return nested function

Why to use Closures?


1 We can avoid gloable values
2 They provide some sort of data hiding.
3 This helps us to reduce the use of global variables.
4. We can implement in Decorators

PYTHON DECORATORS:
Decorator is a function that takes another function and extends the behavior of the latter
function without explicitly modifying it.
OR
Decorator is a function that can add additional functionality to an existing function.!

OUTLINE:
INPUT FUNCTION ==> DECORATOR FUNCTION ==> OUTPUT FUNCTION with
Extended Functionality

Example:
def NorFun():
print("Feature-1")
NorFun()

Example:
def DecFun(func):
def Addon():
func()
print("Feature-2")
print("Feature-3")
return Addon

def NorFun():
print("Feature-1")
NorFun=DecFun(NorFun) #=> Best for Debug
NorFun()

Example:
def DecFun(func):
def Addon():
func()
print("Feature-2")
print("Feature-3")
return Addon

@DecFun
def NorFun():
print("Feature-1")
NorFun() #=> Best for Debug

Example:
def NormalFun():
print("Feature-1")
NormalFun()

Example:
def AddFun(func):
def Inner():
func()
print("Feature-2")
return Inner

def NormalFun():
print("Feature-1")

NormalFun=AddFun(NormalFun)#=> Best for Debug


NormalFun()

Example:
def AddFun(func):
def Inner():
func()
print("Feature-2")
return Inner

@AddFun#Decorator
def NormalFun():
print("Feature-1")
NormalFun()#=> Best for Debug
Example:
def MyDecor(func):
def MyInner():
print("Added New Functionality")
return MyInner

@MyDecor
def MyOrginal():
print("My Original Function")

MyOrginal()

Example:
def MyDecor(func):
def MyInner():
print("Added New Functionality")
func()
return MyInner

@MyDecor
def MyOrginal():
print("My Original Function")
MyOrginal()

Example:
def Success(func):
def Study():
print("Prepare Well")
func()
print("Congratulations..!!")
return Study

@Success
def MyFun():
print("Say Hey You are PASS")
MyFun()

Example:
def Div(x,y):
return x/y
print(Div(2,1))
print(Div(2,2))

Example:
def Div(x,y):
return x/y
print(Div(2,1))
print(Div(2,0))#ZeroDivisionError

Example: with Decorator


def DivUpdate(func):
def Inner(a,b):
if b==0:
print("SorryUnableToCompute")
else:
return func(a,b)
return Inner

@DivUpdate #Callable
def Div(a,b):
return a/b
print(Div(2,1))##=> Best for Debug
Div(2,0)
print(Div(2,2))

DivUpdate is a decorator, decorator function added some new functionality to the original
function We can use the @ symbol along with the name of the decorator function and place it
above the definition of the function to be decorated.

Using Multiple Decorators:


def MyDecor_Two(func):
def MyInner_Two():
func()
print("New Functionality for Decorator Two")
return MyInner_Two

def MyDecor_One(func):
def MyInner_One():
func()
print("New Functionality for Decorator One")
return MyInner_One

@MyDecor_Two
@MyDecor_One
def MyOrginal():
print("My Original Function")
MyOrginal()

What is a Python namespace?


A namespace is a system that has a unique name for each and every object in Python. An
object might be a variable or a method. Python itself maintains a namespace in the form of a
Python dictionary. Its Name (which means name, a unique identifier) + Space(which talks
something related to scope).

Namespace & Variable Scope:


Names or Identifiers, To identify an object.
Example:
Variable Name
Function Name
Class Name
Method Name...!!

Namepsace is a system which control all the names which we use in our program. It allows us
to reuse names in our program.

>>> x=4
x is a varible, 4 is the value
>>> x
>>> x=5
x is a varible, 5 is the value
>>> x
>>> x=4
>>> y=5
>>> x
>>> y

If we are writing small coding no issue we can maintain that uniqueness of variables use. In
real time industry multiple programmers are developing code, there is a chance variable
[Link] that case namespace playing major rule.

Example:[Link]
def HelloFun():
print("Welcome to Namespace Classes-1")

Example:[Link]
def HelloFun():
print("Welcome to Namespace Classes-2")

Example:[Link]
import FirstModule
import SecondModule
[Link]()
[Link]()

NOTE:
In the above script function names are same but we can access using module names, this is
exactly the use of namespace.

>>> dir()
>>> x=100
>>> dir()

There are 4 namespaces in Python ie LEGB Rule:


1 Local Scope
2. Enclosed Scope (Closures)
3 Global Scope
4. Builtin

[Link] Scope: We can access variables only within the function.


Example:
def InnerFunction():
x=100
print("X value is: ",x)
InnerFunction()
print("X value is: ",x)#NameError: name 'x' is not defined, OutOfScope

Example:
def Scope_Variables():
x=200#Local Scope
print(x+x)#Local+Local
return
Scope_Variables()

[Link] Scope: We can access variables within the function & Out of the function
Example:
Example:
y=200
def InnerFunction():
x=100
print("X value is: ",x)
print("Y value is: ",y)
InnerFunction()
print("Y value is: ",y)

Example:
x=40#Global Scope
def Scope_Variables1():
x=200#Local Scope
print(x+x)#Local+Local
return
Scope_Variables1()
def Scope_Variables2():
z=600#Local SCope
print(x+z)#Global+Local
return
Scope_Variables2()

Modifying the global variable in local scope


Example:
y=200
def InnerFunction():
x=100
y=y+1
print("Inside X value is: ",x)
print("Inside Y value is: ",y)
InnerFunction()
print("OutSide Y value is: ",y)

NOTE:
UnboundLocalError: local variable 'y' referenced before assignment
Example:
To modify global variable inside the local scope we need to use 'global' keyword.
y=200
def InnerFunction():
x=100
global y
y=y+1
print("Inside X value is: ",x)
print("Inside Y value is: ",y)
InnerFunction()
print("OutSide Y value is: ",y)

3 Enclosing Scope:
Contains Names defined inside any and all enclosed functions.

Example:
y=20 #Global Scope
def OuterFunction():#Enclosed Function
#Enclosed Scope
#We can't access z outside the OuterFunction
z=10
def InnerFunction():#Inner/Nested Function
#Local Scope
x=5
print("X Value is: ",x)
print("Inside Y value is: ",y)
InnerFunction()
print("Z Value is: ",z)
OuterFunction()

Example:
y=20
def OuterFunction():
z=100
def InnerFunction():
x=5
z=z+2
print("X Value is: ",x)
print("Inside Z value is: ",z)
InnerFunction()
print("Z Value is: ",z)
OuterFunction()

NOTE:
UnboundLocalError: local variable 'z' referenced before assignment

Example:
To modify the enclosed variable in the local scope we need to use nonlocal keyword
y=20 #Globa;
def OuterFunction():
z=100#Enclosed
def InnerFunction():
x=5#Local
nonlocal z
z=z+2
print("X Value is: ",x)
print("Inside Z value is: ",z)
InnerFunction()
print("Z Value is: ",z)
OuterFunction()

4. Builtin Scope:Contains names built-in to the Python language. All these are already
defined.
Example:
print("Welcome to Builting")
print(*range(2,10))

WORKING WITH PYTHON MODULES (MODULARITY)


Module is anyone which ends with .py Extension.
OR
A module is a file consisting of Python code. A module can contains functions, classes and
variables.

Advantages of Python Modules.


1 Each and every module is independent unless linked explicitly. So, any changes made in
one module will not affect another module.
2 Modules provide the reusability of code. So, a single module can be reused in another
application (if required) or stored for later purposes.

Creating a Module:
Example:[Link]
def MyFun1():
print("Welcome to Python & Advance")
print("Modular Programming")
return()
def MyFun2():
print("It is Perfect Feature")
print("Thank U ")
return()

How To Use Modules in Python?


The import Keyword
You can use any Python source file as a module by executing an import statement in some
other Python source file.

Syntax:
import module1[, module2[,... moduleN]
Example:[Link]
import MyMod
MyMod.MyFun1()
MyMod.MyFun2()
print("END")

Import with renaming OR module aliasing


We can import a module by renaming it.

Syntax:
import ModName as NewModName

Example:[Link]
def add(a,b):
return a+b
def sub(a,b):
return a-b
def prod(a,b):
return a*b

Example:[Link]
import modulethree as mt
Sum=[Link](10,20)
print("Sum of the numbers is: " ,Sum)
dif=[Link](20,10)
print("Difference of the numbers is: " ,dif)
prd=[Link](10,10)
print("Difference of the numbers is: " ,prd)

The from...import Statement


Python's from statement lets you import specific attributes from a module into the current
namespace.

Syntax:
from modname import name1[, name2[, ... nameN]]

Example:[Link]
a="BigData"
b="Hadoop"
c="Spark"
d="Data Science"
print(a,b,c,d)
print(a,d)

# Grab the whole module:


>>>import mfive (Everything Imported to RAM)

# Access its attributes


>>>mfive.a, mfive.c
('Big Data','Spark')

# Copy multiple names out


from mfive import a, b, c
print(b, c)

Using wildcard imports (from Ö import *)


It is also possible to import all properties from a module into the current namespace.

Syntax:
from modname import *

Example:
def Add1(a,b):
return(a+b)
def Sub1(a,b):
return(a-b)
def Pro1(a,b):
return(a*b)
def Div1(a,b):
return(a/b)
def FDiv1(a,b):
return(a//b)

Example:
from MyProg1 import *
print(Add1(1,2))
print(Sub1(1,2))
print(Pro1(20,2))

Python Builtin Modules:


Python has a large number of built-in modules. These modules can be used in Python
programs by simply importing them using their name followed by the keyword 'import'

Module Description
math Math module is used to perform mathematical operations.
random This module is used to generate random numbers.
Operator This module provides a set of pre-defined functions
decimal This module is used to print the complete decimal value
string string module provides a set of functions & operations on characters.

Math Module in PYTHON:


Python Number abs() Function:
It returns absolute value of x - the (positive) distance between x and zero.

Syntax
abs( x )

Example:
print(abs(-45))
print(abs(100.12))

ceil() Method:
It returns ceiling value of x, always returns forward round value.

Syntax
[Link]( x )

EXAMPLE:
import math
print([Link](-45.17))
print ([Link](100.12))
print ([Link](100.72))

Python Number floor() Method


It returns floor of x ,always returns backward round value.

Syntax
[Link]( x )

Example:
import math
print([Link](-45.17))
print([Link](100.12))
print([Link](100.72))

[Link](x)
Return the absolute value of x.

Syntax:
[Link](x)

Example:
import math
print([Link](-10.99))
print([Link](10.99))
print([Link](-100.01))

[Link](x)
Return x factorial. Raises ValueError if x is not integral or is negative.

Syntax:
[Link](x)

Example:
import math
print([Link](5))

[Link](iterable)
Return an accurate floating point sum of values in the iterable.
Syntax:
[Link]()

Example:
import math
print([Link]([5,7,2,4]))
print([Link]({5,7,2,4}))
print([Link]((5,7,2,4)))

pow() Method: This method returns value of x to the power of y.

Syntax:
[Link](x,y)

Example:
import math
print([Link](100, 2))
print([Link](2, 4))
print([Link](3, 0))

Python Number round() Function


It returns x rounded to n digits from the decimal point.

Syntax
round( x [, n] )

Example:
print(round(10.234,2))#10.23
print(round(10.236,2))#10.24
print(round(10.236,3))#10.236
print(round(10.990,1))#11.0
print(round(80.23456, 2))
print(round(100.5623, 3))

sqrt() Method
It returns the square root of x for x > 0.

Syntax
[Link]( x )

Example:
import math
print([Link](100))
print([Link](7))

Random Module in PYTHON


The [Link]() method returns a random float in the interval [0.0, 1.0). This means the
returned random number will always be smaller than the right-hand endpoint (1.0). This is
also known as a semi-open range.
Syntax:
[Link]()

Example:
import random
print([Link]())
print([Link]())

Generating Random Ints Between x and y


This is how you can generate a random integer between two endpoints in Python with the
[Link]() function. This spans the full [x, y] interval and may include both endpoints:

Syntax:
[Link](x,y)

Example:
import random
print([Link](1,10))
print([Link](1,10))

randrange():
This method you can exclude the right-hand side of the interval, meaning the generated
number always lies within [x, y) and it will always be smaller than the right endpoint:

Syntax:
[Link](x,y)

Example:
import random
print([Link](1,10))
print([Link](1,10))

Generating Random Floats Between x and y


If you need to generate random float numbers that lie within a specifc [x, y] interval you can
use the [Link] function:

Syntax:
[Link](x,y)

Example:
import random
print([Link](1,20))
print([Link](1,20))

Picking a Random Element From a List


To pick a random element from a non-empty sequence (like a list or a tuple) you can use
Pythonís [Link] method.

Syntax:
[Link](seq)

Example:
import random
x=[1,2,3,4,5]
print([Link](x))#1
print([Link](x))#3
print([Link](x))#5

Example:
import random
items=[1,2,3,4,5,6,7]
print([Link](items))
print([Link](items))
print([Link](items))

Randomizing a List of Elements


You can randomize a sequence in place using the [Link] function. This will modify
the sequence object and randomize the order of elements:

Syntax:
[Link](x)

Example:
import random
items=[1,2,3,4,5,6,7]
print(items)
[Link](items)
print(items)

Picking n Random Samples From a List of Elements


To pick a random sample of n unique elements from a sequence, use the [Link]
function. It performs random sampling without replacement:

Syntax:
[Link](population,k)

Example:
import random
items=[1,2,3,4,5,6,7]
print(items)
print([Link](items,3))
print([Link](items,3))
print([Link](items,3))

Operator Module in PYTHON


This module exports a set of efficient functions corresponding to the intrinsic operators of
Python. For example, [Link](x, y) is equivalent to the expression x+y.

Operation Syntax Function


Addition a+b add(a, b)
Concatenation seq1 + seq2 concat(seq1, seq2)
Containment Test obj in seq contains(seq, obj)
Division a/b truediv(a, b)
Division a // b floordiv(a, b)
Bitwise And a&b and_(a, b)
Bitwise Exclusive Or a ^ b xor(a, b)
Bitwise Inversion ~ a invert(a)
Bitwise Or a|b or_(a, b)
Exponentiation a ** b pow(a, b)
Identity a is b is_(a, b)
Identity a is not b is_not(a, b)

Example:
import operator
a=int(input("Enter Any Valid Number: "))
b=int(input("Enter Any Valid Number: "))
print([Link](a, b))
print([Link](a, b))
print([Link](a, b))
print([Link](a, b))
print([Link](a, b))
print([Link](a, b))

Example
a=int(input("Enter Any Valid Number: "))
b=int(input("Enter Any Valid Number: "))
print(operator.__lt__(a, b))
print(operator.__le__(a, b))
print(operator.__eq__(a, b))
print(operator.__ne__(a, b))
print(operator.__ge__(a, b))
print(operator.__gt__(a, b))

Decimal Module in PYTHON:


This decimal module provides support for fast correctly-rounded decimal floating point
arithmetic. It offers several advantages over the float datatype.

Example:
from decimal import Decimal
x=1/3
print(type(x))
print(x)
y = Decimal(1) / Decimal(3)
print(type(y))
print(y)

Python compare floating point values:


Caution should be exercised when comparing floaing point values. While in many real world
problems a small error is negligible, financial and monetary calculations must be exact.
Example:
from decimal import Decimal
x = 0.1 + 0.1 + 0.1
print(x == 0.3)
print(x)

print("----------------------")
x = Decimal('0.1') + Decimal('0.1') + Decimal('0.1')
print(x == Decimal('0.3'))
print(float(x) == 0.3)
print(x)

Sting module in PYTHON:


Python String module contains some constants, utility function, and classes for string
manipulation

Example:
import string
print(string.ascii_letters)
print(string.ascii_lowercase)
print(string.ascii_uppercase)
print([Link])
print([Link])
print([Link])

Working with Packages in Python


It is collection of modules.
OR
Any folder or directory which contains __init__.py file , then we call that folder or directory
as a Python Package

PIC: PackageModuleStructure:

Importing module from a package:


We can import modules from packages using the dot (.) operator. For example, if want to
import the start module from above Structure:

Syntax:
import [Link]

Creating a pakage(As per Live Project)


1 Goto PYTHON Installed location.
>>> import os
>>> [Link]()
C:\\Users\\admin\\AppData\\Local\\Programs\\Python\\Python38-32
2 Create a Directory/Folder and Provide any name (MyPackage)
3 Open Notepad save with, __init__ .py file in the directory (PYTHON recognize a Package)
4. Create a python file in that Package ([Link])
Example:
def MyFun():
print("Welcome to Packages")
print("Packages Are Dirs/Folders")
return
MyFun()
Save with [Link] Extension..!!

Executing a Module from a Package:


>>> import [Link]
>>> [Link]()
>>> import [Link] as nit
>>> [Link]()
>>> from [Link] import MyFun
>>> MyFun()

Creating SubPackage:
1. Create a Folder/Directory inside existing package and Provide A name (SubPackage)
2. Create __init__ .py file in the directory (PYTHON recognize as Package)
3. Create a python file in that ([Link])

Executing a Module from a Sub-Package:


>>> import [Link]
>>> [Link]()
>>> import [Link] as nit
>>> [Link]()
>>> from [Link] import MyFun
>> MyFun()

Popular Python Packages:


1. Requests
2. wxPython
3. BeautifulSoup
4. Twisted
5. boto3 for AWS
6. Python Imaging Library (PIL)
7. MoviePy
8. Pywin32
9. Pytest
10. Pendulum for Date&Time

eval()
eval Function take a String and evaluate the Result.

Syntax:
eval(expression)

Parameters
expression - this string as parsed and evaluated as a Python expression
Example:
x=eval("18-90+87")
print(x)

Example:
x=eval(input("Enter Expression: "))
print(x)

Example:
PyData=eval(input("Enter Data: "))
print(type(PyData))
print(PyData)

Python Date & Time Modules:


In Python, date, time and datetime classes provides a number of functions to deal with dates,
times and time intervals.

Epoch
The Epoch is the point in time in Python from which time is measured. It is labelled
12:00AM, Jan 1, 1970. It is the beginning of an era.

The datetime classes in Python are categorized into main 5 classes.


date ==> Month, Day, Year
time ==> Hour, Minute, Second, Microsecond
datetime ==> Combination of Time & Date
timedelta==> A duration of time used for manipulating dates
tzinfo==> An abstract class for dealing with time zones

What is Tick?
The floating-point numbers in units of seconds for time interval are indicated by Tick in
python.

Example
import time
ticks = [Link]()
print("Number of ticks since 12:00am, January 1, 1970:", ticks)

Daylight Saving Time


US begins DST at 2:00 a.m. on the second Sunday in March and reverts to standard time on
the first Sunday in November. DST-Benjamin Franklin.

In the European Union, Summer Time begins and ends at 1:00 a.m. Universal Time
(Greenwich Mean Time). It begins the last Sunday in March and ends the last Sunday in
October.

Struct_Time Structure
Index Attributes Values
0 tm_year 2020
1 tm_mon 1 to 12
2 tm_mday 1 to 31
3 tm_hour 0 to 23
4 tm_min 0 to 59
5 tm_sec 0 to 61 (60 or 61 are leap-seconds)
6 tm_wday 0 to 6 (0 is Monday)
7 tm_yday 1 to 366 (Julian day)
8 tm_isdst -1, 0, 1, means library determines DST

Example:
#!/usr/bin/python
import time;
localtime = [Link]([Link]())
print("Local current time :", localtime)

How to Use Date & DateTime Class


Before you run the code for datetime, it is important that you import the date time modules.

Example:
from datetime import date
td=[Link]()
print("Today is: ",td)
day=[Link]
print("Day is: ",day)

Example:
from datetime import date
td=[Link]()
print([Link])
print([Link])
print([Link]())
print([Link](td))

How to Format Time Output


1 We used the "strf time function" for formatting.
2 This function uses different control code to give an output.
3 Each control code resembles different parameters like year,month, weekday and date
[(%y/%Y – Year), (%a/%A- weekday), (%b/%B- month), (%d - day of month)] .

Example:
from datetime import datetime
x=[Link]()
print([Link]("%y"))
print([Link]("%Y"))
print([Link]("%a"))
print([Link]("%A"))
print([Link]("%b"))
print([Link]("%B"))
print([Link]("%A %d %B,%y"))
print([Link]("%A %D %B,%Y"))
With the help of "Strftime" function we can also retrieve local system time, date or both.
%c- indicates the local date and time
%x- indicates the local date
%X- indicates the local time

Example:
from datetime import datetime
DFormat=[Link]()
print([Link]("%a"))
print([Link]("%A"))
print([Link]("%b"))
print([Link]("%B"))
print([Link]("%c"))
print([Link]("%C"))
print([Link]("%d"))
print([Link]("%D"))
print([Link]("%F"))
print([Link]("%y"))
print([Link]("%Y"))
print([Link]("%A %d %B,%y"))
print([Link]("%A %D %B,%Y"))
print([Link]("%x"))
print([Link]("%X"))
print([Link]("%I:%M:%S %p"))
print([Link]("%I:%M %p"))

Example:
from datetime import datetime
x=[Link]()
print([Link]("%c"))
print([Link]("%x"))
print([Link]("%X"))

The "strftime function" allows you to call the time in any format 24 hours or 12 hours.

Example:
from datetime import datetime
x=[Link]()
print([Link]("%I:%M:%S %p"))
print([Link]("%H:%M %p"))

Python Errors:
In python there are three types of errors
1. Syntax Errors
2. Logical Errors or Semantic Errors
3. RunTime Errors

1 Syntax Errors
These are the most basic type of errors. Syntax errors are almost always fatal. In IDLE, it will
highlight where the syntax error is. Most syntax errors are typos, incorrect
indentation/incorrect arguments.

Example:
print(Hello, World!)
print("Hello')
print('Hello")
class="Naresh i Technologies"
Name="KSRaju

Here are some ways to avoid the most common Syntax Errors:
1 Never use a Python keyword for a variable name
2 Any strings in the code should have matching quotation marks
3 Always check unclosed opening operators - (,{.(
4 Always check the indentation
5 Don't give your module the same name as one of the standard Python modules.

2 Logical Errors:
Your program might run without crashing (no syntax or run-time errors), but still do the
wrong thing.

Example:
x = 3; y = 4
avg = x + y / 2
print(avg)

but the program prints 5.0 instead!


x+ y / 2, this has the same mathematical meaning as x + (y / 2) = 3 + (4 / 2) = 3 + 2 = 5. To
fix the problem, average = (x + y) / 2, which makes clear. Logic errors can be difficult to
spot, especially in a longer program, but as you get better at writing code you will also get
better at avoiding logic errors.

How to use Timedelta Objects


With timedelta objects, you can estimate the time for both future and the past. In other words,
it is a timespan to predict any special day, date or time.

Example:
from datetime import datetime
from datetime import timedelta
print(timedelta(days=365,hours=8, minutes=15))
print("ToDay is: ", [Link]())

Example:
from datetime import timedelta
print(timedelta(days=345,hours=14,minutes=15))
#345 days, 14:15:00
print(timedelta(days=35,minutes=15,hours=14))
#35 days, 14:15:00
print(timedelta(days=35,minutes=15,hours=14,seconds=123))
#35 days, 14:17:03

The time Module


There is a popular time module available in Python which provides functions for working
with times and for converting between representations. Here is the list of all available
methods:

Getting formatted time


You can format any time as per your requirement, but simple method to get time in readable
format is asctime().
Example:
import time
lt=[Link]([Link]([Link]()))
print(lt)
dst=[Link]([Link]([Link]))
print(dst)

Python Calendar Module:


It allows you to output calendars like the Unix cal program. By default, these calendars have
Monday as the first day of the week, and Sunday as the last.

iterweekdays() method
It returns an iterator for the weekday numbers that will be used for one week. The first
number from the iterator will be the same as the number returned by firstweekday().

Syntax
iterweekdays()

Example:
import calendar
cal= [Link](firstweekday=0)
for x in [Link]():
print(x)

itermonthdays() method
It returns an iterator of a specified month and a year. Days returned will simply be day
numbers. The method is similar to itermonthdates().

Syntax:
itermonthdays(year, month)

Example:
import calendar
cal= [Link]()
for x in [Link](2016, 5):
print(x)

itermonthdays2() method
It is used to get an iterator for the month in the year similar to itermonthdates(). Days
returned will be tuples consisting of a day number and a week day number.

Syntax
itermonthdays2(year, month)

Example:
import calendar
cal=[Link](firstweekday=0)
for x in cal.itermonthdays2(2020,1):
print(x)

NOTE: Do the task of the folloing calendar methods:


1. itermonthdays3()
2. itermonthdays4()

itermonthdates() method
It returns an iterator for the month (1-12) in the year. This iterator will return all days for the
month and all days before the start of the month or after the end of the month that are
required to get a complete week.

Syntax
itermonthdates(year, month)

Example:
import calendar
cal=[Link](firstweekday=0)
for x in [Link](2020,1):
print(x)

monthdatescalendar() method
It is used to get a list of the weeks in the month of the year as full weeks. Weeks are lists of
seven [Link] objects.

Syntax
monthdatescalendar(year, month)

Example:
import calendar
cal= [Link]()
print([Link](2017, 5))

Python TextCalendar
formatyear() method
It is used to get a m-column calendar for an entire year as a multi-line string.

Syntax
formatyear(theyear, w=2, l=1, c=6, m=3)

year Year for which the calendar should be generated.


w The width between two columns. Default value is 2.
l Blank line between two rows. Default value is 1.
c Space between two months(Columnwise). Default value is 6
m Number of months in a row. Default value is 3.

Example:
import calendar
cal=[Link](firstweekday=0)
print([Link](2020,10))

Example:
import calendar
cal=[Link](firstweekday=0)
print([Link](2020,10,3,2,10,4))

Python HTMLCalendar Class:


formatmonth() method
It is used to get a month's calendar as an HTML table.

Syntax
formatmonth(theyear, themonth, withyear=True)

Example:
import calendar
cal=[Link](firstweekday=0)
print([Link](2020,2))

More Calendar Methods:


isleap() method
It returns True if the year is a leap year, otherwise False.

Syntax
isleap(year)

Example:
import calendar
print([Link](2016))
print([Link](2020))
print([Link](2019))

leapdays() method
It is used to get the number of leap years in a specified range of years.

Syntax
leapdays(y1, y2)

Example:
import calendar
print([Link](2015, 2018))
print([Link](2015, 2020))
print([Link](2000, 2020))
print([Link](2000, 2024))

weekheader() method
It is used to get a header containing abbreviated weekday names.

Syntax
weekheader(n)

Example:
import calendar
print([Link](3))

Display a specific Year Calendar


Example:
import calendar
Year=int(input("Enter Any Year: "))
Data=[Link](Year)
print(Data)

Example:Specific Month in a Year


import calendar
Year=2021
Month=1
Data=[Link](Year,Month)
print(Data)

calendar() method
It is used to get a 3-column calendar for an entire year as a multi-line string using the
formatyear() of the TextCalendar class.

Syntax
calendar(year, w=2, l=1, c=6, m=3)

Example:
import calendar
print([Link](2017))

month() method
It is used to get a month’s calendar in a multi-line string using the formatmonth() of the
TextCalendar class.

Syntax
month(theyear, themonth, w=0, l=0)

Example:
import calendar
print([Link](2017,5))

Example:
while True:
print("Options: ")
print("Enter 'Yes' to Display Calendar: ")
print("Enter Quit to End Program: ")
user_input=input(":")
if user_input=="Quit":
break
elif user_input=="Yes":
import calendar
Y=int(input("Enter Year: "))
M=int(input("Enter Month: "))
print([Link](Y.M))

Q3 Measure the execution time of small bits of Python code with the "timeit" module
>>> import timeit
>>> [Link]('"-".join(str(n) for n in range(100))',
number=10000)
0.3412662749997253
>>> [Link]('"-".join([str(n) for n in range(100)])',
number=10000)
0.2996307989997149
>>> [Link]('"-".join(map(str, range(100)))',
number=10000)
0.24581470699922647

Python Errors:
In python there are three types of errors
1. Syntax Errors
2. Logical Errors or Semantic Errors
3. RunTime Errors

1 Syntax Errors
These are the most basic type of errors. Syntax errors are almost always fatal. In IDLE, it will
highlight where the syntax error is. Most syntax errors are typos, incorrect
indentation/incorrect arguments.

Example:
print(Hello, World!)
print("Hello')
print('Hello")
class="Naresh i Technologies"
Name="KSRaju

Here are some ways to avoid the most common Syntax Errors:
1 Never use a Python keyword for a variable name
2 Any strings in the code should have matching quotation marks
3 Always check unclosed opening operators - (,{.(
4 Always check the indentation
5 Don't give your module the same name as one of the standard Python modules.
2 Logical Errors:
Your program might run without crashing (no syntax or run-time errors), but still do the
wrong thing.

Example:
x = 3; y = 4
avg = x + y / 2
print(avg)

but the program prints 5.0 instead!


x+ y / 2, this has the same mathematical meaning as x + (y / 2) = 3 + (4 / 2) = 3 + 2 = 5. To
fix the problem, average = (x + y) / 2, which makes clear. Logic errors can be difficult to
spot, especially in a longer program, but as you get better at writing code you will also get
better at avoiding logic errors.

3. RunTime Errors:
Python is able to understand what the program says, but runs into problems when actually
performing the instructions. Like spelling mistakes or invalid Methods & Properties etc...!!

Example:
x=500
printf(x)

CallMe="KSRaju"
print(callme)

Common RunTime Errors in PYTHON:


In PYTHON The following are common RunTimeErrors:
1 NameError 2 TypeError
3 KeyError 4 AttributeError
5 IndexError

Abnormal termination:
The concept of terminating the program or script in the middle of its execution without
executing last statement(s) of the program is known as abnormal termination.

Example:
a=input("Enter any Number")
b=input("Enter any Number")
c=a/b
print("The Value is: " ,c)

NOTE:
TypeError: unsupported operand type(s) for /: 'str' and 'str'

NOTE:
Abnormal termiation is the undesirable situation in any Programming language.

Types of Exceptions:
In Python there are 2 types of exceptions are possible.
[Link] Exceptions [Link] Definded Exceptions

Predefined Exceptions: Also known as in-built exceptions


Python Exception Handling
Python provides two important features to handle any unexpected error in your Python
programs:
1 Exception Handling 2 Assertions

What is an Exception?
An exception is an error that happens during execution of a program. When that error occurs,
Python generate an exception that can be handled, which avoids your program to crash.

Common Exception Errors


1 except IOError:
print('An error occurred trying to read the file.')

2 except ValueError:
print('Non-numeric data found in the file.')

3 except ImportError:
print("NO module found")

4 except EOFError:
print('End Of File No Data')

5 except KeyboardInterrupt:
print('You cancelled the operation.')

6 except:
print('An error occurred.')

Example:
number=int(input("Enter Any Number: "))
print("You Are Entered: ", number)

Note:
The above script get executed perfectly as long as the user enters a number, If not It
terminates, then we should develop exception logic.

Syntax:
try:
Some Statements Here
except:
Exception Handling

Example:
try:
x=int(input("Enter a value: "))
print("Try Block:Enter Number is: ",x)
except ValueError:
print("ExceptBlock:Invalid Input Enter Only Numbers");

Example:
try:
a=int(input("Enter any Number: "))
b=int(input("Enter any Number: "))
c=a/b
print("The Value is: " ,c)
except ValueError:
print("SooryInvalidInput")

Example:
try:
a=int(input("Enter any Number: "))
b=int(input("Enter any Number: "))
c=a/b
print("The Value is: " ,c)
except ValueError:
print("SooryInvalidInput")
except ZeroDivisionError:
print("b must be valid Number")

Example:
try:
x=int(input("Enter Required Number: "))
y=int(input("Enter Required Number: "))
print("The Result is: ",x/y)
except Exception as arg:
print("You can't divide by zero.")
print('Error: ', arg)

try with multiple except blocks:


Example:
try:
p=int(input("Enter Any Number: "))
q=int(input("Enter Any Number: "))
r=p/q
print("The Value is: ",int(r))
print("TryBlockIsExecuted:")
except ValueError:
print("ExceptBlock")
print("Sorry User Numbers Only Valid")
except Exception as arg:
print("You can't divide by zero.")
print('Error: ', arg)

Syntax-II
try:
You do your operations here;
......................
except Exception-I:
If there is ExceptionI, then execute this block.
......................
else:
If there is no exception then execute this block.

Example:
try:
fi=open("[Link]",'r')
print([Link](6))
except IOError:
print("File Not Existed Please Create")
else:
print("ContentReadSuccessfully")
[Link]()

NOTE: If file Not Existed It returns except IOError

Example:
try:
x=int(input("Enter Any Input: "))
y=int(input("Enter Any Input: "))
z=x/y
print(z)
except ValueError:
print("SorryAlphabetsUnableToCompute")
print("Special Chars Also Not Accepted")
except Exception as arg:
print("Error: ",arg)
else:
print("Welcome to Else Block")
print("Else Block Successfully Executed")
print("Welcome to More Computations")
print(x+y)
print(x-y)
print(x*y)

Default except block:


The except Clause with No Exceptions:
You can also use the except statement with no exceptions:

Syntax-III
try:
You do your operations here;
............................................
............................................
except:
If there is any exception, then execute this block.
............................................
............................................
else:
If there is no exception then execute this block.

Example:
try:
x=int(input("Enter Required Number: "))
y=int(input("Enter Required Number: "))
print("The Result is: ",int(x/y))
except:
print("Arithmetic Exception Raised.")
else:
print("SuccessfullyDone")

Default except block:


The except Clause with No Exceptions:
You can also use the except statement with no exceptions:

Syntax-III
try:
You do your operations here;
............................................
............................................
except:
If there is any exception, then execute this block.
............................................
............................................
else:
If there is no exception then execute this block.

Example:
try:
x=int(input("Enter Required Number: "))
y=int(input("Enter Required Number: "))
print("The Result is: ",int(x/y))
except:
print("Arithmetic Exception Raised.")
else:
print("SuccessfullyDone")

Syntax:-IV
The try-finally Clause
You can use a finally: block along with a try: block. The finally block is a place to put any
code that must execute, whether the try-block raised an exception or not.

try:
You do your operations here;
............................................
except:
Exceptional Statements
............................................
finally:
This would always be executed.
............................................

NOTE: You cannot use else clause, along with a finally clause.

Example:
try:
print("try block")
except:
print("except block")
finally:
print("finally block")

SyntaxV:
Nested try-except-finally blocks:
We can take try-except-finally blocks inside try or except or finally blocks.i.e nesting of try-
except-finally is possible.

Syntax:
try:
----------
----------
try:
----------
----------
except:
----------
----------
finally:
-----------
except:
-----------
-----------
finally:
-------------
-------------

EXAMPLE:
try:
print("OuterTryBlock")
try:
print("InnerTryBlock")
except ZeroDivisionError:
print("InnerExceptBlock")
finally:
print("InnerFinallyBlock")
except:
print("OuterExceptBlock")
finally:
print("OuterFinallyBlock")

User Defined Exceptions:


Some time we have to define and raise exceptions explicitly to indicate that something goes
wrong ,such type of exceptions are called User Defined Exceptions or Customized
Exceptions.

raise (throw) keyword:


We can raise an exception explicitly with the raise keyword. You can manually throw (raise)
an exception in Python with the keyword raise.

Syntax:
raise [Exception [, args ]]

Exception is the type of exception (for example, NameError) and argument is a value for the
exception argument. The argument is optional; if not supplied, the exception argument is
None.

Example:
>>> raise NameError("Raju")
>>> raise ValueError("InvalidData")

Example:
x=int(input("Enter Any Number: "))
if x<=10:
raise ValueError('x should not be less than 10!')
else:
print("Great Value")

Example:
try:
x=int(input("Enter Any Number: "))
print(x)
except:
raise ValueError("Invalid Input")

Example:
try:
a = int(input("Enter a negative integer: "))
if a >= 0:
raise ValueError("That is not a negative number!")
except ValueError as ve:
print(ve)

Assertions in Python(Automatic Error Detection)


Assert is the PYTHON Keyword. Python's assert statement helps you find bugs more quickly
and with less pain. When it encounters an assert statement, Python evaluates the
accompanying expression, which is hopefully true. If the expression is false, Python raises an
AssertionError exception.

Syntax
assert expression, argument

expression
Required. Expression to evaluate.

argument
Optional. Argument passed to the exception raise

Asserts VS Try...Except:
Software Errors are Two Categories:
1. Recoverable Errors (try ... except)
==> User can take corrective action(Try Again or Choose Another Option)
2. Un-Recoverable Errors(assert)
==> Not Enough information to fix or no alternative action is possible

Places to consider putting assertions:


1 Checking parameter types, classes, or values
2 Checking data structure invariants (never changed)
3 After calling a function, to make sure that its return is reasonable

NOTE:
Assertions are like airbags for your software. Always there, work automatically when you
need them.

Example:
assert 2 + 2 == 4
assert 2 + 2 == 3
assert 2 + 2 == 3,"That can't be right."

Example:
def power(x,y):
assert x>0,"x Must be Positive Number not {0}"
assert y>0,"y Must be Positive Number not {0}"
return x**y
print(power(1,-2))

Example:
def GetAge(age):
assert age>18,"Age Must not Be less than 18Years"
print("You are Allow to Access: ",age)
GetAge(19)

Ignore Errors
Errors can be ignored without handling them in the program. We can do this using 'pass' in
except block of error handling section like below.
Syntax:
try:
data="Something_that_Can_go_wrong"
except:
pass

Example:
try:
pass
except:
pass
finally:
pass

Example:
try:
x=int(input("Enter Required Number: "))
y=int(input("Enter Required Number: "))
print("The Result is: ",int(x/y))
except:
pass
print("Error: Arithmetic Operation Ignored. Pass Block")
else:
print("SuccessfullyDone")

Example:
try:
x=int(input("Enter Any: "))
print(x)
except:
pass
finally:
pass

RealTime Coding Challenges


try:
num = int(input("Input binary value: "), 2)
print("num (decimal format):", num)
print("num (binary format):", bin(num))
except ValueError:
print("Please input only binary value...")

Example:
try:
num = int(input("Input hexadecimal value: "), 16)
print("num (decimal format):", num)
print("num (hexadecimal format):", hex(num))
except ValueError:
print("Please input only hexadecimal value...")
Example:
try:
num = int(input("Input octal value: "), 8)
print("num (decimal format):", num)
print("num (octal format):", oct(num))
except ValueError:
print("Please input only octal value...")

Example:
Program for limiting the user to input only integer value
while True:
try:
num = int(input("Enter an integer number: "))
break
except ValueError:
print("Please input integer only...")
continue
print("num:", num)

Example:Program for limiting the user to input valid Age.


while True:
try:
age = int(input("Enter age: "))
if age>18 and age<51:
print("Age entered successfully...")
break;
else:
print("Age should be >18 and <51...")
except ValueError:
print("Provide an integer value...")
continue

Example:Program for limiting the user to input valid Gender.


while True:
try:
gender = input("Enter gender: ")
if gender == "Male" or gender == "Female":
print("Gender entered successfully...")
break;
else:
print("Gender should be either Male or Female")
except:
continue

Example:
#Input Age
while True:
try:
age = int(input("Enter age: "))
if age>18 and age<51:
print("Age entered successfully...")
break;
else:
print("Age should be >18 and <51...")
except ValueError:
print("Provide an integer value...")
continue

#Input Gender
while True:
try:
gender = input("Enter gender: ")
if gender == "Male" or gender == "Female":
print("Gender entered successfully...")
break;
else:
print("Gender should be either Male or Female")
except:
continue
# print age and gender
print("Age is:", age)
print("Gender is:", gender)

RealTime Coding Challenges:


Example:
Reading Binary values and Display Decimal Value..!!
def BinToDec(value):
try:
return int(value, 2)
except ValueError:
return "Invalid binary Value"

# Reading Binary Values


input1 = input("Enter Valid Binary: ")
input2 = input("Enter Valid Binary: ")
input3 = input("Enter Valid Binary: ")

print(input1, "as decimal: ", BinToDec(input1))


print(input2, "as decimal: ", BinToDec(input2))
print(input3, "as decimal: ", BinToDec(input3))

Example:
Reading Octal values and Display Decimal Value..!!
def OctToDec(value):
try:
return int(value, 8)
except ValueError:
return "Invalid Octal Value"

# Reading Octal Values


input1 = input("Enter Valid Octal Number: ")
input2 = input("Enter Valid Octal Number: ")
input3 = input("Enter Valid Octal Number: ")

print(input1, "as decimal: ", OctToDec(input1))


print(input2, "as decimal: ", OctToDec(input2))
print(input3, "as decimal: ", OctToDec(input3))

Reading hexa values and Display Decimal Value..!!


def HexToDec(value):
try:
return int(value, 16)
except ValueError:
return "Invalid Hexadecimal Value"

#Reading Values
input1 = input("Enter Valid Hexa Value: ")
input2 = input("Enter Valid Hexa Value: ")
input3 = input("Enter Valid Hexa Value: ")

#Display Hexa Values


print(input1, "as decimal: ", HexToDec(input1))
print(input2, "as decimal: ", HexToDec(input2))
print(input3, "as decimal: ", HexToDec(input3))

WORKING WITH PYTHON FILES:


File is collection of related information. In Python, a file operation takes place in the
following order.
1 Open a file 2 Read or write a file
3 Append a file 4 Close the file

Opening a file
Python has a built-in function open() to open a file. This function returns a file object. It
returns a "file handle" - a variable used to perform operations on the file. file handle has.!
[Link] [Link] [Link] 4. Close

Syntax
FileObject=open(file_name [, access_mode][, buffering])

Parameter details:
file_name: It contains the name of the file.
access_mode: Default file access mode is read (r).
buffering: The buffering value 0, no buffering takes place. If 1, line buffering is performed.

Example:
FileObj=open("[Link]")#relative path
FileObj=open("C:\\Python33\\[Link]") #(AbsolutePath)
File Different Modes:
Modes Description
r Opens a file for reading only. (default)
b Opens in binary mode.
r+ Opens a file for both reading & writing.
rb+ Opens a file for both reading & writing in binary format
w Opens a file for writing only.
a Opens a file for appending.
a+ Opens a file for both appending and reading.
't' Opens in text mode. (default)
x Open a file for exclusive creation. If file already exists Operation fails.

The file Object Attributes


Attribute Description
[Link] Returns name of the file
[Link] Returns access mode
writable() Returns boolean value
readable() Retruns boolean value
[Link] Retruns boolean value

The best way to do this is using the with statement. This ensures that the file is closed when
the block inside with is existed. We don't need to explicitly call the close() method. It done
Implicitly.

Syntax:
with open("[Link]",mode='r',encoding = 'utf-8') as MyFObj:
# Perform Required File Operations

Example:
try:
with open("[Link]",mode='r',encoding='utf-8') as MyFile:
print([Link])
print([Link])
print([Link])
print([Link]())
print([Link]())
except IOError:
print("SorryFileNotExisted")
finally:
print("FinallyBlockSuccess")

Writing data into a File


In order to write into a file we need to open it in write 'w', append 'a' or exclusive creation 'x'
mode.

NOTE:
We need to be careful with the 'w' mode as it will overwrite into the file if it already exists.

write() Method:
Using this method we can write a specific line in the file.
Syntax:
[Link]("Text")

writelines() Method:
Using this method we can write a specific multiple lines in the file.

Syntax:
[Link]("Text lines")

Example:
try:
with open("[Link]",mode='w',encoding='utf-8') as MyFileObj:
[Link]()
[Link]("Welcome to PYTHON File Operations\n")
[Link]("""Multiple lines are
Writing inside the A file.
Thank U""")
except IOError:
print("SorryFileUnableToCreate")
print("DiskWriteProtected")
finally:
print("FinallyBlockExecutedSuccessfully")
print("FileOperationsSuccess")

Example: Absolutepath or FullPath or LocalPath:


with open("C:\\Users\\admin\\Desktop\\Data\\[Link]",mode='w',encoding="utf-8") as
MyFile:
[Link]("हिन्दी हिन्दी हिन्दी हिन्दी\n")
[Link]("తెలుగు తెలుగు తెలుగు తెలుగు\n")
[Link]("Thank U")
print("FileCreatedSuccessfully")

Reading Data From a File


To read the content of a file, we must open the read mode. There are various methods to read
a file.

1. read() method:
It can read the data depends on size of characters read(size). If size parameter is not specified,
it reads and returns complete the file.

Syntax
[Link]([count]);

readline(): to read individual lines of a file


Syntax:
[Link]()

readlines()==> To read all lines into a list


Syntax:
[Link]()

Example:
with open("[Link]",'r',encoding = 'utf-8')as fi:
print([Link](3)) # read the first 3 chars. data
print([Link]()) # read in the rest till end of file
print([Link]()) # further reading returns empty sting
[Link]()

Example:
with open("[Link]",'r',encoding = 'utf-8') as fi:
print([Link](5))
str = [Link](10);
print("Read Strting is: " ,str)

Example: Reading the Whole File


with open("[Link]",'r',encoding = 'utf-8') as fi:
print([Link]())
[Link]()

Example:
#Reading the file and displaying number of characters
with open("[Link]",'r',encoding='utf-8') as fi:
chars=[Link]()
print("Number of characters are: ", len(chars))

Example:
with open("[Link]",'r',encoding = 'utf-8')as fi:
print([Link]())

Example:
with open("[Link]",'r',encoding = 'utf-8')as fi:
print([Link]())

Example:
#Reading the file and displaying number of Lines
with open("[Link]",'r',encoding='utf-8') as fi:
lines=[Link]()
print("Number of characters are: ", len(lines))

NOTE: All these reading method return empty values when end of file (EOF) is reached.

Example:
with open("[Link]",mode='r',encoding='utf-8') as MyFile:
lines=[Link]()
for line in lines:
print(line,end='')
[Link]()

Example:
#Counting Number of lines in a file
with open("[Link]",'r',encoding="utf-8") as lcount:
count = 0
for line in lcount:
count = count + 1
print('Number of Lines in a File:', count)

Example:
Number of Spaces in a file:
myfile=open("[Link]")
c=[Link]()
intialline=len(c)
finalline=0
for i in c:
z=[Link](" ")
for j in z:
finalline+=1
totalnumofspace=finalline-intialline
print(totalnumofspace)

Example:
fhand = open('[Link]','r')
for line in fhand:
if [Link]('From:') :
print(line)

Example:
import os,sys
fname=input("Enter Any File Name: ")
if [Link](fname):
print("File Existed:",fname)
f=open(fname,mode="r")
else:
print("Sorry File does not exist:",fname)
[Link]()
lcount=wcount=ccount=0
for line in f:
lcount=lcount+1
ccount=ccount+len(line)
words=[Link]()
wcount=wcount+len(words)
print("Number of Lines:",lcount)
print("Number of Words:",wcount)
print("Number of Characters:",ccount)

Appending a file:
We can able to append a file with the help of 'a'. Append means add the data to an existing
file, Under existing data.

Example:
with open("[Link]",'a',encoding="utf-8") as file:
[Link]("Appending a File\n")
[Link]("Thank U\n")
print("Successfully File Appended")

File cursor Positions


The tell() method tells you the current cursor position within the file.

Syntax:
[Link]()

Example:
with open("[Link]",'r',encoding = 'utf-8')as fi:
print([Link](5))
str = [Link](10);
print("Read Strting is: " ,str)
position=[Link]()
print("The Position of the cursor is: ",position)

seek() Method:
This method changes the cursor position in the file.

Syntax:
seek(offset[, from])

1 offset represents the number of positions


2 from
0---->From beginning of file(default value)
1---->From current position
2--->From end of the file

Note: Python 2 supports all 3 values but Python 3 supports only zero.

Example:
with open("[Link]",'r',encoding = 'utf-8')as fi:
print([Link](5))
str = [Link](10);
print("Read Strting is: " ,str)
position=[Link](0,0)
print("The Position of the cursor is: ",position)

Example:
with open("[Link]",'r',encoding = 'utf-8')as fi:
print([Link](5))
str = [Link](10);
print("Read Strting is: " ,str)
position = [Link](0, 0);
str = [Link](10);
print("Again read String is : ", str)
[Link]()

Example with for loop:


with open("[Link]",'r',encoding = 'utf-8')as fi:
for line in fi:
print(line, end = '')

Handling Binary Data:


It is very common requirement to read or write binary data like images,video files,audio files
etc.

Example:
MyFile1=open("[Link]",mode="rb")
MyFile2=open("[Link]",mode="wb")
Byts=[Link]()
[Link](Byts)
print("New Image is : [Link]")

Working with Zipping & Unzipping Files:


In PYTHON we can do zip and unzip files. Zip common featers are:
[Link] improve memory utilization
[Link] can reduce transfor time in network
[Link] can improve performance of transfer files

To create Zip file:


We have to create ZipFile class object with name of the zip file,mode and constant
ZIP_DEFLATED. This constant represents we are creating zip file.

Syntax:
Obj=ZipFile("ZipFileName",mode,"ZipType")

Example2:
from zipfile import *
ZFile=ZipFile("[Link]","w",ZIP_DEFLATED)
[Link]("[Link]")
[Link]("[Link]")
[Link]("[Link]")
[Link]()

Unzip Operations:
ZIP_STORED represents unzip operation. This is default value and hence we are not required
to specify. Once we created ZipFile object for unzip operation,we can get all file names
present in that zip file by using namelist() method.

Syntax:
FileObj = ZipFile("[Link]","r",ZIP_STORED)
names = [Link]()

Example:
from zipfile import *
ZFile=ZipFile("[Link]","r",ZIP_STORED)
names=[Link]()
for name in names:
print("File Name: ",name)

Working PYTHON OS Module:


The rename() Method
It takes two arguments, the current filename and the new filename.

Syntax
[Link](current_file_name, new_file_name)

Example:
import os
[Link]("[Link]","[Link]")

The remove() Method


It is used to delete files.

Syntax
[Link](file_name)

Example
import os
[Link]("[Link]")

The mkdir() Method


It is used to create directories in the current location.

Syntax
[Link]("newdir")

Example
import os
[Link]("PYTHON")

The chdir() Method


It is used to change the current directory.

Syntax
[Link]("Existingdir")

walk():
To display all contents of Current working directory including sub directories

Example:
import os
for dirpath,dirnames,filenames in [Link]('.'):
print("Current Directory Path:",dirpath)
print("Directories:",dirnames)
print("Files:",filenames)
print()

Example:Display all statistics of file:


import os
AllStat=[Link]("[Link]")
print(AllStat)

Shutdown and Restart Computer in Python


To shutdown and restart your computer or pc or laptop using python code, you have to first
import os library and then use [Link]() function with the code "shutdown /s /t 1" and
"shutdown /r /t 1" to shutdown and restart your computer in a second.

NOTE:
Caution - Make sure to close all the program before running any of the below program as
these program immediately shutdown or restart your computer.

Example:
import os
check = input("Shutdown your computer? (Y/N): ")
if check == 'N':
exit()
else:
[Link]("shutdown /s /t 1")

Example:
import os;
check = input("Shutdown your computer? (Y/N): ")
if check == 'n':
exit();
else:
[Link]("shutdown /r /t 1");

Example:
# Python Program - Shutdown and Restart Computer

import os;
print("1. Shutdown Computer");
print("2. Restart Computer");
print("3. Exit");
choice = int(input("\nEnter your choice: "));
if(choice>=1 and choice<=2):
if choice == 1:
[Link]("shutdown /s /t 1");
else:
[Link]("shutdown /r /t 1");
else:
exit();
print():
It prints the given object to the standard output device (screen) or to the text stream file.

Syntax
print(*objects, sep=' ', end='\n', file=[Link], flush=False)

1 objects/values - object to the printed. * indicates that there may be more than one object or
value
2 sep - objects are separated by sep. Default value: ' '
3 end - end is printed at last
4. file - must be an object with write(string) method. If omitted it, [Link] will be used
which prints objects on the screen.
5. flush - If True, the stream is forcibly flushed. Default value: False

Example:
Sfile=open("[Link]",mode='w')
print("Subba Raju Sir: ",file=Sfile)
print("Data Scientist: ",file=Sfile)
[Link]()

Example:
from time import sleep
#Output is flushed here
print("Hello, world!", end='', flush= True)
sleep(5)
print("Bye!!!")
#Output is not flushed here
print("HelpMe", end='')
sleep(5)
print("Okay!!!")

NOTE:
See the output – "Hello, world" and "Bye!!!" are printing correctly because before sleep(5)
the print() is flushing but "HelpMe" and "Okay!!!" are printing together, because print() is not
flushing.

Python Data Processing and Encoding:


CSV (Comma Separated Values/Data) files to store data that are in tabular format into plain
text & each line is treated as a data record in the file.

Define Delimiter:
It is a sequence of one or more characters used to specify the boundary between separate.

Example:
A delimiter is the comma character, or Space, or Gap or Colon etc.. a CSV file in Notepad,
Microsoft Excel, OpenOffice Calc, and Google Docs.

Syntax: CSV formated text..!!


fname,lname,age,salary
nancy,davolio,33,$30000
erin,borakova,28,$25250
tony,raphael,35,$28700

In PYTHON Environment we can able to work with csv files, we can use built-in module is
called CSV.
1. Open the file on required mode
2. Create the csv file represented object
3. Read or write or update the data

Syntax:
import csv

CSV Functions
1 [Link]
2 [Link]

EXAMPLE:Writing data in CSV file (Creating CSV File)


import csv
try:
with open("[Link]",mode='w',encoding='utf-8') as FP:
a=[Link](FP,delimiter=',')
data=[['STOCK','SALES','PRICE'],
['100','90','90$'],
['300','100','100$'],
['100','200','200$']]
[Link](data)
print("CSVFileCreatedSuccessfully")
except IOError:
print("SorryCSVFileUnableTOCreate")
print("ServerWriteProtected")
finally:
print("FinallyBlockSuccess")

EXAMPLE:Appending data in CSV file..!!


import csv
try:
with open("[Link]",mode='a',encoding='utf-8') as FP:
a=[Link](FP,delimiter=',')
data=[['10','9','9$'],
['0','0','0$'],
['10','2','2$']]
[Link](data)
print("CSVFileAppendSuccessfully")
except IOError:
print("SorryCSVFileUnableTOAppend")
print("ServerWriteProtected")
finally:
print("FinallyBlockSuccess")
EXAMPLE: Reading CSV File Without Builtin Methods..!!
try:
with open("[Link]",mode='r',encoding='utf-8') as FP:
for data in FP:
print(data)
print("CSVFileReadSuccessfully")
except IOError:
print("SorryCSVFileUnableToAppend")
print("ServerWriteProtected")
finally:
print("FinallyBlockSuccess")

Example:Reading CSV File


import csv
with open("[Link]",'r') as FP:
a=[Link](FP)
data=[]
for row in a:
if len(row)!=0:
data=data+[row]
print(data)

#without using csv module


path="[Link]"
lines=[line for line in open(path)]
print(lines[0])

Python String strip() Method


It returns a copy of the string in which all chars have been stripped from the beginning and
the end of the string (default whitespace characters).

Syntax:
[Link]([chars]);

Example:
path="[Link]"
lines=[line for line in open(path)]
print(lines[0])
print(lines[1].strip())

Python String split() Method


It returns a list of all the words in the string, using str as the separator.

Syntax
[Link](",").

Example:
path="[Link]"
lines=[line for line in open(path)]
print(lines[0])
print(lines[1].strip())
print(lines[1].strip().split(','))

[Link]

PYTHON LOGGING:
Logging is a means of tracking events that happen when some software runs. Logging is
important for software developing, debugging and running.

Example: Employee Log Book, System Log Files, Server Log File..!!

The main advantages of logging are:


[Link] can use log files while performing debugging
[Link] can provide statistics like number of requests per day etc
[Link] implement logging, Python provides one inbuilt module logging.

Levels of Log Message


Debug : These are used to give Detailed information
Info : These are used to Confirm that things are working as expected
Warning : These are used an indication that something unexpected happened
Error : This tells that due to a more serious problem
Critical : Indicating that the program itself may be unable to continue running

Each built-in logging level has been assigned its numeric value.
1 NOTSET ==> 0
2 DEBUG ==> 10
3 INFO ==> 20

High Priority/Higher Level Messages


4 WARNING ==> 30
5 ERROR ==> 40
6 CRITICAL ==> 50

Example:
import logging
[Link](filename='[Link]',level=[Link])
print("Hey Demo for Logging")
[Link]("This is Debug Message")
[Link]("This is Info Message")
[Link]("This is Warning Message")
[Link]("This is Error Message")
[Link]("This is Critical Message")
print("LoggingFileCreatedSuccessfully")

Example:
import logging
[Link](filename='[Link]',level=[Link])
print("Hey Demo for Logging")
[Link]("This is Debug Message")
[Link]("This is Info Message")
[Link]("This is Warning Message")
[Link]("This is Error Message")
[Link]("This is Critical Message")
print("LoggingFileCreatedSuccessfully")

Configure Log File in different File Modes:


The above scripts by default data will be append to the log file.

Example: (Default Append)


#Specify Explicitly Overwriting
[Link](filename='[Link]',level=[Link],filemode='w')
#Specify Explicitly
[Link](filename='[Link]',level=[Link],filemode='a')
#Default Mode
[Link](filename='[Link]',level=[Link])

NOTE:
Default Level-Warning(30), Default File-Console, Default Mode-Append

Example:
import logging
[Link](filename='[Link]',level=[Link])
print("Hey Demo for Logging")
[Link]("This is Debug Message")
[Link]("This is Info Message")
[Link]("This is Warning Message")
[Link]("This is Error Message")
[Link]("This is Critical Message")
print("LoggingFileCreatedSuccessfully")

Example:
import logging
[Link](filename='[Link]',level=[Link])
[Link]('Hei DevTeam New Log Tracked..!!')
try:
x=int(input('Enter First Number:'))
y=int(input('Enter Second Number:'))
print('The Result:',x/y)
except ZeroDivisionError as msg:
print('Error Divide With Zero')
[Link](msg)
except ValueError as msg:
print('Integer Only')
[Link](msg)
[Link]('Logging Finished Guys..!!')

How to format log messages:


Format keyword argument we can format messages
1. To display only level [Link](format='%(levelname)s')
Example:
import logging
[Link](filename='[Link]',level=[Link],format='%(asctime)s:%
(levelname)s:%(message)s')
[Link]('Hei Dev. Team,New Log Track..!!')
try:
x=int(input('Enter First Number:'))
y=int(input('Enter Second Number:'))
print('The Result:',x/y)
except ZeroDivisionError as msg:
print('Error Divide With Zero')
[Link](msg)
except ValueError as msg:
print('Integer Only')
[Link](msg)
[Link]('Logging Finished Guys..!!')

Example:
import logging
[Link](filename='[Link]',level=[Link],format='%(asctime)s:%
(levelname)s:%(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
[Link]('HeyDevTeamNew Log Track..!!')
try:
x=int(input('Enter First Number:'))
y=int(input('Enter Second Number:'))
print('The Result:',x/y)
except ZeroDivisionError as msg:
print('Error Divide With Zero')
[Link](msg)
except ValueError as msg:
print('Integer Only')
[Link](msg)
[Link]('Logging Finished..!!')

How to generate PDF using PYTHON:


We are going to learn how to generate PDF using python. Python has many supporting
libraries and world's largest community. Sometimes we need to convert our text files into
PDFs.

Installation:
$pip install fpdf

Example:
from fpdf import FPDF
pdf = FPDF()
pdf.add_page()
pdf.set_font('Arial',size=25)
[Link](200,100,txt='Hello, You are in [Link] ', align='C')
[Link]("[Link]")
print("Say Hey PDF File Creted Successfully")

NOTE:
1 We import FPDF and create an object for it. Now we create a page. we set font_size,
font_family. align represents the position of content in the cell, “C” -center, “R”-right, “L”-
left.
2 [Link]() method generate the output file. we need to give the output file name.

Generate pdf file from text file:


Example:
from fpdf import FPDF
f = open('[Link]','r')
content = ''
for i in f:
content =i
pdf = FPDF()
pdf.add_page()
pdf.set_font('Arial',size=18)
[Link](100,10,txt=content,align='C')
[Link]("[Link]")

NOTE:
open() helps us to grab our text file from our current directory in our system. ‘r’ represents
the mode of the file
Created one string empty variable "content" which helps us to store our text from the text file.
Used here a for loop to get that text from textfile and store it into "content".
[Link]() we reassign the txt parameter to "content" because we were storing the data in a
variable content.

WORKING WITH PYTHON REGULAR EXPRESSIONS


WHY REGULAR EXPRESSIONS?
#Example1
str1="My Name is Raju"
print([Link]("Raju","KSRaju"))

#Example2:
str2="Main Street is broad road"
print([Link]("road","rd"))

NOTE:
The above example converting all "road" patterns into rd, this is illegal, that time we are
counting characters as follows...!!

#Example3: We can replace with the help of index


print(str2[0:20]+str2[21:].replace("road","rd"))

NOTE:
The above example display result as per programmer expectation, but counting characters
every time is big challange, that time we are implementing PYTHON regexp or regex or re.
Define re?
Regular Expressions are powerful standardized way of searching, replacing, and parsing text
with complex patterns of characters.

Syntax
import re

Regular Expression Patterns


You can escape a control character by preceding it with a backslash.
Pattern Description
^ Matches beginning of line.
$ Matches end of line.
. Matches any single character except newline.
re* Matches 0 or more occurrences of preceding expression.
re+ Matches 1 or more occurrence of preceding expression.
re? Matches 0 or 1 occurrence of preceding expression.

Special Character Classes


Example Description
\d Match a digit: [0-9]
\D Match a nondigit: [^0-9]
\s Match a whitespace character: [ \t\r\n\f]
\S Match nonwhitespace: [^ \t\r\n\f]
\w Match a single word character: [A-Za-z0-9_]
\W Match a nonword character: [^A-Za-z0-9_]

Literal characters
Example Description
[Pp]ython Match "Python" or "python"
rub[ye] Match "ruby" or "rube"
[0-9] Match any digit; same as[0123456789]
[^0-9] Match anything other than a digit
[a-z] Match any lowercase
[A-Z] Match any uppercase
[a-zA-Z0-9] Match any of the above

Repetition Cases
Example Description
ruby? Match "rub" or "ruby": the y is optional
ruby* Match "rub" plus 0 or more y's
ruby+ Match "rub" plus 1 or more y's
\d{3} Match exactly 3 digits
\d{3,} Match 3 or more digits
\d{3,5} Match 3, 4, or 5 digits

The most common uses of Regular Expressions are:


1 Search a string (match & search)
2 Finding a string (findall)
3 Break string into a sub strings (split)
4 Replace part of a string (sub)

Various methods of RE?


The 're' package provides multiple methods to perform queries on an input string.
1 [Link]() 2 [Link]()
3 [Link]() 4 [Link]() 5 [Link]()

The most common uses of Regular Expressions are:


1 Search a string (match & search)
2 Finding a string (findall)
3 Break string into a sub strings (split)
4 Replace part of a string (sub)

Various methods of RE?


The 're' package provides multiple methods to perform queries on an input string.
1 [Link]() 2 [Link]()
3 [Link]() 4 [Link]() 5 [Link]()

The match Method


It finds and match, if pattern occurs at start of the string.

Syntax:
[Link](pattern, string)

Example:
import re
line="pet:cat I love cats"
mat=[Link](r"pet:\w\w\w",line)
print(mat)

NOTE:
It shows that pattern match has been found. To print the matching string use method group, It
helps to return the matching string.

import re
line="pet:cat I love cats"
mat=[Link](r"pet:\w\w\w",line)
print([Link](0))

Example:Using start and end methods


import re
line="Pet:Cat I like Pets Pet:Cow I love Cows"
mat=[Link](r"Pet:\w\w\w",line)
print([Link](0)) #Pet:Cat
print([Link]())#0
print([Link]())#7

NOTE: r always indicates PYTHON raw string..!!


NOTE: match method only matches the patterns in the starting..!!

Example:
from re import *
StrPatt = '^s...a$'
PyStr = 'subba'
PyResult = match(StrPatt, PyStr)
if(PyResult):
print("Striing Pattern Matched")
else:
print("String Pattern Not Matched")

The search Method


It searches for first occurrence of RE pattern within string.

Syntax:
[Link](pattern, string)

Example:
import re
line="pet:cat I love cats"
mat=[Link](r"pet:\w\w\w",line)
print([Link](0))

Example:
import re
line="I love cats pet:cat"
mat=[Link](r"pet:\w\w\w",line)
print(mat)

Example:
import re
line="I love cats pet:cat"
mat=[Link](r"pet:\w\w\w",line)
print([Link](0))

Example:
import re
line=" pet:cat I love cats pet:cow I love cow"
mat=[Link](r"pet:\w\w\w",line)
print([Link](0))

Example: For more than 1 time.


import re
PyResult = [Link]('m*', 'Programming')
if(PyResult):
print("Pattern Found")
else:
print("Pattern Not Found")
Example:For Exactly 1 time.
from re import *
PyResult = search('!?', 'Hello World!')
if(PyResult):
print("YES Found")
else:
print("NOT Found")

NOTE:
search method returns only first occurance of the pattern in the string or line. If we need all
matching patterns we should use findall().

[Link] Method:
It helps to get a list of all matching patterns. It has no constraints of searching from start or
end. If we will use method findall to search cat in given string it will return both occurrence
of cow.

Syntax:
[Link] (pattern, string)

Example:
import re
line=" pet:cat I love cats pet:cow I love cow"
mat=[Link](r"pet:\w\w\w",line)
print(mat)

Example:
import re
result=[Link](r'@\w+.\w+','[Link]@[Link], xyz@[Link],
[Link]@[Link], [Link]@[Link]')
print(result)

Example:
import re
result=[Link](r'@\w+.(\w+)','[Link]@[Link], xyz@[Link],
[Link]@[Link], [Link]@[Link]')
print(result)

[Link] Method:
It helps to split string by the occurrences of given pattern.

Syntax:
[Link](pattern,string)

Example:
import re
line="I love cats pet:cat I love cows, pet:cow thank U"
mat=[Link](r"pet:\w\w\w",line)
print(mat)
Example:
import re
print([Link](r'\s','Naresh i Technologies Ameerpet'))
print([Link](r'\s','Leader in IT Training'))

Example:
import re
result=[Link](r' ','NareshIT HYDERABAD')
print(result)

Syntax2:
[Link](pattern, string, [maxsplit=0])

Example:
import re
result=[Link](r'a','NareshITHYDERABAD',maxsplit=1)
print(result)

[Link]():
It helps to search a pattern and replace with a new sub string. If the pattern is not found,
string is returned unchanged.

Syntax:
[Link](pattern, repl, string):

Example:
import re
str1="raju@[Link] and ksr@[Link] and vara@[Link]"
mat=[Link](r"@\w+","@gmail",str1)
print(mat)

Example:
import re
text = "Python for beginners is a cool Scripting"
pattern = [Link]("cool", "good", text)
print(pattern)
***************************************************************************
******
Example:
import re
result = [Link](r'BigData', 'Data Science Based on BigData')
print ([Link](0))
#group(0) didn't return the entire match

Example:
import re
fi = open('[Link]')
for line in fi:
if [Link]('^F', line) :
print(line)
rstrip()
It returns a copy of the string in which all chars have been stripped from the end of the string.

Syntax
[Link]([chars])

Example:
import re
fi = open('[Link]')
for line in fi:
if [Link]('From:', line) :
line = [Link]()
print(line)

Search and Replace


One of the most important re methods that use regular expressions is sub and search.

Syntax
[Link](pattern, repl)

Example:
import re
s = 'NareshITOn Ameerpet MAIN ROAD..!!'
Rep=[Link]('NareshIT', 'NiT:')
print(Rep)

[Link] Method:
It helps to get a list of all matching patterns. It has no constraints of searching from start or
end. If we will use method findall to search NiT in given string it will return both occurrence
of nit.

Syntax:
[Link] (pattern, string)

Example: Extract each character (using "\w")


import re
result=[Link](r'.','Naresh i Technologies')
print(result)
result1=[Link](r'\w','Naresh i Technologies')
print(result1)

Extract each word (using "*" or "+")


Example:
import re
result=[Link](r'\w*','Naresh i Technologies Leader in IT Training')
print (result)

Example:
import re
result=[Link](r'\w+','Naresh i Technologies Leader in IT Training')
print (result)

Extract each word (using "^")


Example:
import re
result=[Link](r'^\w+','NiT Naresh i Technologies')
print (result)

Example:
import re
result=[Link](r'\w+$','NiT Naresh i Technologies')
print (result)

Return the first three character of each word (\w)


Example:
import re
result=[Link](r'\w\w\w','NiT Naresh i Technologies')
print (result)

Extract consecutive two characters those available at start of word boundary (using "\b")
Example:
import re
result=[Link](r'\b\w.','NiT Naresh i Technologies Leader in IT')
print (result)

Return the domain type of given email-ids


Extract all characters after “@”

Example:
import re
result=[Link](r'@\w+',"""[Link]@[Link], xyz@[Link],
[Link]@[Link], [Link]@[Link]""")
print (result)

NOTE: Above, you can see that ".com", ".in" part is not extracted.

Example:
import re
result=[Link](r'@\w+.\w+',"""[Link]@[Link], xyz@[Link],
[Link]@[Link], [Link]@[Link]""")
print (result)

Example: Extract only domain name using "( )"


import re
result=[Link](r'@\w+.(\w+)',"""[Link]@[Link], xyz@[Link],
[Link]@[Link], [Link]@[Link]""")
print (result)

Return date from given string: Here we will use "\d" to extract digit.
Example:
import re
result=[Link](r'\d{2}-\d{2}-\d{4}',"""Amit 34-3456 12-05-2007,
XYZ 56-4532 11-11-2011, ABC 67-8945 12-01-2009""")
print (result)

NOTE: If you want to extract only year again parenthesis "( )" will help you.

Example:
import re
result=[Link](r'\d{2}-\d{2}-(\d{4})',"""Amit 34-3456 12-05-2007,
XYZ 56-4532 11-11-2011, ABC 67-8945 12-01-2009""")
print (result)

[Link] Method:
"s": This expression is used for creating a space in the string

Example:
import re
print([Link](r'\s','Naresh i Technologies Ameerpet'))
print([Link](r'\s','Leader in IT Training'))

Example: Split a string with multiple delimiters


import re
line = 'asdf fjdk;afed,fjek,asdf,foo'
result= [Link](r'[;,\s]', line)
print(result)

NOTE: We can also use method [Link]() to replace these multiple delimiters with one as
space.

[Link](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.

Example:
import re
result=[Link](r'India','the World','NiT is largest Training Center of India')
print(result)

Example:
import re
line = 'asdf fjdk;afed,fjek,asdf,foo'
result= [Link](r'[;,\s]',' ', line)
print(result)

WORKING WITH PYTHON OOPs


PYTHON Object Oriented Programming System:(OOPs)
Python is truly object oriented programming language. In Python everything is an Object
like:classes, objects, functions, methods, modules etc..These can passed as arguments to
functions or assign to variables.

OOPS Principles
Oops are the rules (or) guidelines which are supposed to be satisfied by any programming
language in order to call that programming language as oopl. Different oops principles are:
1. Class 2. Object [Link] [Link] [Link]
[Link]

Define Class?
Class can be described as :
1 Pre-defined keyword.
2 Class is Template or Blue print for Objects
3 Collections of variables and methods
4 Collection of objects that has common properties

Example:
Class Name ==> Phone
Rotary Phone Cellular Phone
Mobile Phone Touch Phone

Example:
print(type('Hello'))

def Hello():
print("Wish Programmers")
print(type(Hello))

Example:
Human ==> Class
Midhun, Daniel, Scott are the Objects
Two hands, Height, weight, color, eyes ==> Attributes
eating(), walking(), sleeping(), writing() ==> Methods

Class in Python
We can define a class by using 'class' keyword.

Syntax1:
class Account:
"""This is docstring, explains brief about the class"""
pass
sb_account=Account()
current_account=Account()

Syntax2:
class Account(object):
"""This is docstring, explains brief about the class"""
pass
sb_account=Account()
current_account=Account()

Syntax3:
class Account():
"""This is docstring, explains brief about the class"""
pass
sb_account=Account()
current_account=Account()

NOTE: Don't miss the colon after the class name

Example:
class Car():
pass
print(Car)
print(type(Car))
print(Car.__name__)
print(Car.__doc__)

Example:
class Car():
"""This is docstring, explains brief about the class"""
pass
CC=Car()
print(type(CC))
print(CC)
print(isinstance(CC,Car))

NOTE:
Class Name should starts with Capital letter, It is convention in PYTHON

Define Object?
Collection of data and its functionality.
OR
It is an entity that has states & behaviors is known as Object.
OR
An Object is an instance of class, which contains attributes & methods

Define Reference Variable?


The variable which can be used to refer object is called reference variable. By using reference
variable, we can access properties and methods of object.

NOTE:
State means Properties/Attributes, Behaviour means methods/functionalities.

Example:
Object1: Human
Identity: Midhun
Properties: Color, Height, Weight
Functionalities: walk () , see() , run() ....
Example:
class MyBank_SBI():
pass
class MyBank_AB:
pass
class MyBank_HDFC(object):
pass
#SS is an Object or Instance
SS=MyBank_SBI()
print(SS)
#AA is an Object or Instance
AA=MyBank_AB()
print(AA)
#HH is an Object or Instance
HH=MyBank_HDFC()
print(HH)

NOTE:
Instance indicates relationship between an Object to its Class (Instanace means reference)

Example:
class Banking():
#Class Body or Logic
print("Welcome to Banking")
#Creating Instance or Object
#Driver Code
BB=Banking()
print(BB)#display the address of Object or Instance

isinstance() method
It checks if the object (first argument ) is an instance or subclass of classinfo class (second
argument)

Syntax:
isinstance(object, classinfo)

Example:
class Example:
name = 'NareshIT'
Ex=Example()
print(isinstance(Ex,Example))

Comparison between type() and isinstance()


type()
It returns the type of the object

isinstance()
it checks to see if the object passed in the first argument is of the type of any of the type
objects passed in the second argument.
Define Method?
A method is an operation on object , with in the class

Example:
class Banking():
#It is a Method of Member
#Class inside all are members
def MyCustomer():
print("Welcome to Banking")
return()
#Driver Code
BB=Banking()
[Link]()
#TypeError: MyCustomer() takes 0 positional arguments but 1 was given

Self variable:
self is the default variable which is always pointing to current object (like this keyword in
JAVA) By using self we can access instance variables and instance methods of object.

Example:
class Banking():
def MyCustomer(self):
print("Welcome to Banking")
return()
#Driver Code
BB=Banking()
[Link]()

Example:
class Human():
"This class demonstrates the creation of Objects"
#Instance Attributes
num=100
#Instance Method
def EampleMethod(self):
print("I am a method inside the class")

#Creating Object or Instance of Human Class


HH=Human()
print([Link])
#Calling Method
[Link]()
print(Human.__doc__)
print(help(Human))

Example:
class Banking():
def MyCustomer(x):
print("Welcome to Banking")
return()
#Driver COde
BB=Banking()
[Link]()

Example:
class Banking():
def MyCustomer(self):
print("Welcome to Banking")
print(id(self))
#Driver Code
BB=Banking()
[Link]()
print(id(BB))

NOTE:
As per PYTHON Documentation, self is not mandatory, It is not keyword, self replace by any
argument, but first argument is default & acting as self. self value provided by PVM.

Example:
class MyTry_Finally():
def Exceptions(self):
try:
x=int(input("Enter Any Number: "))
y=int(input("Enter Any Number: "))
z=x/y
print("The Result is: ",z)
except ZeroDivisionError:
print("Y must not be ZERO")
except ValueError:
print("Invalid Input")
finally:
print("FinallyBlockSuccess")

#Creating Instance or Object


MyObj=MyTry_Finally()
[Link]()
[Link]()

Difference between Function and Method in PYTHON:


Function:
1 It is always independent, not related to any Class
2 Outside the class a piece of code
3 No Self Parameter required
4 No Instance required to call

Method:
1 It is always related to a class
2 Inside the class a piece of code
2 Self Parameter required
4 Always instance required to call

Constructor in PYTHON:
1 It is a special method or magical method in python.
2 Name of the constructor should be __init__
3 It will be executed automatically at the time of object creation.
4 The main advantage of constructor is to declare and initialize instance variables.
5 For every instance constructor will be exeucted one-time
6 It can take atleast one argument(self)
7 It is an optional, if we are not providing any constructor then Python will provide default
constructor.

Constructors can be of two types.


1 Parameterized Constructor
2 Non-parameterized Constructor

Example:
class MyBanking():
def __init__(self):
print("Hello I am Always First Get Executed")
print("Thank U")
#Creating an Object
MM=MyBanking()

Example:
class MyBanking():
def __init__(self,name):
print("Hello I am Always First Get Executed")
print("Thank U")
#Instance Variable is name
[Link]=name
print("My Name is: ",[Link])
#Creating Object or Instance/Driver Code
MM=MyBanking("PYTHON")

Example:
class MyBanking():
def __init__(self,a):
print("Hello I am Always First Get Executed")
print("Thank U")
#Instance Variable is name
[Link]=a
print("My Name is: ",[Link])
#Creating Object or Instance/Driver Code
MM=MyBanking("PYTHON")

Example: Counting the number of objects of a class


class Student:
count = 0
def __init__(self):
[Link] = [Link] + 1
s1=Student()
s2=Student()
s3=Student()
print("The number of students:",[Link])

Example:
class Human():
life="Air & Water"
#Instance Attributes
def __init__(self,name,height,weight):
[Link]=name
[Link]=height
[Link]=weight
#Instance Method
def Eating(self,food):
return "{} is eating {}".format([Link],food)
#Creating object of human class
Ram=Human('Ram',6,70)
Scott=Human('Scott',6,76)
print([Link])#Accessing class level variable

print("Height of {} is {}".format([Link],[Link]))
print("Height of {} is {}".format([Link],[Link]))
print([Link]("Pizza"))

print("Height of {} is {}".format([Link],[Link]))
print("Height of {} is {}".format([Link],[Link]))
print([Link]("Big Burger"))

Example:
class Basket():
def __init__(self):
[Link]=[]

#Creating Instance Methods


def Fill(self,fruit):
[Link](fruit)

def Delete(self,fruit):
if fruit in [Link]:
[Link](fruit)

def Show(self):
for fruit in [Link]:
print(fruit)
Obj=Basket()
[Link]("Apple")
[Link]("Grapes")
[Link]("Papaya")
[Link]()
print()
[Link]("Apple")
[Link]()

Example:
class MyBanking():
def __init__(self):
print("Hello I am Always First Get Executed")
def Display(self):
print("Welcome to Display Method")
print("Good Bye")
#Creating Object or Instance
MM=MyBanking()

Example:
class MyBanking():
def __init__(self):
print("Hello I am Always First Get Executed")
def Display(self):
print("Welcome to Display Method")
print("Good Bye")

MM=MyBanking()
[Link]()

Example:
class person:
def __init__(self,name):
[Link]=name
def display(self):
print("Hello",[Link])
return
MyObj=person('Raju')
[Link]()

Example:
class person:
def __init__(self,name):
[Link]=name
def display(self):
print("Hello",[Link])
return
person('Raju').display()

Example:
class Employee():
def __init__(self,name,eid,loc):
[Link]=name
[Link]=eid
[Link]=loc
def eDetails(self):
print("Hello Name is:",[Link])
print("Employee ID is:",[Link])
print("Employee Location is:",[Link])
Emp=Employee("KSRaju",1139,"HYD")
[Link]()

Example:
class Employee():
def eDetails(self):
print("Hello Name is:",[Link])
print("Employee ID is:",[Link])
print("Employee Location is:",[Link])
Emp=Employee()
[Link]='Raju'
[Link]=101
[Link]="HYD"
[Link]()

Example:
class Employee():
def Emp(self,Name,Id,Loc):
[Link]=Name
[Link]=Id
[Link]=Loc

def eDetails(self):
print("Hello Name is:",[Link])
print("Employee ID is:",[Link])
print("Employee Location is:",[Link])

EE=Employee()
[Link]("Raju",1001,'Hyd')
[Link]()

Example:
class Test():
def __init__(self):
print("Hei I am a Constructor.!")
def Method(self):
print("Hello I am a Method.!")
Tst_One=Test()
Tst_Two=Test()
Tst_Three=Test()
Tst_One.Method()

Example:
class Me():
def __init__(self):
print("Hei Constructor")
print(id(self))
MM=Me()
MM.__init__()
MM.__init__()

Find the number of references of an object:


[Link](objectreference)

EXAMPLE:
import sys
class Bank():
pass
BB=Bank()
BB1=BB
BB2=BB1
print([Link](BB))

Note:
For Every object, PYTHON internally maintains one default reference variable 'self'

Python Default Constructor


When we do not include the constructor in the class or forget to declare it, then that becomes
the default constructor. It does not perform any task but initializes the objects.

Example:
class Student:
roll_num = 101
name = "Joseph"
def display(self):
print(self.roll_num,[Link])

st = Student()
[Link]()

Differences between Methods and Constructors:


Method
1. Method can be any name
2. It will be executed if we call that method
3. For an object, method can be called any number of times.
4. Method contains business logic

Constructor
1. Name should be always __init__
2. It will be executed automatically at the time of object creation.
3. For object, Constructor will be executed one-time
4. Constructor Inside we have to declare, initialize instance variables

In Python class we can represent data by using the following variables.


[Link] Variables (Object Level Variables)
[Link] Variables (Class Level Variables)
[Link] variables (Method Level Variables)

Instance Variables:
If the value of a variable is varied from object to object, for every object a separate copy of
instance variables will be created.

Where we can declare Instance Variables:


1 Inside Constructor by using self variable
2 Inside Instance Method by using self variable
3 Outside of the class by using object reference variable

Example:
class Emp():
def __init__(self):
[Link]=1
[Link]='Rama'
[Link]="$1000"

eDetails=Emp()
print(eDetails.__dict__)

Example:
class MyClass():
def __init__(self):
self.x=100

def MyMethod(self):
self.y=200

MM=MyClass()
[Link]()
print(MM.__dict__)

Example:
class MyClass():
#This is constructor
def __init__(self):
#Instance Variable with self
self.x=100

#Instance Method
def MyMethod(self):
#Instance Variable with self
self.y=200

MM=MyClass()
[Link]()
#Instance Variable with Object Reference
MM.z=300
print(MM.__dict__)

Example:
class MyClass():
def __init__(self):
self.x=100

def MyMethod(self):
self.x=200
self.y=300

MM=MyClass()
[Link]()
MM.y=400
MM.z=500
print(MM.__dict__)

Example: Deleting Instance Variabes


class MyClass():
def __init__(self):
self.x=100

def MyMethod(self):
self.x=200
self.y=300
#Deleting Instance variables
del self.x

MM=MyClass()
[Link]()
MM.y=400
#Deleting Instance variables
del MM.y
MM.z=500
print(MM.__dict__)

Example:
class MyClass():
def __init__(self):
self.x=100
self.y=200

MM1=MyClass()
MM1.x=300
MM2=MyClass()
MM2.y=400
print(MM1.x,MM1.y)
print(MM2.x,MM2.y)

Static Variables:
The value of a variable is constant for every object
Class having static variable, shared by all objects of that class.
Access static variables by class name or object reference, recommended to use class name.

Instance Variable vs Static Variable:


In the case of instance variables for every object a seperate copy created
in the case of static variables for total class only one copy created

Example:
class MyClass():
#Static Variable
x=1
def __init__(self):
self.y=2

MM1=MyClass()
MM1.y=333
MyClass.x=666
MM2=MyClass()
print(MM1.x,MM1.y)
print(MM2.x,MM2.y)

Example:
class MyClass():
x=1
def __init__(self):
self.y=2

MM1=MyClass()
MM1.y=333
MM1.x=666
MM2=MyClass()
print(MM1.x,MM1.y)
print(MM2.x,MM2.y)

NOTE:
By object reference we can access instance variables
By class name we can access static variables

Various Places to declare Static Variables:


1 We can declare within the class directly
2 Inside constructor by using class name
3 Inside instance method by using class name
4 Inside classmethod by using either class name or cls variable
5 Inside static method by using class name
6 Outside of class using class name

Example:
class MyClass():
#We can declare within the class directly
p=1
def __init__(self):
#Inside constructor by using class name
MyClass.q=2

def MyMethod(self):
#Inside instance method by using class name
MyClass.r=3

@classmethod
def ClassMethod(cls):
#Inside classmethod by using either class name or cls variable
MyClass.s=4
cls.t=5
@staticmethod
def StaticMethod():
#Inside static method by using class name
MyClass.u=5

print(MyClass.__dict__)

Example:
class MyClass():
#We can declare within the class directly
p=1
def __init__(self):
#Inside constructor by using class name
MyClass.q=2

def MyMethod(self):
#Inside instance method by using class name
MyClass.r=3

@classmethod
def ClassMethod(cls):
#Inside classmethod by using either class name or cls variable
MyClass.s=4
cls.t=5
@staticmethod
def StaticMethod():
#Inside static method by using class name
MyClass.u=5

MM=MyClass()
[Link]()
[Link]()
[Link]()
#Outside of class using obj ref. or class name
MyClass.v=6
print(MyClass.__dict__)
[Link] variables/Temporary variables (Method Level Variables):
1 If we can declare variables inside a method directly.
2 It will be created at the time of method execution
3 They destroyed once method execution completes.
4 They cannot be accessed from outside of method.

Example:
class MyClass():
def MyMethodOne(self):
#Local Variable
x=1
print(x)
def MyMethodTwo(self):
#Local Variable
y=2
print(y)
MM=MyClass()
[Link]()
[Link]()

Example:
class MyClass():
def MyMethodOne(self):
#Local Variable
x=1
print(x)
def MyMethodTwo(self):
#Local Variable
y=2
print(y)
print(x)
MM=MyClass()
[Link]()
[Link]()

Attributes
An attribute is a specification that defines a property of an object, element, or file. It may
also refer to or set the specific value for a given instance of such.

There are two types of Attributes:


Built- in Class Attributes
Attributes defined by Users

Built-In Class Attributes


Every Python class has five built-in attributes and they can be accessed using dot (.) operator.
Attribute Type Description
__dict__ dictionary The class name space.
__name__ string The name of the class.
__bases__ tuple of classes The classes from which this class inherits
__doc__ string OR None The class documentation string.
__module__ string The name of the module in which this class was
defined.

Example:
class Built_Attr():
"Welcome to BuiltInAttrs"
print(Built_Attr.__dict__)
print(Built_Attr.__name__)
print(Built_Attr.__bases__)
print(Built_Attr.__doc__)
print(Built_Attr.__module__)

Attribute Defined by Users


1 Attributes are created inside the class definition
2 We can dynamically create new attributes for existing instances of a class
3 Attributes can be bound to class names as well

Example:
class Employee():
empCount=100
print([Link])
obj=Employee()
print([Link])

Access Modifiers:
PYTHON supports the following list of Access Modifiers:
1 Public:Attributes can be freely used
2 Protected: (Restricted) attributes should only be used under certain conditions
3 Private:Attributes can only be accessed inside of the class definition

Naming type
name public These attributes can be used freely inside or outside of a class
definition
_name Protected These attributes should not be used outside of the class definition, unless
inside of a subclass definition
__name Private This kind of attributes inaccessible and invisible.

Public:
All member variables and methods are public by default in Python
Example:
class Nit():
def __init__(self):
self.__pri="I am Private"
self._pro="I am Protected"
[Link]="I am Public"
ob=Nit()
print([Link]) #accessing Public attribute

Example:
class Nit():
def __init__(self):
self.__pri="I am Private"
self._pro="I am Protected"
[Link]="I am Public"
ob=Nit()
print([Link] )
[Link]=[Link] + ' Can U add me PUBLIC'
print([Link]) #Updaing and accessing Public attribute

Protected: (Restricted) attributes should only be used under certain conditions


class Nit():
def __init__(self):
self.__pri="I am Private"
self._pro="I am Protected"
[Link]="I am Public"
ob=Nit()
print(ob._pro) #accessing Protected attribute

Private:Attributes can only be accessed inside of the class definition


class Nit():
def __init__(self):
self.__pri="I am Private"
self._pro="I am Protected"
[Link]="I am Public"
ob=Nit()
print(ob.__pri) #accessing Private attribute

NOTE: AttributeError: 'Nit' object has no attribute '__pri'

Example:
class DataBinding():
def __init__(self):
self.x="It is Public Access"
print(self.x)

DD=DataBinding()
print(DD.x)

Example:
class DataBinding():
def __init__(self):
self._x="It is Protected Access"
print(self._x)

DD=DataBinding()
print(DD._x)

Example:
class DataBinding():
def __init__(self):
self.__x="It is Private Access"
print(self.__x)

DD=DataBinding()
print(DD.__x)#AttributeError:

Python built-in class functions


Python getattr()
It returns the value of the named attribute of an object. If not found, it returns the default
value provided to the function.

Syntax:
getattr(object, name[, default])

Example:
class Person:
exp = "15+"
name = "KSRaju"
person = Person()
print('The Exp is:', getattr(person, "exp"))
print('The Exp is:', [Link])

Example:
class Car():
brand='Toyota'
name='Innova'
model=2021
print(getattr(Car,'name'))
print(getattr(Car,'brand'))
print([Link])
print([Link])

Example:
class Person:
exp = "15+"
name = "KSRaju"
person = Person()
print('The Gender is:', getattr(person, 'gen', 'Male'))

Python setattr()
It sets the value of given attribute of an object.

Syntax:
setattr(object, name, value)

Example:
class Person:
name = 'KSRaju'
p = Person()
print('Before modification:', [Link])
setattr(p, 'name', 'NareshIT')
print('After modification:', [Link])

Example:
class Person:
name = 'KSRaju'
p = Person()
setattr(p, 'name', None)
print('Name is:', [Link])
setattr(p, 'exp', 15)
print('Exp is:', [Link])

Python hasattr()
It returns true if an object has the given named attribute and false if it does not.

Syntax:
hasattr(object, name)

Example:
class Person:
exp = 15
name = 'KSRaju'
person = Person()
print(hasattr(person, 'exp'))
print(hasattr(person, 'salary'))

Python delattr()
It deletes an attribute from the object (if the object allows it).

Syntax:
delattr(object, name)

Example:
class Person:
exp = 15
name = 'KSRaju'
person = Person()
print(delattr(person, 'exp'))

Example:
class Student:
def __init__(self, name, id, age):
[Link] = name
[Link] = id
[Link] = age
#Creates the object of the class Student
s = Student("John", 101, 22)
# prints the attribute name of the object s
print(getattr(s, 'name'))
# reset the value of attribute age to 23
setattr(s, "age", 23)
# prints the modified value of age
print(getattr(s, 'age'))
# prints true if the student contains the attribute with name id
print(hasattr(s, 'id'))
# deletes the attribute age
delattr(s, 'age')
# this will give an error since the attribute age has been deleted
print([Link])

EXAMPLES:
class Rectangle:
def __init__(self, length, breadth):
[Link] = length
[Link] = breadth

def get_perimeter(self):
return 2 * ([Link] + [Link])

def get_area(self):
return [Link] * [Link]

def calculate_cost(self):
area = self.get_area()
return area * self.unit_cost
r = Rectangle(160, 120)
print("Area of Rectangle: %s cm^2" % (r.get_area()))

Example:
class Car(object):
def __init__(self, model, color, company, speed_limit):
[Link] = color
[Link] = company
self.speed_limit = speed_limit
[Link] = model

def start(self):
print("started")

def stop(self):
print("stopped")

def accelarate(self):
print("accelarating...")

def change_gear(self, gear_type):


print("gear changed")

maruthi_suzuki=Car("ertiga", "black", "suzuki", 60)


maruthi_suzuki.start()
maruthi_suzuki.change_gear(0)
maruthi_suzuki.accelarate()
maruthi_suzuki.stop()

Class Variable (Static Variable) & Instance/Non-Static Variables


Class or static variables are shared by all objects, Instance variables are unique to each
Instance.

Example:
class student:
clg='NareshIT' #Class Variable
def __init__(self,rollno,name):
#Defining an Instance Variable
[Link]=rollno
[Link]=name

def display(self):
print("Student Name:" ,[Link])
print("Student RollNumber:" ,[Link])
print("Student College:" ,[Link])

#Declaring an Instance of Class


student1=student('100005','Raju')
[Link]()

#Declaring an Instance of Class


student2=student('100006','DRaju')
[Link]()

What is Garbage Collection?


Garbage Collection (GC) is a form of automatic memory management.
OR
The concept of removing the unused,unreferenced object from the memory location is known
as a garbage collection.

Example:
import gc
print(dir(gc))

Example:
import gc
#Checking Enable or not
print([Link]())#True
#To disable GC explicitly
[Link]()
#To enable GC explicitly
[Link]()

Garbage Collection.
There are two types of garbage collection supported by python they are
[Link] Garbage Collection
[Link] Garbage Collection

[Link] Garbage Collection:-


1 After starting execution of program periodically garbage collector program runs internally
2 Whenever any object is going to be removed from memory location the distructor of that
class is going to be executed.
3 In distructor we write the resource deallocation statement.

[Link] Garbage Collection


The concept of executing the garbage collection program explicitly whenever we required is
known as explicit garbage collection.
-By using 'del' keyword we can run garbage collector explicitly.

Destructors:
Destructor is a special method and the name should be del
Just before destroying an object Garbage Collector always calls destructor to perform clean
up activities
Once destructor execution completed then Garbage Collector automatically destroys that
object.

Note:
The job of destructor is not to destroy object, it is just to perform clean up activities.

Example
class Human:
def __init__(self,name,age):
print("Hello InIt")

def walk(self):
print("Walking")

def __del__(self):
print("I am Destroyed")

a=Human("Raju",44)
[Link]()
del a

Example:Output of the following Script..!


class Account():
def __init__(self,Id):
[Link]=Id
Id=666
Acc=Account(123)
print([Link])

Inner Classes or Nested Classes:


We can declare a class inside another class, such type of classes are called inner classes.
Without existing one type of object, if there is no chance of existing another type of
object,then we should go for inner classes.

Example:
Without existing Fan object there is no chance of existing Rotator object. Hence Rotator class
should be part of Fan class.

class Fan():
.........................
.........................
class Rotator():
.........................
.........................

Note:
Without existing outer class object there is no chance of existing inner class object.

EXAMPLE:
class Outer_Class():
def __init__(self):
print("Hey Outer Class")
class Inner_Class():
def __init__(self):
print("Bye Inner Class")
def Inner_Method(self):
print("InnerClassMethod")
OO=Outer_Class()
II=OO.Inner_Class()
II.Inner_Method()

Class Method in PYTHON:


It returns a class method for the given function. It is a method that is bound to a class rather
than its object. It doesn't require creation of a class instance. We can declare class method
explicitly by using @classmethod decorator. For class method we should provide 'cls'
variable at the time of declaration. A class method receives the class as implicit first
argument.

Syntax:
@classmethod
def func(cls, args...)

Example:
class Banker():
Cust=10000
@classmethod
def service(cls,name):
print('{} has {} Customers...'.format(name,[Link]))
#Calling with class name
[Link]('SBI')
[Link]('ICICI')

When to use?
Class method to create factory methods. Factory methods return class object ( Similar to a
constructor )

Static Method in PYTHON:


1 Simple functions with no 'self' argument
2 Nested inside a class
3 These methods are general utility methods.
4 Inside these methods we won't use any instance or class variables.
5 We can declare static method explicitly by using @staticmethod decorator.
6 We can access static methods by using classname or object reference

Example:
class Nit():
@staticmethod
def static_method(attr):
print(attr)
#Calling static Method
Nit.static_method("Hello Static Method")

Example:
class Math_Compute():
@staticmethod
def Sum(A,B):
print('The Sum is:',A+B)
@staticmethod
def Mult(A,B):
print('The Product is:',A*B)
@staticmethod
def Avg(A,B):
print('The average:',(A+B)/2)

Math_Compute.Sum(1,2)
Math_Compute.Mult(3,4)
Math_Compute.Avg(5,6)

Class method vs Static Method


A class method takes cls as first parameter while a static method needs no specific
parameters.
We use @classmethod decorator in python to create a class method.
We use @staticmethod decorator to create a static method

When to use?
Static methods to create utility functions.

Python Metaprogramming
It is the concept of building functions and classes whose primary target is to manipulate code
by modifying, wrapping or generating existing code. The major features of meta-
programming are:
I. Metaclasses
II. Decorators
III. Class-decorators

Metaclasses
In Python everything have some type associated with it. You can get type of anything using
type() function. Metaclass create Classes and Classes creates objects.

[Link]..!

Example:
num = 23
print("Type of num is:", type(num)) #<class 'int'>

lst = [1, 2, 4]
print("Type of lst is:", type(lst)) #<class 'list'>

name = "PYTHON"
print("Type of name is:", type(name)) #<class 'str'>

Every type in Python is defined by Class.


Example:
class Student():
pass
Stu_Obj = Student()
print("Type of stu_obj is:", type(Stu_Obj)) #<class '__main__.Student'>

A Class is also an object, and just like any other object it’s a instance of something called
Metaclass. A special class type creates these Class object.

Class-decorators
Decorators are a very powerful and useful tool in Python since it allows programmers to
modify the behaviour of function or class.

Example:
class MyDecorator:
def __init__(self, function):
[Link] = function
def __call__(self):
[Link]()
@MyDecorator
def function():
print("Welcome to Class Decorators")
function()

Example:
def Decorator_One(f):
def Method():
print("Decorating", f.__name__)
f()
return Method
@Decorator_One
def Decorator_Method():
print("inside Decorator_Method()")
Decorator_Method()

Python property decorator--@property


It is one of the built-in decorators. The main purpose of any decorator is to change your class
methods or attributes in such a way so that the user of your class no need to make any change
in their code.
Property Decorators - Getters, Setters and Deleters

Setter Method:
It can be used to set values to the instance variables. setter methods also known as mutator
methods.

Syntax:
def setVariable(self,variable):
[Link]=variable

Example:
def setName(self,name):
[Link]=name

Getter Method:
It can be used to get values of the instance variables. Getter methods also known as accessor
methods.

Syntax:
def getVariable(self):
return [Link]

Example:
def getName(self):
return [Link]

Example:
class Student:
def setName(self,name):
[Link]=name
def getName(self):
return [Link]
n=int(input('Enter number of students:'))
for i in range(n):
s=Student()
name=input('Enter Name:')
[Link](name)
print('Hi',[Link]())

Example:
class Student:
def setName(self,name):
[Link]=name
def DelName(self):
return [Link]
n=int(input('Enter number of students:'))
for i in range(n):
s=Student()
name=input('Enter Name:')
[Link](name)
del name

WHY INHERITANCE(NEED OF REUSABILITY)


Example:
class Banking():
def Login(self):
print("LoginRequiredForBanking")
print("Thank U")
class OnlineBanking():
def Login(self):
print("LoginRequiredForBanking")
print("Thank U")
def Online(self):
print("Welcome to Online Banking")
print("Secured Banking")
class MobileBanking():
def Login(self):
print("LoginRequiredForBanking")
print("Thank U")
def MBanking(self):
print("Welcome to Touch Banking")
print("It is More Comfort and AnyWhere Banking")
class PhoneBanking():
def Login(self):
print("LoginRequiredForBanking")
print("Thank U")
def PBanking(self):
print("Welcome to Phone Banking")
print("It is Only for Senior Citizens")
print("Thank U")

#Creating Instance or Object


PP=PhoneBanking()
[Link]()
[Link]()
MM=MobileBanking()
[Link]()
[Link]()
OO=OnlineBanking()
[Link]()
[Link]()

Example: UseCase-II
class Animal():
def Eat(self):
print("All Animals are Eating")
class Dog():
def Eat(self):
print("All Animals are Eating")
def Sound(self):
print("Barking........!!")
class Cat():
def Eat(self):
print("All Animals are Eating")
def Sound(self):
print("Mewwwwwwwwww!!!")
class Lion():
def Eat(self):
print("All Animals are Eating")
def Sound(self):
print("Roaring............!!")
LL=Lion()
[Link]()
[Link]()
CC=Cat()
[Link]()
[Link]()
DD=Dog()
[Link]()
[Link]()

INHERITANCE:
Reuse-Class Members-Attributes & Methods
OR
It is the process of inheriting the class members from one class to another class is called
Inheritance.
OR
The concept of using properties of one class into another class without creating object of that
class explicitly is known as inheritance.
OR
1 A class which is extended by another class is known as 'super class'.
2 Both super class property and sub class property can be accessed through sublcass
[Link]

Types of Inheritance(s):
1. Single Level Inheritance
2. Multilevel Inheritance
3. Multiple Inheritance
4. Hierarchial Inheritance
5. Hybrid Inheritance
6. Diamond Inheritance

Outline of Inheritance:
BaseClass #Existing Class
Feature1
Feature2

DerievedClass #NewlyCreatedClass
Feature1
Feature2
Feature3

Terminology:
Parent class ==> Base class ==>Super class
Child class ==> Derived class==> Sub class

Single Level Inheritance:


The concept of inheriting properties from only one class into another class is known as single
level inheritance.

Syntax:
class name(superclass):
BlockOfStatements

Syntax:
class BaseClass:
Body of base class
class DerivedClass(BaseClass):
Body of derived class

Example:
class animal:
def eat(self):
print('Eating...')

class dog(animal):
def bark(self):
print("barking")

d=dog()
[Link]()
[Link]()

Example:
class Animal():
def Eat(self):
print("Animal Eating...!!")
class Dog():
def Sound(self):
print("Dog Barking..!!")

D=Dog()
[Link]()
[Link]()

O/P
AttributeError: 'Dog' object has no attribute 'Eat'

Example:
class Banker():
def Services(self):
print("Every Bank Provide Services to Customers")
class Customer(Banker):
def Cust_Ser(self):
print("Customer using all services from Banker")
CC=Customer()
[Link]()
CC.Cust_Ser()

Example:
class animal:
def __init__(self,name):
[Link]=name
class dog(animal):
def display(self):
print([Link])
d=dog("Puppy")
[Link]()

Multilevel Inheritance
You can inherit a derived class from another derived class.
OR
Extending features from one derived class to another.

Outline of Multilevel Inheritance:


BaseClass #Existing Class
Feature1

DerievedClass1 #NewlyCreatedClass
Features+BaseClass
Feature2

DerievedClass2 #NewlyCreatedClass
Features+BaseClass
Features+DereivedClass1
Feature3

Syntax:
class BaseClass:
Body of base class
class DerivedClass1(BaseClass):
Body of derived class1
class DerivedClass2(DereivedClass1):
Body of derived class2

Example:
class Student():#Super Class
def getStudent(self):
[Link]=input("Name: ")
[Link]=int(input("Age: "))
[Link]=input("Gender: ")

class Subjects(Student):#Derived Class-1


def getMarks(self):
[Link]=input("Class: ")
print("Enter the marks of the respective subjects:")
[Link]=int(input("Programming: "))
[Link]=int(input("Math: "))
[Link]=int(input("English: "))
[Link]=int(input("Physics: "))

class Marks(Subjects):#Derived Class-2


def Display(self):
print("\n Name is: ",[Link])
print("Age is: ",[Link])
print("Gender is: ",[Link])
print("Class Name: ",[Link])
print("Total Marks: ",[Link]+[Link]+[Link]+[Link])

MM=Marks()
[Link]()
[Link]()
[Link]()

Example:
class Finacial_Services_India():
def FSI(self):
print("All Permissions from here")
print("It is related Finance")
class ReserveBankofIndia(Finacial_Services_India):
def RBI(self):
print("It is leading All Bankers in INDIA")
print("Thank u RBI")
class Bankers_India(ReserveBankofIndia):
def Bank_INDIA(self):
print("Welcome to Indian Banks")
print("We are ready to serve")
print("We deal Finanacial Matters")
BI=Bankers_India()
[Link]()
[Link]()
BI.Bank_INDIA()

Example:
class GrandFather():
def Hello_GFather(self):
print("I am in GrandFather Class")
class Father(GrandFather):
def Hello_Father(self):
print("I am in Father Class")
class Child(Father):
def Hello_Child(self):
print("I am in Child Class")

ch=Child()
ch.Hello_GFather()
ch.Hello_Father()
ch.Hello_Child()

Example:
class person():
def display(self):
print("Hello, This is class Person")
class employee(person):
def printing(self):
print("Hello This is derieved class Employee")
class programmer(employee):
def show(self):
print("Hello This is derieved class Programmer")

p1=programmer()
[Link]()
[Link]()
[Link]()

Example:
class Animal:
def eat(self):
print('Eating...')
class Dog(Animal):
def bark(self):
print('Barking...')
class BabyDog(Dog):
def weep(self):
print('Weeping...')
d=BabyDog()
[Link]()
[Link]()
[Link]()

LIVE USE CASES:


Bank ==> CreditCard ==> Customer
College ==> Course ==> Student
Vehi ==> Car ==> SportsCar ==> Speed

Multiple Inheritance:-
You can derive a child class from more than one base (Parent) class.

Outline of Multiple Inheritance:


BaseClass1 BaseClass2

DerievedClass

Syntax1:
class DerivedClassName(Base1, Base2...BaseN):
<statement-1>
-------------------------
<statement-N>

Example:
class First():
def A(self):
print("I am in First PClass")
class Second():
def B(self):
print("I am in Second PClass")
class Third(First,Second):
def C(self):
print("I am in Child Class")

TT=Third()
TT.A()
TT.B()
TT.C()

Python super() function:


It always refer the immediate superclass. It allows you to call methods of the superclass in
your subclass. It can refer the superclass implicitly. It eliminates the need to declare certain
characteristics of a class.

In Python, super() built-in has two major use cases:


1 Allows us to avoid using base class explicitly
2 Working with Multiple Inheritance
Syntax:PY-3.x
super().methoName(args)

Method Resolution Order (MRO)


In the multiple inheritance scenario, any specified attribute is searched first in the current
class. If not found, the search continues into parent classes in depth-first, left-right fashion
without searching same class twice. MRO must prevent local precedence ordering and also
provide monotonicity.

Example:
class First():
def __init__(self):
print("init of First Class")
def A(self):
print("I am in First PClass")
class Second():
def __init__(self):
print("init of Second Class")
def B(self):
print("I am in Second PClass")
class Third(First,Second):
def __init__(self):
super().__init__()
print("init of Third Class")
def C(self):
print("I am in Child Class")

TT=Third()
print([Link]())

Method Resolution Order (MRO) is the order in which Python looks for a method in a
hierarchy of classes. Especially it plays vital role in the context of multiple inheritance as
single method may be found in multiple super classes.

CASE:1
This is a simple case where we have class C derived from both A and B. When method
process() is called with object of class C then process() method in class A is called.

Example:
class A:
def process(self):
print('A process()')

class B:
pass

class C(A, B):


pass

obj = C()
[Link]()
print([Link]())

Example2:Case-2
class A:
def process(self):
print('A process()')

class B:
def process(self):
print('B process()')

class C(A, B):


pass

obj = C()
[Link]()

Case 3
In this case, we create D from C and B. Classes C and B have process() method and as
expected MRO chooses method from C. Remember it goes from left to right. So it searches C
first and all its super classes of C and then B and all its super classes.

Example:
class A:
def process(self):
print('A process()')
class B:
def process(self):
print('B process()')
class C(A, B):
def process(self):
print('C process()')
class D(C,B):
pass

obj = D()
[Link]()
print([Link]())

Case 4
Lets change the hierarchy. We create B and C from A and then D from B and C. Method
process() is present in both A and C.

Example:
class A:
def process(self):
print('A process()')
class B(A):
pass

class C(A):
def process(self):
print('C process()')

class D(B,C):
pass

obj = D()
[Link]()

Case 5
There are cases when Python cannot construct MRO owing to complexity of hierarchy.

Example:
class A:
def process(self):
print('A process()')

class B(A):
def process(self):
print('B process()')

class C(A, B):


pass

obj = C()
[Link]()

NOTE: TypeError: Cannot create a consistent method resolution order (MRO) for bases A, B

Example:
class Employee():
def Set1(self,empid,name,salary):
[Link]=empid
[Link]=name
[Link]=salary

class Fitness():
def Set2(self,height,weight, bloodGrp):
[Link]=height
[Link]=weight
[Link]=bloodGrp

class Company(Employee,Fitness):
def Set3(self,Company,dep):
[Link]=Company
[Link]=dep

def Display(self):
print("ID is: ",[Link])
print("Emp Name is: ",[Link])
print("Salary is: ",[Link])
print("Height is: ",[Link])
print("Weight is: ",[Link])
print("Blood Group is: ",[Link])
print()
print("Company is: ",[Link])
print("Department is: ",[Link])

CC=Company()
print([Link]())
CC.Set1(101,"Raju",70000)
CC.Set2(145,50,"B-")
CC.Set3("IBM","Software")
[Link]()

Constructor or __init__ In Inheritance


Example:
class First():
def __init__(self):
print("init of First Class")
def A(self):
print("I am in First PClass")
class Second(First):
def B(self):
print("I am in Second PClass")
class Third(Second):
def C(self):
print("I am in Child Class")

FF=First()

Example:
class First():
def __init__(self):
print("init of First Class")
def A(self):
print("I am in First PClass")
class Second(First):
def B(self):
print("I am in Second PClass")
class Third(Second):
def C(self):
print("I am in Child Class")

SS=Second()
Example:
class First():
def __init__(self):
print("init of First Class")
def A(self):
print("I am in First PClass")
class Second(First):
def B(self):
print("I am in Second PClass")
class Third(Second):
def C(self):
print("I am in Child Class")

TT=Third()

Example:The priority for its own class


class First():
def __init__(self):
print("init of First Class")
def A(self):
print("I am in First PClass")
class Second(First):
def __init__(self):
print("init of Second Class")
def B(self):
print("I am in Second PClass")
class Third(Second):
def C(self):
print("I am in Child Class")

SS=Second()

Example: If you want to execute both __init__ classes,super() function required


class First():
def __init__(self):
print("init of First Class")
def A(self):
print("I am in First PClass")
class Second(First):
def __init__(self):
super().__init__()
print("init of Second Class")
def B(self):
print("I am in Second PClass")
class Third(Second):
def C(self):
print("I am in Child Class")

SS=Second()
Hierarchical Inheritance:-
The concept of inheriting properties from one class into multiple classes is known as a
hierarchical inheritance

Syntax:
class A:
pass
class B(A):
pass
class C(A):
pass

Example:
class Details():
def __init__(self):
[Link]=""
[Link]=""
def SetData(self,Id,Name):
[Link]=Id
[Link]=Name
def ShowData(self):
print("ID: ",[Link])
print("Name: ",[Link])

class Employee(Details):
def __init__(self):
[Link]=""
[Link]=""
def SetEmployee(self,Id,Name,Comp,Dept):
[Link](Id,Name)
[Link]=Comp
[Link]=Dept
def ShowEmployee(self):
[Link]()
print("Company: ",[Link])
print("Department: ",[Link])

class Doctor(Details):
def __init__(self):
[Link]=""
[Link]=""
def SetEmployee(self,Id,Name,Hos,Dept):
[Link](Id,Name)
[Link]=Hos
[Link]=Dept
def ShowEmployee(self):
[Link]()
print("Hospital: ",[Link])
print("Department: ",[Link])

print("Employee Class Object")


EE=Employee()
[Link](101,"Raju","TCS","IT")
[Link]()

print("\n Doctor Class Object: ")


DD=Doctor()
[Link](101,'RaviKumar',"Prime","Dental")
[Link]()

Example:
class Banker():
def Bank_Services(self):
print("Welcome to Banking Services")
class EBanking(Banker):
def Email(self):
print("Welcome to Email Banking")
class Banking_Mobile(Banker):
def Mobile(self):
print("Welcome to Mobile Banking")
class Banking_Phone(Banker):
def Phone(self):
print("Welcome to Phone Banking")
BP=Banking_Phone()
BP.Bank_Services()
[Link]()
BM=Banking_Mobile()
BM.Bank_Services()
[Link]()
BE=EBanking()
BE.Bank_Services()
[Link]()

Example:
class Hello():
def MyOne(self):
print("I am in Hello Class")
class Hei(Hello):
def MyTwo(self):
print("I am in Hei Class")
class Bye(Hello):
def MyThree(self):
print("I a, in Bye Class")

HH=Hei()
[Link]()
[Link]()
BB=Bye()
[Link]()
[Link]()

Example:
class Animal():
def __init__(self,name):
[Link]=name
def talk(self):
pass

class Cat(Animal):
def talk(self):
print("Cat is MewMewMewMewMewMew..!!")

class Dog(Animal):
def talk(self):
print("Dog is Barkingngngngngngngng..!!")

a=Animal('Sound')
c=Cat("KITTY")
[Link]()

d=Dog("TOMMY")
[Link]()

LIVE USE CASE


Library ==> Students ==> Faculty ==> Management ==>SrCitizen

Hybrid Inheritance
It is combining two or more types of inheritance(s).
OR
It is the combination of Hirarchical+Multiple+Multilevel Inheritance(s) are called Hybrid
Inheritance.

PIC: HybridInheritance

Syntax:
class A:
pass
class B(A):
pass
class C(A):
pass
class D(B, C):
pass

def main():
obj1=D()

if __name__=="__main__":
main()

Example:
class A:
def m(self):
print("method from Class A....")

class B(A):
def m(self):
print("method from Class B....")

class C(A):
def m(self):
print("method from Class C....")

class D(B, C):


def m(self):
print("method from Class D....")
B.m(self)
C.m(self)
A.m(self)

def main():
obj1=D()
obj1.m()

if __name__=="__main__":
main()

Example: (Diamond Death Problem)


class A:
def m(self):
print("method from Class A....")

class B(A):
def m(self):
print("method from Class B....")
A.m(self)

class C(A):
def m(self):
print("method from Class C....")
A.m(self)

class D(B, C):


def m(self):
print("method from Class D....")
B.m(self)
C.m(self)
A.m(self)
def main():
obj1=D()
obj1.m()

if __name__=="__main__":
main()

Example: (with super())


class A:
def m(self):
print("method from Class A....")

class B(A):
def m(self):
print("method from Class B....")
super().m()

class C(A):
def m(self):
print("method from Class C....")
super().m()

class D(B, C):


def m(self):
print("method from Class D....")
super().m()

def main():
obj1=D()
obj1.m()

if __name__=="__main__":
main()

if __name__ =='__main__':

__name__ (A Special variable) in Python


__name__ is one such special variable. If the source file is executed as the main program, the
interpreter sets the __name__ variable to have a value “__main__”. If this file is being
imported from another module, __name__ will be set to the module’s name.

__name__ is a built-in variable which evaluates to the name of the current module. Thus it
can be used to check whether the current script is being run on its own or being imported
somewhere else by combining it with if statement.

>>>__name__
'__main__'

Example:
def Mul(a,b):
return a*b
print(Mul(2,3))
print(__name__)

Example:
import multiply
print([Link](2.3,1.1))
print(__name__)

Example:
def Mul(a,b):
return a*b
if __name__=="__main__":
print(Mul(2,3))
print(__name__)

Consider two separate files File1 and File2.


# [Link]
print("File1 __name__ = %s" %__name__)
if __name__ == "__main__":
print("File1 is being run directly")
else:
print("File1 is being imported")

# [Link]
import File1
print("File2 __name__ = %s" %__name__)
if __name__ == "__main__":
print("File2 is being run directly")
else:
print("File2 is being imported")

Above, when [Link] is run directly, the interpreter sets the __name__ variable as __main__
and when it is run through [Link] by importing, the __name__ variable is set as the name of
the python script, i.e. File1. Thus, it can be said that if __name__ == “__main__” is the part
of the program that runs when the script is run from the command line using a command like
python [Link].

Polymorphism:- (Many Forms or Shapes)


It is an ability of an object to adopt the code to the type of the data processing.
OR
It refers to the use of a single type entity (Method, Operator, Object) to represent different
types and different scenarios
OR
Implementing same thing in different ways or forms

Example:
Area of Polygon ==> Square, Rectangle, Triangle
Points to Remember:
1 Poly means many and morphism means forms
2 Forms means functionalities or logics.
3 The concept of defining multiple logics to perform same operation is known as a
polymorphism.
4 Python is implicitly polymorphic

Example:
A=5; B=6
print(A+B)

A="Hello";B="PYTHON"
print(A+B)

NOTE:
In the above example A, B are Over-ridden, + is Overloaded.

Example:
Using The Same membership operator checking the variable existed in Data Structures.
print('x' in {'a','b','c','x'})
print('x' in ['a','b','c','x'])
print('x' in ('a','b','c','x'))
print('x' in {'a':'b','x':'c'})

Example:

print(len('PYTHON'))
print(len(list(range(1,25,3))))

NOTE:
len function is polymorphism because the same function taking different inputs.

Polymorphism different forms:


Dynamic/RunTime Polymorphism(Overriding)
i) Method overriding
ii) Constructor overriding

Static Polymorphism/CompileTime Polymorphism (Overloading)


i) Method Overloading
ii) Constructor Overloading
iii) Operator Overloading

Dynamic/RunTime Polymorphism: Method overriding


Through method overriding a class may "copy" another class, avoiding duplicated code, and
at the same time enhance or customize part of it.
OR
It is the ability of a class to change the implementation of method provided by one of its
ancestors.
Example:
class A():
def display(self):
print("Method belongs to Class A")
class B(A):
pass

b1=B()
[Link]()

Example:
class A():
def display(self):
print("Method belongs to Class A")
class B(A):
def display(self):
print("Method belongs to Class B")

b1=B()
[Link]()

Example:
class ParentClass():
def Transport(self):
print("CYCLE")
class ChildClass(ParentClass):
def Transport(self):
print("BIKE")
class GrandChildClass(ChildClass):
def Transport(self):
print("CAR")

GG=GrandChildClass()
[Link]()

Example:
class Father():
def Fname(self):
print("FatherFirstName")
def Lname(self):
print("FatherLastName")
class Son(Father):
def Fname(self):
print("SonFirstName")

ObjSon=Son()
[Link]()
[Link]()

NOTE:
If method names are different, It never satisfy method overriding concept.

Example:
class Person():
def __init__(self,name,age):
[Link]=name
[Link]=age

def DisplayData(self):#OverriddenMethod
print("Parent Class Method")
print("Name is: ",[Link])
print("Age is: ",[Link])

class Employee(Person):
def __init__(self,name,age,Id):
super().__init__(name,age)
[Link]=Id

def DisplayData(self):#OverriddenMethod
print("Employee Class Display-Data Method")
print("Name is: ",[Link])
print("Age is: ",[Link])
print("Emp ID is: ",[Link])

class Developer(Employee):
def __init__(self,name,age,Id,Exp):
super().__init__(name,age,Id)
[Link]=Exp

def DisplayData(self):#OverriddenMethod
print("Developer Class Display-Data Method")
print("Name is: ",[Link])
print("Age is: ",[Link])
print("Emp ID is: ",[Link])
print("Exp is: ",[Link])

#Person Class Insatnce or Object


PP=Person("Rama",45)
[Link]()
print()
#Employee Class Instance or Object
EE=Employee("Rama",45,101)
[Link]()
print()
#Developer Class Instance or Object
Dev=Developer("Rama",45,"101","5 Yrs")
[Link]()

Constructor Overriding:
Example:
class PConstructor():
def __init__(self):
print('Welcome to Main Constructor')
class CContstructor(PConstructor):
def __init__(self):
print('Good Bye Sub Constructor')

#Creating Instance
HelloCons=CContstructor()

NOTE:
If child class does not contain constructor then parent class constructor will be executed

Example:
class PConstructor():
def __init__(self):
print('Welcome To Main Constructor')
class CContstructor(PConstructor):
pass

#Creating Instance
HelloCons=CContstructor()

Static Polymorphism: Method & Constructor Overloading:


PYTHON does not supports Method Overloading & Constructor Overloading, It is
dynamically typed language. If we are trying to declare multiple methods with same name
and different number of arguments then Python will always consider only last method.

Example:
class CalCulate():
def add(self,a,b):
return a+b
def add(self,a,b,c):
return a+b+c
obj=CalCulate()
print([Link](3,1))
print([Link](3,1,3))

NOTE:
TypeError: add() missing 1 required positional argument: 'c'
NOTE:
In Python it always calls latest implemention of the method

Example: We can achieve through default arguments.!


class MethodOverLoading():
def Total(self,a,b,c=0,d=0):
Sum=a+b+c+d
return Sum

MOL=MethodOverLoading()
Tot1=[Link](7,8)
print(Tot1)

Tot2=[Link](7,8,9)
print(Tot2)

Tot3=[Link](7,8,9,10)
print(Tot3)

Constructor Overloading
It is not possible in Python. If we define multiple constructors then the last constructor will be
considered.

Example:
class Constructor1():
def __init__(self):
print('Welcome to Constructor1')
def __init__(self):
print('Welcome To Constructor2')

#Creating Object
CC=Constructor1()

Example:
class Constructor1():
def __init__(self,x):
print('Welcome to Constructor1')
def __init__(self,x,y):
print('Welcome To Constructor2')

#Creating Object
CC=Constructor1(1)

NOTE:
TypeError: __init__() missing 1 required positional argument: 'y'

Example:
class Constructor1():
def __init__(self,x):
print('Welcome to Constructor1')
def __init__(self,x,y):
print('Welcome To Constructor2')

#Creating Object
CC=Constructor1(1,2)

Polymorphism:- (Many Forms or Shapes)


It is an ability of an object to adopt the code to the type of the data processing.
OR
It refers to the use of a single type entity (Method, Operator, Object) to represent different
types and different scenarios
OR
Implementing same thing in different ways or forms

Example:
Area of Polygon ==> Square, Rectangle, Triangle

Points to Remember:
1 Poly means many and morphism means forms
2 Forms means functionalities or logics.
3 The concept of defining multiple logics to perform same operation is known as a
polymorphism.
4 Python is implicitly polymorphic

Example:
A=5; B=6
print(A+B)

A="Hello";B="PYTHON"
print(A+B)

NOTE:
In the above example A, B are Over-ridden, + is Overloaded.

Example:
Using The Same membership operator checking the variable existed in Data Structures.
print('x' in {'a','b','c','x'})
print('x' in ['a','b','c','x'])
print('x' in ('a','b','c','x'))
print('x' in {'a':'b','x':'c'})

Example:

print(len('PYTHON'))
print(len(list(range(1,25,3))))

NOTE:
len function is polymorphism because the same function taking different inputs.

Polymorphism different forms:


Dynamic/RunTime Polymorphism(Overriding)
i) Method overriding
ii) Constructor overriding

Static Polymorphism/CompileTime Polymorphism (Overloading)


i) Method Overloading
ii) Constructor Overloading
iii) Operator Overloading

Dynamic/RunTime Polymorphism: Method overriding


Through method overriding a class may "copy" another class, avoiding duplicated code, and
at the same time enhance or customize part of it.
OR
It is the ability of a class to change the implementation of method provided by one of its
ancestors.

Example:
class A():
def display(self):
print("Method belongs to Class A")
class B(A):
pass

b1=B()
[Link]()

Example:
class A():
def display(self):
print("Method belongs to Class A")
class B(A):
def display(self):
print("Method belongs to Class B")

b1=B()
[Link]()

Example:
class ParentClass():
def Transport(self):
print("CYCLE")
class ChildClass(ParentClass):
def Transport(self):
print("BIKE")
class GrandChildClass(ChildClass):
def Transport(self):
print("CAR")

GG=GrandChildClass()
[Link]()

Example:
class Father():
def Fname(self):
print("FatherFirstName")
def Lname(self):
print("FatherLastName")
class Son(Father):
def Fname(self):
print("SonFirstName")
ObjSon=Son()
[Link]()
[Link]()

NOTE:
If method names are different, It never satisfy method overriding concept.

Example:
class Person():
def __init__(self,name,age):
[Link]=name
[Link]=age

def DisplayData(self):#OverriddenMethod
print("Parent Class Method")
print("Name is: ",[Link])
print("Age is: ",[Link])

class Employee(Person):
def __init__(self,name,age,Id):
super().__init__(name,age)
[Link]=Id

def DisplayData(self):#OverriddenMethod
print("Employee Class Display-Data Method")
print("Name is: ",[Link])
print("Age is: ",[Link])
print("Emp ID is: ",[Link])

class Developer(Employee):
def __init__(self,name,age,Id,Exp):
super().__init__(name,age,Id)
[Link]=Exp

def DisplayData(self):#OverriddenMethod
print("Developer Class Display-Data Method")
print("Name is: ",[Link])
print("Age is: ",[Link])
print("Emp ID is: ",[Link])
print("Exp is: ",[Link])

#Person Class Insatnce or Object


PP=Person("Rama",45)
[Link]()
print()
#Employee Class Instance or Object
EE=Employee("Rama",45,101)
[Link]()
print()
#Developer Class Instance or Object
Dev=Developer("Rama",45,"101","5 Yrs")
[Link]()

Constructor Overriding:
Example:
class PConstructor():
def __init__(self):
print('Welcome to Main Constructor')
class CContstructor(PConstructor):
def __init__(self):
print('Good Bye Sub Constructor')

#Creating Instance
HelloCons=CContstructor()

NOTE:
If child class does not contain constructor then parent class constructor will be executed

Example:
class PConstructor():
def __init__(self):
print('Welcome To Main Constructor')
class CContstructor(PConstructor):
pass

#Creating Instance
HelloCons=CContstructor()

Static Polymorphism: Method & Constructor Overloading:


PYTHON does not supports Method Overloading & Constructor Overloading, It is
dynamically typed language. If we are trying to declare multiple methods with same name
and different number of arguments then Python will always consider only last method.

Example:
class CalCulate():
def add(self,a,b):
return a+b
def add(self,a,b,c):
return a+b+c
obj=CalCulate()
print([Link](3,1))
print([Link](3,1,3))

NOTE:
TypeError: add() missing 1 required positional argument: 'c'
NOTE:
In Python it always calls latest implemention of the method

Example: We can achieve through default arguments.!


class MethodOverLoading():
def Total(self,a,b,c=0,d=0):
Sum=a+b+c+d
return Sum

MOL=MethodOverLoading()
Tot1=[Link](7,8)
print(Tot1)

Tot2=[Link](7,8,9)
print(Tot2)

Tot3=[Link](7,8,9,10)
print(Tot3)

Constructor Overloading
It is not possible in Python. If we define multiple constructors then the last constructor will be
considered.

Example:
class Constructor1():
def __init__(self):
print('Welcome to Constructor1')
def __init__(self):
print('Welcome To Constructor2')

#Creating Object
CC=Constructor1()

Example:
class Constructor1():
def __init__(self,x):
print('Welcome to Constructor1')
def __init__(self,x,y):
print('Welcome To Constructor2')

#Creating Object
CC=Constructor1(1)

NOTE:
TypeError: __init__() missing 1 required positional argument: 'y'

Example:
class Constructor1():
def __init__(self,x):
print('Welcome to Constructor1')
def __init__(self,x,y):
print('Welcome To Constructor2')

#Creating Object
CC=Constructor1(1,2)
Python Operator Overloading:
Assigning extra work to operators is called operators overloading
OR
The assignment of more than one function to a particular operator

Example:Basics of Operators
x=10
y=20
print(x+y)
print(int.__add__(x,y))
#Addition of Integers it not possible without __add__ method defined inside 'int' class

Example:
print(10+20)#30
print('KSraju'+'DataScientist')#KSrajuDataScientist

Example:
print(10*2)#20
print('Data Science '*4,end=" ")#Data Science Data Science Data Science Data Science

Example:
a=4;b=6
print(a+b)
c="Hello ";d="World!"
print(c+d)

Example:
class EmpSlary():
def __init__(self, salary):
[Link]=salary

Emp1=EmpSlary(300000)
Emp2=EmpSlary(200000)
TotalSal=Emp1+Emp2
print("TotalSalaryOfEmployeesIS: ",TotalSal)

NOTE:
1 TypeError: unsupported operand type(s) for +: 'EmpSlary' and 'EmpSlary'
2 The program defines + operator is not for objects adding.

Example:
class Subject():
def __init__(self,Course):
[Link]=Course

Sub1=Subject(89)
Sub2=Subject(56)
print(Sub1+Sub2)
O/P:
TypeError: unsupported operand type(s) for +: 'Subject' and 'Subject'

Points to Remember:
1 In Python every operator has Magic Method.
2 To overload any operator we have to override that Method in our class.
3 Internally + operator is implemented by using add () method.
4 This method is called magic method for + operator

Operator Overloading Special Functions in Python


Operator Expression Internally
Addition p1 + p2 p1.__add__(p2)
Subtraction p1 - p2 p1.__sub__(p2)
Multiplication p1 * p2 p1.__mul__(p2)
Power p1 ** p2 p1.__pow__(p2)
Division p1 / p2 p1.__truediv__(p2)
Floor Div p1 // p2 p1.__floordiv__p2()
Modulus p1 % p2 p1.__mod__p2()

Example:
class EmpSlary():
def __init__(self, salary):
[Link]=salary

def __add__(self,other):
return [Link]+[Link]

Emp1=EmpSlary(300000)
Emp2=EmpSlary(200000)
TotalSal=Emp1+Emp2
print("TotalSalaryOfEmployeesIS: ",TotalSal)

NOTE: Return statement plays major role here, whatever value you want to return.

Example:
class EmpSlary():
def __init__(self, salary):
[Link]=salary

def __add__(self,other):
return 3000

Emp1=EmpSlary(300000)
Emp2=EmpSlary(200000)
TotalSal=Emp1+Emp2
print("TotalSalaryOfEmployeesIS: ",TotalSal)

Example:
class Subject():
def __init__(self,Course):
[Link]=Course

def __add__(self,other):
return [Link]+[Link]

Sub1=Subject(89)
Sub2=Subject(56)
print(Sub1+Sub2)

NOTE:
Python supports + operator for , Addition, Concatenation, and Objects Adding, JAVA
Never..!!

Example:
class Subject():

def __init__(self,Course):
[Link]=Course

def __sub__(self,Other):
return [Link]

def __add__(self,Other):
return [Link]+[Link]

SubjectOne=Subject(90)
SubjectTwo=Subject(49)
print(SubjectOne-SubjectTwo)
print(SubjectOne-SubjectTwo)
print(SubjectOne+SubjectTwo)
print(SubjectOne+SubjectTwo)

Example:
class Subject():
def __init__(self,Course):
[Link]=Course

def __add__(self,other):
return [Link]+[Link]

def __mul__(self,other):
return [Link]*[Link]

Sub1=Subject(89)
Sub2=Subject(56)
print(Sub1+Sub2)
print(Sub1*Sub2)

Example:
class Subject():
def __init__(self,Sub,Price):
[Link]=Sub
[Link]=Price

def __gt__(self,other):
return [Link]>[Link]

Sub1=Subject('Maths',100)
Sub2=Subject('Social',200)
print(Sub2>Sub1)

Example:
class Subject():
def __init__(self,Course):
[Link]=Course

def __add__(self,other1,other2):
return [Link]+[Link]+[Link]

Sub1=Subject(89)
Sub2=Subject(56)
Sub3=Subject(76)
print(Sub1+Sub2+Sub3)

NOTE: TypeError: __add__() missing 1 required positional argument: 'other2'

Duck-Typing
If its looks like a duck and quacks like duck, It is duck.
OR
It is an application of the duck test in type safety. It requires that type checking be deferred to
runtime, and is implemented by means of dynamic typing or reflection. It is type of
Polymorphism.
OR
It is a concept related to dynamic typting, where the type or the class of an object is less
important than the method it defines. We do not check types at all.

Example:
def Cal(a,b):
return a+b
print(Cal(1,2))
print(Cal("Hello","PYTHON"))
print(Cal(1,"PYTHON"))

Error: TypeError: unsupported operand type(s) for +: 'int' and 'str'

Example:
class Duck():
def Sound(self):
print("Quack-Quack-Quack-Quack!")

class Dog():
def Sound(self):
print("Woof Woof!")

class Cat():
def Sound(self):
print("Meow Meow Meow!")

def AllSounds(obj):
[Link]()

x=Duck()
AllSounds(x)

NOTE:
It doesn't matter to which class or object x belongs, what matter is if that object has method
sound define in it.

Example:
class Lion():
def Sound(self):
print('Roar, Roar, Roaring..!!')

class Cow():
def Sound(self):
print('Ammmmmm..!!')

def AnimalSound(obj):
[Link]()

PyList=Lion()
AnimalSound(PyList)

Example:
class Lion():
def Sound(self):
print('Roar, Roar, Roaring..!!')

class Cow():
def Sound(self):
print('Ammmmmm..!!')

def MyFun(obj):
[Link]()

PyList=[Lion(),Cow()]
for obj in PyList:
MyFun(obj)

Encapsulation:(Data Binding/Grouping)
We can restrict the access to the variables and methods is called as Encapsulation.
OR
The process of wrapping up variables and methods into a single entity is known as
Encapsulation
OR
It can prevent the data from being modified by accidently.
OR
It describes the idea of wrapping data and the methods that work on data within one unit.

Example:RealTimeUseCase
Employees==>Diff Deparments
Admin Department ==> These Employee records can access that Department Head only
HR Deparment ==> These Employee records can access that Department Head only
Admin Department Employee Details Unable to access HR Department is called
Encapsulation.

Private & Protected members in Python


1 When the attributes of an object can only be accessed inside the class
2 Python use two underscores for private, single underscore for protect
3. We can not access private, protect attributes or methods outside the class

Summary of Encapsulation:
1 Encapsulation provide security by hiding the data from outside world
2 In Python we achieve encapsulation through Private & Protected access members
3 Private by leading two underscores, Protected by leading single underscore
4 Encapsulation ensures data protection & avoids the access of data accidentally

Example:
class Employee():
def __init__(self,name,age):
[Link]=name
[Link]=age
def DisplayDetails(self):
print([Link])
print([Link])

EE=Employee("SARA",30)
print([Link])
print([Link])
[Link]()

Example:
class DataBinding():
def __init__(self):
self.x="It is Public Access"
print(self.x)

DD=DataBinding()
print(DD.x)

Example:
class DataBinding():
def __init__(self):
self._x="It is Protected Access"
print(self._x)

DD=DataBinding()
print(DD._x)

Example:
class DataBinding():
def __init__(self):
self.__x="It is Private Access"
print(self.__x)

DD=DataBinding()
print(DD.__x)#AttributeError:

Example:
class Banking():
#Public Method
def PublicMethod(self):
print("Public Method")
#Protected Method
def _ProtectMethod(self):
print("Protect Method")
#Private Method
def __PrivateMethod(self):
print("Private Method")

#CreatingInstance
BB=Banking()
[Link]()
BB._ProtectMethod()
BB.__PrivateMethod()

NOTE:
AttributeError: 'Banking' object has no attribute '__PrivateMethod'

Multi Tasking:
Executing several tasks simultaneously is the concept of multitasking.

There are 2 types of Multi Tasking


[Link] based Multi Tasking
[Link] based Multi Tasking

[Link] based Multi Tasking:


Executing several tasks simmultaneously where each task is a seperate independent process is
called process based multi tasking.
We can listen audio songs from the system, at the same time we can download a file from the
internet. All these taks are executing simultaneously and independent of each other. It is best
suitable at operating system level.

[Link] based MultiTasking:


Executing several tasks simultaneously where each task is a seperate independent part of the
same program, is called Thread based multi tasking, each independent part is called a Thread.
This type of multi tasking is best suitable at programmatic level.

NOTE: We can reduce execution time and improve performance.!

Example:
import time
def CalSquareNums(numbers):
print("Calculate Square Of Numbers")
for n in numbers:
[Link](0.2)
print('SQUARE:',n*n)

def CalCubeNums(numbers):
print("Calculate Cube Of Numbers")
for n in numbers:
[Link](0.2)
print('CUBE:',n*n*n)

arr = [2,3,4,5,6,7]
stime = [Link]()
CalSquareNums(arr)
CalCubeNums(arr)
print("done in : ",[Link]()-stime)
print("Hah... I am done with all my work now!")

Python Threading or Multithreading:


Threading allows multiple tasks run concurrently or indepedently. It is a separate flow of
execution.
OR
Threads provide a way to improve application performance through parallelism.

Why Threading?
[Link] implement Multimedia graphics
2 Parallel Computation
3 Standardization
4 Parallel I/O (Input/Output)
5 Asynchronous Events
[Link] develop animations
[Link] develop video games
[Link] develop web and application servers..!

Methods of Thread Class


run(): It acts as the entry of the thread
start(): is used for starting the thread by calling the run()
isAlive(): is used to verify whether the still executing or not
getName(): is used for returning the name of a thread
setName(): is used to set the name of the thread

Example:
import threading
print("Current Executing Thread:",threading.current_thread().getName())#mainthread

Example:
import time
import threading

def calc_square(numbers):
print("calculate square numbers")
for n in numbers:
[Link](0.2)
print('square:',n*n)

def calc_cube(numbers):
print("calculate cube of numbers")
for n in numbers:
[Link](0.2)
print('cube:',n*n*n)

arr = [2,3,8,9]
t = [Link]()
t1= [Link](target=calc_square, args=(arr,))
t2= [Link](target=calc_cube, args=(arr,))

[Link]()
[Link]()

[Link]()
[Link]()

print("done in : ",[Link]()-t)
print("Hah... I am done with all my work now!")

Example:
import threading
class Thread1([Link]):
def run(self):
i=1
while i<=5:
print(i)
i=i+1
class Thread2([Link]):
def run(self):
i=1
while i<=5:
print(i)
i=i+1
t1=Thread1()
t2=Thread2()
[Link]()
[Link]()

Setting and Getting Name of a Thread:


Every thread in python has name. It may be default name generated by Python or Customized
Name provided by programmer. We can get and set name of thread by using the following
Thread class methods.
[Link]() ==> Returns Name of Thread
[Link](newName) ==>To set our own name

Note:
Every Thread has implicit variable "name" to represent name of Thread.

Example:
from threading import *
print(current_thread().getName())
current_thread().setName("PyThread")
print(current_thread().getName())
print(current_thread().name)

Thread Identification Number (ident):


For every thread internally a unique identification number is available. We can access this id
by using implicit variable "ident"

Example:
from threading import *
def Test_Thread():
print("MyThread",end=" ")
th=Thread(target=Test_Thread)
[Link]()
print("Main Thread ID:",current_thread().ident)
print("Child Thread ID:",[Link])

Daemon Threads:
The threads which are running in the background are called Daemon Threads.

Example:
Garbage Collector

Example:
from threading import *
print(current_thread().isDaemon()) #False
print(current_thread().daemon) #False

Default Nature:
By default Main Thread is always [Link] for the remaining threads Daemon nature
will be inherited from parent to child.

Example:
from threading import *
def ThTask():
print("ChildThread")
th=Thread(target=ThTask)
print([Link]())
[Link](True)
print([Link]())

PYTHON ABSTRACTION OR DATA HIDING


Abstraction is used to hide internal details & show only functionalities. It is blue print for
other classes.
OR
Abstraction is used to hide the internal functionality of the function from the users.
OR
Hiding all implemenations, show only essential parts. Here, using inheritance concept.

RealTimeUseCase:
Suppose you are going to an ATM to withdraw money. You simply insert your card and click
some buttons and get the money. You don’t know what is happening internally on press of
these buttons. Basically you are hiding unnecessary information from user.

Remember Points:
1 We are unable to create instance for abstract class.
2. We want to create instance, then we must convert into concrete class.
3. Concrete class means no abstract methods.
4. Abstract methods we can override through inheritance.
5. Abstract class is base class, concrete class is child class, we can override methods

Syntax:
from abc import ABC
abc :Abstract Base Class
abc : Module Name, ABC ==>Class Name

Abstract Method:
Only function call with empty [Link] class can be inherited by the subclass and
abstract method gets its definition in the subclass.

Syntax:
@abstractmethod

Use of Abstraction:
Abstraction classes are meant to be the blueprint of the other class. An abstract class can be
useful when we are designing large functions. An abstract class is also helpful to provide the
standard interface for different implementations of components.

Example:
from abc import ABC,abstractmethod
class Banking(ABC):#Abstract Class
@abstractmethod
def MonthInterest(self):#Abstract Method
pass
def QuaterlyInterest(self):#Abstract Method
pass
AA=Banking()

Example:
from abc import ABC,abstractmethod
class Banking(ABC):#Abstract Class
@abstractmethod
def MonthInterest(self):#Abstract Method
pass
@abstractmethod
def QuaterlyInterest(self):#Abstract Method
pass

class SBI(Banking):#Concrete Class


def MonthInterest(self):
print("Montly Interest is: 4.5% ")
def QuaterlyInterest(self):
print("Quarterly Interest is: 5.5% ")

SS=SBI()
[Link]()
[Link]()

Example:
from abc import ABC,abstractmethod
class Banking(ABC):#Abstract Class
@abstractmethod
def MonthInterest(self):#Abstract Method
pass
def QuaterlyInterest(self):#Abstract Method
pass

class SBI(Banking):#Concrete Class


def MonthInterest(self):
print("Montly Interest is: 4.5% ")
def QuaterlyInterest(self):
print("Quarterly Interest is: 5.5% ")

class HDFC(Banking):#Concrete Class


def MonthInterest(self):
print("Montly Interest is: 5.5% ")
def QuaterlyInterest(self):
print("Quarterly Interest is: 7.5% ")
SS=SBI()
[Link]()
[Link]()

HH=HDFC()
[Link]()
[Link]()

Example:
from abc import ABC,abstractmethod
class Banking(ABC):#Abstract Class
@abstractmethod
def MonthInterest(self):#Abstract Method
pass
@abstractmethod
def QuaterlyInterest(self):#Abstract Method
pass

class SBI(Banking):#Abstract Class


def MonthInterest(self):
print("Montly Interest is: 4.5% ")

SS=SBI()
[Link]()

NOTE:
1 TypeError: Can't instantiate abstract class SBI with abstract methods QuaterlyInterest
2 Because still it is abstract class, We must implement all abstract class definitions (Override)
in Concrete class.

Example:
from abc import ABC,abstractmethod
class Banking(ABC):#Abstract Class
@abstractmethod
def MonthInterest(self):#Abstract Method
pass
@abstractmethod
def QuaterlyInterest(self):#Abstract Method
pass

class SBI(Banking):#Abstract Class


def MonthInterest(self):
print("Montly Interest is: 5.5% ")

class UBI(Banking):#Concrete Class


def MonthInterest(self):
print("Montly Interest is: 4.5% ")
def QuaterlyInterest(self):
print("Montly Interest is: 6.5% ")
UU=UBI()
[Link]()
[Link]()

Concrete Methods in Abstract Base Classes :


Concrete classes contain only concrete (normal)methods whereas abstract class contains both
concrete methods as well as abstract methods. Concrete class provide an implementation of
abstract methods, the abstract base class can also provide an implementation by invoking the
methods via super().

Example:
from abc import ABC
class BaseClass(ABC): #Abstract Base Class
def BaseMethod(self):
print("AbstractBaseClass")

class Concrete(BaseClass): #Concrete Class


def ConcreteMethod(self):
super().BaseMethod()
print("Subclass With ConcreteMethod")

#Driver code
CC=Concrete()
[Link]()

Multi Tasking:
Executing several tasks simultaneously is the concept of multitasking.

There are 2 types of Multi Tasking


[Link] based Multi Tasking
[Link] based Multi Tasking

[Link] based Multi Tasking:


Executing several tasks simmultaneously where each task is a seperate independent process is
called process based multi tasking.

We can listen audio songs from the system, at the same time we can download a file from the
internet. All these taks are executing simultaneously and independent of each other. It is best
suitable at operating system level.

[Link] based MultiTasking:


Executing several tasks simultaneously where each task is a seperate independent part of the
same program, is called Thread based multi tasking, each independent part is called a Thread.
This type of multi tasking is best suitable at programmatic level.

NOTE: We can reduce execution time and improve performance.!


Example:
import time
def CalSquareNums(numbers):
print("Calculate Square Of Numbers")
for n in numbers:
[Link](0.2)
print('SQUARE:',n*n)

def CalCubeNums(numbers):
print("Calculate Cube Of Numbers")
for n in numbers:
[Link](0.2)
print('CUBE:',n*n*n)

arr = [2,3,4,5,6,7]
stime = [Link]()
CalSquareNums(arr)
CalCubeNums(arr)
print("done in : ",[Link]()-stime)
print("Hah... I am done with all my work now!")

Python Threading or Multithreading:


Threading allows multiple tasks run concurrently or indepedently. It is a separate flow of
execution.
OR
Threads provide a way to improve application performance through parallelism.

Why Threading?
[Link] implement Multimedia graphics
2 Parallel Computation
3 Standardization
4 Parallel I/O (Input/Output)
5 Asynchronous Events
[Link] develop animations
[Link] develop video games
[Link] develop web and application servers..!

Methods of Thread Class


run(): It acts as the entry of the thread
start(): is used for starting the thread by calling the run()
isAlive(): is used to verify whether the still executing or not
getName(): is used for returning the name of a thread
setName(): is used to set the name of the thread

Example:
import threading
print("Current Executing Thread:",threading.current_thread().getName())#mainthread

Example:
import time
import threading

def calc_square(numbers):
print("calculate square numbers")
for n in numbers:
[Link](0.2)
print('square:',n*n)

def calc_cube(numbers):
print("calculate cube of numbers")
for n in numbers:
[Link](0.2)
print('cube:',n*n*n)

arr = [2,3,8,9]
t = [Link]()
t1= [Link](target=calc_square, args=(arr,))
t2= [Link](target=calc_cube, args=(arr,))

[Link]()
[Link]()

[Link]()
[Link]()

print("done in : ",[Link]()-t)
print("Hah... I am done with all my work now!")

Example:
import threading
class Thread1([Link]):
def run(self):
i=1
while i<=5:
print(i)
i=i+1
class Thread2([Link]):
def run(self):
i=1
while i<=5:
print(i)
i=i+1
t1=Thread1()
t2=Thread2()
[Link]()
[Link]()

Setting and Getting Name of a Thread:


Every thread in python has name. It may be default name generated by Python or Customized
Name provided by programmer. We can get and set name of thread by using the following
Thread class methods.
[Link]() ==> Returns Name of Thread
[Link](newName) ==>To set our own name

Note:
Every Thread has implicit variable "name" to represent name of Thread.

Example:
from threading import *
print(current_thread().getName())
current_thread().setName("PyThread")
print(current_thread().getName())
print(current_thread().name)

Thread Identification Number (ident):


For every thread internally a unique identification number is available. We can access this id
by using implicit variable "ident"

Example:
from threading import *
def Test_Thread():
print("MyThread",end=" ")
th=Thread(target=Test_Thread)
[Link]()
print("Main Thread ID:",current_thread().ident)
print("Child Thread ID:",[Link])

Daemon Threads:
The threads which are running in the background are called Daemon Threads.

Example:
Garbage Collector

Example:
from threading import *
print(current_thread().isDaemon()) #False
print(current_thread().daemon) #False

Default Nature:
By default Main Thread is always [Link] for the remaining threads Daemon nature
will be inherited from parent to child.

Example:
from threading import *
def ThTask():
print("ChildThread")
th=Thread(target=ThTask)
print([Link]())
[Link](True)
print([Link]())

Synchronization:
If multiple threads are executing simultaneously then there may be a chance of data
inconsistency problems.
Synchronization means at a time only one Thread The main application areas of
synchronization are
1 Online Reservation system
2 Funds Transfer from joint accounts
3 Online Exams

In Python, we can implement synchronization by using the following


[Link] [Link] [Link]

Locks are the most fundamental synchronization mechanism provided by threading module.
The Lock object can be hold by only one thread at a time.
A Thread can acquire the lock by using acquire() method.
A Thread can release the lock by using release() method.

Example:
from threading import *
lck=Lock()
[Link]()
[Link]()

Example:
import time
import threading
from threading import *
lc=Lock()
def calc_square(numbers):
[Link]()
print("calculate square numbers")
for n in numbers:
[Link](0.3)
print('square:',n*n)
[Link]()

def calc_cube(numbers):
[Link]()
print("calculate cube of numbers")
for n in numbers:
[Link](0.3)
print('cube:',n*n*n)
[Link]()

arr = [2,3,8,9]
t = [Link]()
t1= [Link](target=calc_square, args=(arr,))
t2= [Link](target=calc_cube, args=(arr,))

[Link]()
[Link]()

[Link]()
[Link]()

print("done in : ",[Link]()-t)

RLock:
RLock keeps track of recursion level and hence for every acquire() call compulsory release()
call should be available. i.e the number of acquire() calls and release() calls should be
matched then only lock will be released.

Example:
import time
import threading
from threading import *
rc=RLock()
def calc_square(numbers):
[Link]()
print("calculate square numbers")
for n in numbers:
[Link](0.3)
print('square:',n*n)
[Link]()

def calc_cube(numbers):
[Link]()
print("calculate cube of numbers")
for n in numbers:
[Link](0.3)
print('cube:',n*n*n)
[Link]()

arr = [2,3,8,9]
t = [Link]()
t1= [Link](target=calc_square, args=(arr,))
t2= [Link](target=calc_cube, args=(arr,))

[Link]()
[Link]()

[Link]()
[Link]()

print("done in : ",[Link]()-t)
Difference between Lock and RLock:
Lock:
[Link] object can be acquired by only one thread at a [Link] owner thread also cannot
acquire multiple times.
[Link] suitable to execute recursive functions and nested access calls
[Link] this case Lock object will takes care only Locked or unlocked and it never takes care
about owner thread and recursion level.

RLock:
[Link] object can be acquired by only one thread at a time, but owner thread can acquire
same lock object multiple times.
[Link] suitable to execute recursive functions and nested access calls
[Link] this case RLock object will takes care whether Locked or unlocked and owner thread

Synchronization by using Semaphore:


In the case of Lock and RLock,at a time only one thread is allowed to execute. Semaphore is
advanced Synchronization Mechanism.

Syntax:
s=Semaphore(counter)

Example:
s=Semaphore(3)
In this case Semaphore object can be accessed by 3 threads at a [Link] remaining threads
have to wait until releasing the semaphore.

NOTE:
counter represents the maximum number of threads are allowed to access simultaneously.
The default value of counter is 1.

Example:
import time
import threading
from threading import *
lc=Lock()
s=Semaphore(2)

def calc_square(numbers):
[Link]()
print("Square of Numbers")
for n in numbers:
[Link](0.3)
print('square:',n*n)
[Link]()

s=Semaphore(2)
def calc_cube(numbers):
[Link]()
print("calculate cube of numbers")
for n in numbers:
[Link](0.3)
print('cube:',n*n*n)
[Link]()

arr = [2,3,4,5,6,7]
t = [Link]()

t1= [Link](target=calc_square, args=(arr,))


t2= [Link](target=calc_cube, args=(arr,))

[Link]()
[Link]()

[Link]()
[Link]()

print("done in : ",[Link]()-t)

WORKING WITH PYTHON XML PROCESSING


XML is a portable, open source language that allows programmers to develop applications
that can be read by other applications, regardless of operating system and/or developmental
language.

Creating XML file or Downloading XML file:


We have created a sample XML file that we are going to parse.
Step 1) Goto google type sample xml file
[Link]

How to Create xml file?


<?xml version="1.0"?>
<catalog>
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications
with XML.</description>
</book>
</catalog>

Save the above XML source code with [Link] @ spyder or @PyCharm installed
location..!!

Example1:Reading xml file data..!!


import [Link] as ET
tree=[Link](file='[Link]')
root=[Link]()
for data in root:
print([Link]('id'))

NOTE:
Go to [Link] file, change book as magzine and run the following script.

Example2:Display Book IDs


import [Link] as ET
tree=[Link](file='[Link]')
root=[Link]()

for data in root:


if([Link]=='book'):
print([Link]('id'))

Example3:Display magzine ID..!!


import [Link] as ET
tree=[Link](file='[Link]')
root=[Link]()

for data in root:


if([Link]!='book'):
print([Link]('id'))

Example4: Reading the data from .xml file..!!


import [Link] as ET
tree=[Link](file='[Link]')
root=[Link]()

for books in root:


if([Link]=='book'):
print("Book ID is: "+[Link]('id'))
print("----------------------")
for attr in books:
if([Link]=="author" or [Link]=="title" or [Link]=="price"):
print([Link])
print("***************")

Example5: Writing data in Other file...!!


import [Link] as ET
tree=[Link](file='[Link]')
root=[Link]()

for books in root:


if([Link]=='book'):
fo=open([Link]('id') + '.txt','w')
#print("Book ID is: "+[Link]('id'))
#print("----------------------")
for attr in books:
if([Link]=="author" or [Link]=="title" or [Link]=="price"):
#print([Link])
#print("***************")
[Link]([Link]+' : '+[Link])
[Link]('\n')

WORKING WITH PYTHON JSON


JSON stands for JavaScript Object Notation
JSON is a lightweight data-interchange format
JSON is "self-describing" and easy to understand
JSON is language independent

Why use JSON?


Since the JSON format is text only, it can easily be sent to and from a server, and used as a
data format by any programming language.

JSON Syntax Rules


JSON syntax is derived from JavaScript object notation Syntax:
1 Data is in name/value pairs
2 Data is separated by commas
3 Curly braces hold objects
4 Square brackets hold arrays

JSON Uses JavaScript Syntax


Because JSON syntax is derived from JavaScript object notation.!

In JSON, string values must be written with double quotes:


{ "name":"Raju" }

JSON Files
The file type for JSON files is ".json"
The MIME type for JSON text is "application/json"

JSON vs XML
Both JSON and XML can be used to receive data from a web server.

JSON Example
{"employees":[
{ "firstName":"John", "lastName":"Doe" },
{ "firstName":"Anna", "lastName":"Smith" },
{ "firstName":"Peter", "lastName":"Jones" }
]}

XML Example
<employees>
<employee>
<firstName>John</firstName> <lastName>Doe</lastName>
</employee>
<employee>
<firstName>Anna</firstName> <lastName>Smith</lastName>
</employee>
<employee>
<firstName>Peter</firstName> <lastName>Jones</lastName>
</employee>
</employees>

JSON is Unlike XML Because


1 JSON doesn't use end tag
2 JSON is shorter
3 JSON is quicker to read and write
4 JSON can use arrays

$pip install simplejson


$pip show simplejson
$pip install -U simplejson (for Updating)

Example:
import json
print(dir(json))

Example:
import simplejson
print(dir(simplejson))

Example:
book={}
book['raju']={'name':'raju','address':'Ameerpet HYD','Phone':9866698666}
book['tom']={'name':'tom','address':'5 Green Street NY','Phone':9866612345}
import json
print(type(book))#<class 'dict'>
s=[Link](book)
print(type(s))#<class 'str'>
print(s)

Example:
book={}
book['raju']={'name':'raju','address':'Ameerpet HYD','Phone':9866698666}
book['tom']={'name':'tom','address':'5 Green Street NY','Phone':9866612345}
import json
s=[Link](book)
with open("[Link]",mode='w',encoding='utf-8')as MyFile:
[Link](s)

Example:
book={}
book['raju']={'name':'raju','address':'Ameerpet HYD','Phone':9866698666}
book['tom']={'name':'tom','address':'5 Green Street NY','Phone':9866612345}
import json
s=[Link](book)
with open("[Link]",mode='r',encoding='utf-8')as MyFile:
s=[Link]()
print(s)#String
book=[Link](s)
print(book)#Dictionary
print(type(book))
print(book['raju'])#complete addresss book
print(book['raju']['Phone'])

Example:
book={}
book['raju']={'name':'raju','address':'Ameerpet HYD','Phone':9866698666}
book['tom']={'name':'tom','address':'5 Green Street NY','Phone':9866612345}
import json
print(type(book))
SS=[Link](book)#converting dict to string format
print(type(SS))
try:
with open("[Link]",mode='w',encoding='utf-8') as MyFile:
[Link](SS)
print("DataLoadedSuccessfully..!!")
except IOError:
print("SorryFileUnableToCrete")
finally:
print("FinallyBlockSuccess..!!")

Python-Data Base Conmmunications(PDBC):-


It stores a collection of data. Each database has one or more distinct APIs for creating,
accessing, managing, searching and replicating the data it holds. RDBMS store and manage
huge volume of data.

You can choose the right database for your application. Python Database API supports a wide
range of database servers:
1. MySQL 2. PostgreSQL 3. Microsoft SQL Server
4. Informix 5. Oracle 6. Sybase 7. SQLite
8. MongoDB [Link]

What Can SQL do?


1. SQL can execute queries, retrieve data, insert, update and delete records.
2. SQL can create new databases tables, SP, views and set permissions

Most Important SQL Commands:


SELECT, UPDATE, DELETE, INSERT INTO, ALTER DB, Table CREATE TABLE,
DROP TABLE, INDEX..!!

Step1: Install PYTHON


Step2: Install MySQL (8.0 or later)
[Link]
[Link]
[Link]/download
Step3: MySQL Driver
$pip install mysql-connector
conda install -c anaconda mysql-cnnector-python

Test MySQL Connector


To test if the installation was successfull,
Example:
import [Link]
print(dir([Link]))

Syntax:
mydb = [Link](host="localhost",
user="yourusername", password="yourpassword",database="YourDBName")

Syntax:
mydb = [Link](host="[Link]",
user="yourusername", password="yourpassword",database="YourDBName")

Create Connection
Start by creating a connection to the database.
Use the username and password from your MySQL database:

import [Link]
mydb = [Link](host="localhost",user="root",password="root")
print("MySQL-Server-ConnectedSuccessfully")

Python MySQL Create Database:


To create a database in MySQL, use the "CREATE DATABASE" statement:

Example:
import [Link]
mydb = [Link](host="localhost",user="root",password="root")
mycursor = [Link]()
[Link]("CREATE DATABASE STUDENTS")
print("DataBaseCreatedSuccessfully")

NOTE:
A cursor is a temporary work area created in the system memory when a SQL statement is
executed. A cursor contains information on a select statement and the rows of data accessed
by it.

Check if Database Exists


Check if a database exist by listing all databases, by using the "SHOW DATABASES"
statement:

Example:
import [Link]
mydb = [Link](host="localhost",user="root",passwd="root")
mycursor = [Link]()
[Link]("SHOW DATABASES")
for data in mycursor:
print(data)

To use particular database:


mysql> use student
OR
mysql> connect student

Python-Data Base Conmmunications(PDBC):-


It stores a collection of data. Each database has one or more distinct APIs for creating,
accessing, managing, searching and replicating the data it holds. RDBMS store and manage
huge volume of data.

You can choose the right database for your application. Python Database API supports a wide
range of database servers:
1. MySQL 2. PostgreSQL 3. Microsoft SQL Server
4. Informix 5. Oracle 6. Sybase 7. SQLite
8. MongoDB [Link]

What Can SQL do?


1. SQL can execute queries, retrieve data, insert, update and delete records.
2. SQL can create new databases tables, SP, views and set permissions

Most Important SQL Commands:


SELECT, UPDATE, DELETE, INSERT INTO, ALTER DB, Table CREATE TABLE,
DROP TABLE, INDEX..!!

Step1: Install PYTHON


Step2: Install MySQL (8.0 or later)
[Link]
[Link]
[Link]/download

Step3: MySQL Driver


$pip install mysql-connector
conda install -c anaconda mysql-cnnector-python

Test MySQL Connector


To test if the installation was successfull,
Example:
import [Link]
print(dir([Link]))

Syntax:
mydb = [Link](host="localhost",
user="yourusername", password="yourpassword",database="YourDBName")

Syntax:
mydb = [Link](host="[Link]",
user="yourusername", password="yourpassword",database="YourDBName")

Create Connection
Start by creating a connection to the database.
Use the username and password from your MySQL database:

import [Link]
mydb = [Link](host="localhost",user="root",password="root")
print("MySQL-Server-ConnectedSuccessfully")

Python MySQL Create Database:


To create a database in MySQL, use the "CREATE DATABASE" statement:

Example:
import [Link]
mydb = [Link](host="localhost",user="root",password="root")
mycursor = [Link]()
[Link]("CREATE DATABASE STUDENTS")
print("DataBaseCreatedSuccessfully")

NOTE:
A cursor is a temporary work area created in the system memory when a SQL statement is
executed. A cursor contains information on a select statement and the rows of data accessed
by it.

Check if Database Exists


Check if a database exist by listing all databases, by using the "SHOW DATABASES"
statement:

Example:
import [Link]
mydb = [Link](host="localhost",user="root",passwd="root")
mycursor = [Link]()
[Link]("SHOW DATABASES")
for data in mycursor:
print(data)

To use particular database:


mysql> use student
OR
mysql> connect student

Python MySQL Create Table


Creating a Table
To create a table in MySQL, use the "CREATE TABLE" statement.

Example:
import [Link]
mydb = [Link](host="localhost",user="root",passwd="root",
database='student')
mycursor = [Link]()
[Link]("CREATE TABLE Students (name VARCHAR(255), address
VARCHAR(255))")
print("Table Created Successfully")

mysql> show tables;


mysql> desc student;

Check if Table Exists


You can check if a database exist by listing all tables in your database by using the "SHOW
TABLES" statement:

Example:
import [Link]
mydb = [Link](host="localhost",user="root",passwd="root",
database='student')
mycursor = [Link]()
[Link]("SHOW TABLES")
for data in mycursor:
print(data)

Python MySQL Insert Into Table


To fill a table in MySQL, use the "INSERT INTO" statement.

Example:
import [Link]
mydb=[Link](host="[Link]",
user="root",
passwd="root",
database='student')
mycursor=[Link]()
[Link]("insert into students values(1,'SARA')")
print("DataInsertedSuccessfully")

NOTE:
The above script executed successfully but data not saved in the table, that time we must
'commit' the table..!!

Example:
import [Link]
mydb=[Link](host="[Link]",
user="root",
passwd="root",
database='std')
mycursor=[Link]()
[Link]("insert into emp values(1,'SARA')")
[Link]()
print("DataInsertedSuccessfully")
Insert Data in Multiple Rows
To insert multiple rows into a table, use the executemany() method.

Example:
import [Link]
mydb = [Link](host="localhost",user="root",passwd="root",
database='student')
mycursor = [Link]()
sql = "INSERT INTO students (name, address) VALUES (%s, %s)"
val = [
('Peter', 'Lowstreet 4'),
('Amy', 'Apple st 652'),
('Hannah', 'Mountain 21'),
('Michael', 'Valley 345'),
('Sandy', 'Ocean blvd 2'),
('Betty', 'Green Grass 1'),
('Richard', 'Sky st 331'),
('Susan', 'One way 98'),
('Vicky', 'Yellow Garden 2'),
('Ben', 'Park Lane 38'),
('William', 'Central st 954'),
('Chuck', 'Main Road 989'),
('Viola', 'Sideway 1633')
]
[Link](sql, val)
[Link]()
print("Data Inserted Successfully")

Python MySQL Select From:


To select from a table in MySQL, use the "SELECT" statement:
Select all records from the "students" table, and display the result:

Example:
import [Link]
mydb = [Link](host="localhost",user="root",passwd="root",
database='student')
mycursor = [Link]()
[Link]("SELECT * FROM students")
for data in mycursor:
print(data)

Selecting Columns
To select only some of the columns in a table, use the "SELECT" statement followed by the
column name(s):

Example:
import [Link]
mydb = [Link](host="localhost",user="root",passwd="root",
database='student')
mycursor = [Link]()
[Link]("SELECT name, address FROM students")
myresult = [Link]()
for x in myresult:
print(x)

Using the fetchone() Method:


If you are only interested in one row, you can use the fetchone() method. It will return the
first row.

Example:
import [Link]
mydb = [Link](host="localhost",user="root",passwd="root",
database='student')
mycursor = [Link]()
[Link]("SELECT * FROM students")
myresult = [Link]()
print(myresult)

Python MySQL Where:


Select With a Filter, When selecting records from a table, you can filter the selection by using
the "WHERE" statement:

Example:
import [Link]
mydb = [Link](host="localhost",user="root",passwd="root",
database='student')
mycursor = [Link]()
sql = "SELECT * FROM students WHERE address ='Park Lane 38'"
[Link](sql)
myresult = [Link]()
for data in myresult:
print(data)

Python MySQL Order By


The ORDER BY keyword sorts the result ascending by default. To sort the result in
descending order, use the DESC keyword.

Example:
import [Link]
mydb = [Link](host="localhost",user="root",passwd="root",
database='student')
mycursor = [Link]()
sql = "SELECT * FROM students ORDER BY name"
[Link](sql)
myresult = [Link]()
for x in myresult:
print(x)

ORDER BY DESC: Use the DESC keyword to sort the result in a descending order
Example:
import [Link]
mydb = [Link](host="localhost",user="root",passwd="root",
database='student')
mycursor = [Link]()
sql = "SELECT * FROM students ORDER BY name DESC"
[Link](sql)
myresult = [Link]()
for x in myresult:
print(x)

Python MySQL Delete From By


You can delete records from an existing table by using the "DELETE FROM" statement:

Example:
import [Link]
mydb = [Link](host="localhost",user="root",passwd="root",
database='student')
mycursor = [Link]()
sql = "DELETE FROM students WHERE address = 'Mountain 21'"
[Link](sql)
[Link]()
print([Link], "record(s) deleted")

Python MySQL Update Table:


You can update existing records in a table by using the "UPDATE" statement:
Example:
import [Link]
mydb = [Link](host="localhost",user="root",passwd="root",
database='student')
mycursor = [Link]()
sql = "UPDATE students SET address = 'Canyon 123' WHERE address = 'Valley 345'"
[Link](sql)
[Link]()
print([Link], "record(s) affected")

Python MySQL Drop Table


You can delete an existing table by using the "DROP TABLE" statement
Example:
import [Link]
mydb = [Link](host="localhost",user="root",passwd="root",
database='student')
mycursor = [Link]()
sql = "DROP TABLE customers"
[Link](sql)

Drop Only if Exist


If the the table you want to delete is already deleted, or for any other reason does not exist,
you can use the IF EXISTS keyword to avoid getting an error.
Example:
import [Link]
mydb = [Link](host="localhost",user="root",passwd="root",
database='student')
mycursor = [Link]()
sql = "DROP TABLE IF EXISTS customers"
[Link](sql)

SQLite3
It can be integrated with Python using sqlite3 module, It is default along with Python-2.5.x. It
is famous for its great feature zero-configuration, which means no complex setup or
administration is needed.

Connect To Database
Example:
import sqlite3
conn = [Link]('[Link]')
print("Opened database successfully")

Create a Table
import sqlite3
conn = [Link]('[Link]')
[Link]('''CREATE TABLE COMPANY
(ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
SALARY REAL);''')
print("Table created successfully")
[Link]()

INSERT Operation
import sqlite3
conn = [Link]('[Link]')
[Link]("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \
VALUES (1, 'Paul', 32, 'California', 20000.00 )");

[Link]("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \


VALUES (2, 'Allen', 25, 'Texas', 15000.00 )");
[Link]()
print("Records created successfully")
[Link]()

ORACLE:
It is an ORDBMS developed and marketed by Oracle Corporation.

Following are the four Editions of the Oracle:


Enterprise Edition: It is the most robust and secure edition.

Standard Edition: It provides the base functionality for users that do not require Enterprise
Edition's robust package.
Express Edition (XE): It is the lightweight, free and limited Windows and Linux edition.

Oracle Lite: It is designed for mobile devices.

Step1: Install PYTHON


Step2:Intall Oracle Any Edition (XE Prefered)
Step3:Install Oracle Driver
$pip install cx_Oracle

Update Oracle
$pip install -U cx_Oracle

To View Version of Oracle


$pip show cx_Oracle

Syntax:
import cx_Oracle

Example:
import cx_Oracle
print(dir(cx_Oracle))

Example:
import cx_Oracle
con=[Link]('scott/tiger@localhost')
cursor=[Link]()
[Link]("select * from students")
print([Link]())
[Link]()
[Link]()

Example:
import cx_Oracle
con=[Link]('scott/tiger@localhost')
cursor=[Link]()
[Link]("select * from students")
records=[Link]()
for record in records:
print("Student Name: ",record[0])
print("Address: ",record[1])
print()
[Link]()
[Link]()

Example:
import cx_Oracle
con=[Link]('scott/tiger@localhost')
cursor=[Link]()
[Link]("select * from students")
records=[Link]()
print(records)

Example:
import [Link]
con = [Link](host="localhost",user="root",passwd="root",
database='student')
cursor = [Link]()
[Link]("SELECT * FROM students")
records = [Link]()
print(records)

Python Object Serialization


What is Pickle?
Pickle is an inbuilt python library for serializing and de-serializing Python object.
OR
Pickle is used for serializing and de-serializing Python object structures, also called
marshalling or flattening.
OR
Pickling is used to store python objects. This means things like lists, dictionaries, class
objects, and more.

Features of Serialization:
1. Python Objects convert into Byte Stream format
2. Over a network byte stream easily transfor
3. Highly secured, good performance
4. Machine easily understandable & Convertable

Storing data with pickle


You can pickle objects with the following data types:
Booleans, Integers, Floats, Complex numbers, Strings, Tuples, Lists, Sets, and Dictionaries
etc..!!

Serialization:
It is the process of converting a object hierarchy into a stream of bytes to store in a file.

dump method:
Saves the object to the file stream with the optional parameter of protocol.

Syntax:
dump(object,file,protocol)

Example: (Pickling)
import pickle
data={'a':[1,2,3,4],'b':'NareshIT',(1,2):[1,2]}
with open("[Link]",mode="wb") as FPK:
[Link](data,FPK)
print("PickleFileCratedSuccessfully")
print(data)
del data
print(data)

Example:
import pickle
PyData={'a':[1,2,3,4],'b':"NareshIT",'c':(1,2)}
try:
with open("[Link]",mode='wb') as FPK:
[Link](PyData,FPK)
print("DataSerializedSuccessfully...!!")
except IOError:
print("SorryDataUnableToSerialize")
finally:
print("FinallyBlockSuccess")

Unpickling:
It is the inverse of Pickling process where a byte stream is converted into an object hierarchy.

load method:
Loads the next object in the file stream and returns the object

Syntax:
[Link]()

Example:(De-Serialization)
import pickle
data ={'a':[1,2,3],'b':'NareshIT',(1,2):[1,2]}
with open("[Link]",mode='wb') as FPK:
[Link](data,FPK)
del data
with open("[Link]",mode='rb')as FPK:
data=[Link](FPK)
print(data)

Example:
import pickle
try:
with open("[Link]",mode='rb') as FPK:
PyData=[Link](FPK)
print(PyData)#This is printing in Object format
print("DataDe-SerializedSuccessfully...!!")
except IOError:
print("SorryDataUnableToDeserialize")
finally:
print("FinallyBlockSuccess")

Pickle Limitations:
1. It doesn't save objects code, only it's attributes values
2. It cannot store file handles or connection sockets
PYTHON DJANGO WEB FRAMEWORK
Define framework?
A framework, is a platform for developing software applications.

Web Framework (WF)/WAF Web App Framework


It is a software framework that is designed to support the development of web applications.

What is MEAN/MERN Stack:


MongoDB, [Link], AngularJS, and [Link]
MongoDB, Express, ReactJS, [Link]

What is OpenStack?
OpenStack is a free and open-source software platform for cloud computing, It is
infrastructure-as-a-service(IaaS). Written in Python by Apache.

What is "Full-Stack"?
There are two main components of a website:
1. The Front-End
2. The Back-End

[Link]:It is what you see as user on the website-UI


1. HTML & HTML5 2. CSS & CSS3
3. JavaScript 4. jQuery 5. Bootstrap 6. AngularJS

2. Back-End:It is the technology used to actually decide what to show you on the Front-End.
It has maily the following three components:
1. The Language (PYTHON)
2. The framework (Django)
3. The Database (SQLite)

DJANGO
It is a high-level Python MVT web framework.

History of Django
2003-Started by Adrian Holovaty&Simon Willison as an internal project 2005 - Released
July 2005 & named it Django, after the jazz guitarist Django Reinhardt.

Features of Django: ([Link]


1. Ridiculously fast.
2. Fully loaded.
3. Reassuringly secure.
4. Exceedingly scalable.
5. Incredibly versatile.

In PYTHON Popular Web Frameworks are:


1 Django 2 Flask 3 Pyramid 4 Falcon 5. Bottle

Step1 : Installing python


Step2: installing django
$ pip install django==3.0.5

Checking Django Installation:


import django
print([Link])
$ pip show django

Getting Started with Django:


1 Creating the first Project
Syntax:
$django-admin startproject projectname

Example:
$django-admin startproject BFSI
$cd BFSI
$ tree /f

[BFSI]/ <== Project root


├── [BFSI]/ <== Django root
│ ├── __init__.py
│ ├── [Link]
│ ├── [Link]
│ ├── [Link]
│ └── [Link]
└── [Link]

__init__.py:
These files are required to make Python treat as packages

[Link]:
It is the central configuration for all Django projects

[Link]
In [Link], the most important thing is the "urlpatterns" tuple. It's where you define the
mapping between URLs and views.

[Link]
Web Server Gateway Interface is a simple calling convention for web servers to forward
requests to web applications.

[Link]
It does the same thing as django-admin but takes care of a few things for you.

How to run Django Project:


$python [Link] runserver
Server will run with few warnings as well.
Open any Web browser , Check address, [Link]:8000

Python Turtle Module:


[Link]
“Turtle” is a python feature like a drawing board, which lets you command a turtle to draw all
over it! You can use functions like [Link](...) and [Link](...) which can move the
turtle around.

1 Import the turtle module


2 Create a turtle to control.
3 Draw around using the turtle methods.
4 Run [Link]().

Turtle motion
forward() | fd() backward() | bk() | back()
right() | rt() left() | lt()
goto() | setpos() | setposition()
setx() sety()
setheading() | seth()
home() circle()
dot() stamp() clearstamp()
clearstamps() undo() speed()

Example:
import turtle
star = [Link]()
for i in range(50):
[Link](50)
[Link](144)
[Link]()

Example:
import turtle
colors = ['red', 'purple', 'blue', 'green', 'orange', 'yellow']
t = [Link]()
[Link]('black')
for x in range(360):
[Link](colors[x%6])
[Link](x/100 + 1)
[Link](x)
[Link](59)

Turtule Star:
from turtle import *
color('red', 'yellow')
begin_fill()
while True:
forward(200)
left(170)
if abs(pos()) < 1:
break
end_fill()
done()
Example:
import turtle
painter = [Link]()
[Link]("blue")
for i in range(50):
[Link](50)
[Link](123) # Let's go counterclockwise this time
[Link]("red")
for i in range(50):
[Link](100)
[Link](123)
[Link]()

Example:
import turtle
ninja = [Link]()
[Link](10)
for i in range(180):
[Link](100)
[Link](30)
[Link](20)
[Link](60)
[Link](50)
[Link](30)
[Link]()
[Link](0, 0)
[Link]()
[Link](2)
[Link]()

Example:
import turtle #Outside_In
wn = [Link]()
[Link]("light green")
[Link]("Turtle")
skk = [Link]()
[Link]("blue")

def sqrfunc(size):
for i in range(4):
[Link](size)
[Link](90)
size = size-5

sqrfunc(146)
sqrfunc(126)
sqrfunc(106)
sqrfunc(86)
sqrfunc(66)
sqrfunc(46)
sqrfunc(26)

Example:
import turtle
loadWindow = [Link]()
[Link](2)

for i in range(100):
[Link](5*i)
[Link](-5*i)
[Link](i)

[Link]()

Example:
import turtle
colors = ['red', 'purple', 'blue', 'green', 'orange', 'yellow']
t = [Link]()
[Link]('black')
for x in range(360):
[Link](colors[x%6])
[Link](x/100 + 1)
[Link](x)
[Link](59)

Tkinter
Introduction to GUI programming
Tkinter(Tk interface) is the standard Python interface to the Tk-GUI toolkit. Tk & Tkinter are
available on all platforms. Graphical User Interface allows a user to interact with a computer
program using a pointing device that manipulates small pictures on a computer screen.

GUI Programming in Python:


There are many ways to develop GUI based programs in Python. Top 5 Python GUI
Libraries:
[Link]
2. PyQT5
3. PySide
4. Kivy
5. wxPython

Tkinter module:
It is the default Graphical User Interface library for Python. Python once combined with
Tkinter provides a quick and simple graphical program applications. The first graphical user
interface toolkit is Tk, Tkinter stands for Tk interface.

Tkinter in Python helps in creating GUI Applications with a minimized steps of coding.
Tkinter is the only library that is built-in into Python's Standard Library. It is cross-platform,
we can write same code on any platform like Windows, Unix, Linux, Mac etc. It is a
lightweight, simple and efficient module.

Tk, TCL & Tkinter


Tool Command Language. Tk is very popular thus it has been ported to a variety of other
scripting languages, including Perl, Ruby and Python. Tkinter provides us a faster and
efficient way in order to build useful apps .

Setup/Configure Tkinter
Explicitly no need to install Tkinter. It is standard library in Python.

Example:
import tkinter as tk
abc = [Link]() #abc indicates name of the main window object
[Link]()# It is used to start the application

Example:
from tkinter import * #It import all of the funtions and varibales from tkinter package
abc=Tk() #tk constructor method
Label(abc,text="Hello PYTHON GUI").pack() #Geometry management method
[Link]()

PYTHON Tkinter Components / Widgets:


1 Button 2 Canvas 3 Checkbutton
4 Entry 5 Frame 6 Label
7 Listbox 8 Menubutton 9 Menu
10 Message 11 Radiobutton 12 Scale
13 Scrollbar 14 Text 15 Spinbox 16 tkMessageBox

Tkinter Button
It is used to add buttons in a Python applications. These buttons are display different
components like text or images that convey the purpose of the buttons.

Syntax
w = Button ( master, option=value, ... )

Example:
from tkinter import *
x = Tk()
[Link]("250x150")
but = Button(x,text = "SampleButton")
[Link]()
[Link]()

Example:
import tkinter
from tkinter import *
from tkinter import messagebox
x = Tk()
[Link]("350x200")
def click():
[Link]("Hey", "Clicked on Green Button")
Btn1 = Button(x, text="YELLOW", pady=10)
Btn2 = Button(x, text="BLUE", pady=10)
# Adding click Event to the following Button
Btn3 = Button(x, text="GREEN", command=click,pady=10)
[Link](side = LEFT)
[Link](side = RIGHT)
[Link](side = TOP)
[Link]()

Example:
from tkinter import *
from tkinter import ttk
root=Tk()
button=[Link](root,text="Click ME.!!")
[Link]()
def callback():
print("ClickME")
[Link](command=callback)
Ctrl+Z (Exit)
[Link]()
[Link](['disabled'])
[Link](['disabled'])
[Link](['!disabled'])
lg=PhotoImage(file='E:\HTML_Tutorials\HTML5\Images\[Link]')
[Link](image=lg,compound=LEFT)
slogo=[Link](3,3)
[Link](image=slogo)

Python Tkinter Radio-Button:


This widget is used to implement one-of-many selection in the Python applications. It shows
multiple choices to the user out of which, the user can select only one out of them. We can
associate different methods with each of the radio-button.

We can display the multiple line text or images on the radio-buttons. To keep track the user's
selection the radio-button, it is associated with a single variable. Each button shows a single
value for that particular variable.

Syntax
w = Radiobutton(top, options)

Example:
from tkinter import *
from [Link] import *
win = Tk()
[Link]("250x250")
var = StringVar(win)
options = {" Option_1" : "A",
"Option_2" : "B",
"Option_3" : "C",
"Option_4" : "D"
}
for (txtt, vall) in [Link]():
Radiobutton(win,text=txtt, variable=var, value=vall).pack(side=TOP, ipady = 5)
mainloop()

Python Tkinter Checkbutton


The Check-Button is used to track the user's choices provided to the application. In other
words, we can say that Check-Button is used to implement the on/off selections. It is a
standard widget in Tkinter library..

The Checkbutton can contain the text or images. The Checkbutton is mostly used to provide
many choices to the user among which, the user needs to choose the one. It generally
implements many of many selections.

Syntax
w = checkbutton(master, options)

Example:
from tkinter import *
top = Tk()
[Link]("100x100")
check1 = IntVar()
check2 = IntVar()
check3 = IntVar()
ckbtn1 = Checkbutton(top, text = "PYTHON", variable = check1)
ckbtn2 = Checkbutton(top, text = "CYTHON", variable = check2)
ckbtn3 = Checkbutton(top, text = "JYTHON", variable = check3)
[Link]()
[Link]()
[Link]()
[Link]()

ComboBox:
It is another widget from tkinter to select a single item at a time from group of items. It is
popularly known as drop down box. It is standard widget in Python Tkinter library.

Syntax:
w = Combobox(master, option=value, ...)

Example:
from tkinter import *
from tkinter import ttk
x = Tk()
[Link]("150x130")
fframe = Frame(x)
[Link]()
vvlist = ["PYTHON", "Machine Learning", "Data Science","CYTHON", "Django"]
Drop=[Link](fframe, values = vvlist)
[Link]("Select Required Tech.")
[Link](padx = 5, pady = 5)
[Link]()

List Box:
It is another tkinter widget, It is used to display a list of options for the user to select any
number of items at a time.
Syntax:
w = Listbox ( master, option, ... )

Example:
from tkinter import *
x = Tk()
[Link]("180x200")
frame = Frame(x)
[Link]()
label = Label(x,text = "Drop of Technologies.")
[Link]()
lbox = Listbox(x)
[Link](1,"PYTHON")
[Link](2, "CYTHON")
[Link](3, "JYTHON")
[Link](4, "IRONPYTHON")
[Link](5, "RUBYPYTHON")
[Link](6, "PYJAVASCRIPT")
[Link]()
[Link]()

What is Data Science?


Data science, also known as data-driven science, is an interdisciplinary field about scientific
methods, processes, and systems to extract knowledge or insights from data in various forms.

Standard Lifecycle of Data Science Projects


Data Science Project lifecycle has 6 steps
1 Business Understanding
2 Data Understanding
3 Data Preparation
4 Modelling
5 Evaluation
6 Deployment

Python Eco System for Data Science


Python's popularity for data science is largely due to the strength of its core libraries
1. NumPy 2. SciPy 3. Pandas
4. Matplotlib 5. Seaborn
Best Book: Doing Data Science
Authors: Cathy O'Neil, Rachel Schutt

What is Machine Learning?


Machine Learning is a type of Artificial Intelligence that provides the computers the ability to
learn without being explicitly programmed.
OR
Machine learning is when machine learns to program itself!

Different machine learning techniques


Machine learning uses two types of techniques:
1. Supervised Learning
Which trains a model on known input and output data so that it can predict future outputs.
It is basically classified into the following two types:
a. Classification
b. Regression

2. Unsupervised Learning
Group and interpret data based only on input data.
a. Clustering
b. Principal Component Analysis

Applications Of Machine Learning


1. Social Media 2. Search Engines
3. Health Care 4. Banking & Finance
5. Legal Services 6. Retail
7. Public Services 8. Security

Top 5 Machine Learning Libraries


1. TensorFlow 2. Scikit -Learn (SKLearn)
3. Keras 4 NLTK 5. PyTorch

Machine Learning Mastery with PYTHON==> Jason Brownlee


Introduction to Machine Learning with Python==>Andreas C. Müller & Sarah Guido

What is Deep Learning?


Deep learning is a machine learning technique that teaches computers to do what comes
naturally to humans.
OR
Deep learning is a subset of machine learning in Artificial Intelligence.

TOP 5 Deep Learning Frameworks:


1 Theano2 TensorFlow 3 Lasagne
4 Keras 5 MXNet

Deep Learning with Python==>Nikhil Ketkar


Deep Learning with Python==>Francois Chollet

Artificial Intelligence
AI makes it possible for machines to learn from experience.
OR
AI is the simulation of human intelligence by machines.

Applications of AI
1. Gaming
2. Natural Language Processing and translation
3. Expert Systems 4. Vision Systems
5. Speech Recognition
6. Handwriting Recognition
7. Intelligent Robots
8. Data mining, Web Crawler
9. Vision, Virtual Reality

AI A Modern Approach ==> Peter Norvig and Stuart J. Russell

What is IoT?
A network of internet-connected objects able to collect and exchange data using embedded
sensors.

IoT Companies
Google, Amazon, AT&T, Cisco, IBM, Honeywell, Microsoft, Apple, Android etc............

IoT Areas:
1. Smart Health 2. Smart Living
3. Smart Industry 4. Animal Tracking
5. Smart Agriculture 6. Smart Homes
7. Smart Transport 8. Smart Energy
8. Smart Cities

Raspberry Pi: (From Python)


It is a credit-card-sized computer that plugs into your TV and a keyboard. It is a capable little
computer which can be used in electronics projects.

Best Book for: IoT-with-python==>Gaston-c-hillar

PYTHON-SELENIUM TEST AUTOMATION

Software Testing can be done in two ways.


a) Manual Testing
Testing an Application by giving manually inputs and observing manually outputs...!!
b) Test Automation
Testing an application with the help of third-party testing tools.

i) Advantages of Manual Testing


1 No Test Tool cost
2 No Environment Limitations
3 Useful for Short term projects
4 Programming knowledge is not required.

Disadvantages:
1 It takes MoreTime/MoreResources/Both
2 Comparing large amount of data is difficult
3 Less Test Coverage, Less Accuracy

Advantages of Test Automation


1 Fast: Test Tool is faster in execution
2 Reusable: Sanity Tests, Regression Tests
3 Repeatable: Data Driven Tests
4 Reliable:
5 Programmable:

Disadvantages
1 Not suitable for short term projects
2 100% Test automation is not possible
3 All types of testing are not possible
4 Lack of knowledge, Debugging issues

Types of Testing-Tools
i. Functional/Regression Test Tools
ii. Performance Test Tools
iii. Mobile Test Tools
iv. Test Management Tools
v. Defect Management Tools

Functional and Regression Test Tools


Test Tools for Functional ion Testing
1. Selenium (Open Source Tool)
2. UFT/QTP (Commercial Tool)
3. RFT (Commercial Tool)
4. SoapUI (Open Source Tool)
5. SilkTest (Commercial Tool)

Performance Test Tools


Popular Test Tools for Performance Testing
1. LoadRunner (Commercial Tool)
2. JMeter (Open Source Tool)
3. Silk Performer (Commercial Tool)
4. WebLoad(Commercial Tool)

Mobile Test Tools


Popular Test Tools for Mobile Testing
Mobile Software Applications
a. Native Applications b. Web Applications
c. Hybrid Application
1. Appium (Open Source Tool)
2. Silk Mobile (Commercial Tool)

Introducing Selenium and Features:


> It is a suite of software tools to automate web browsers
> It is a open source software
> Selenium supports various Operating environments (Windows, UNIX, Macintosh etc...)
> Selenium supports various browsers (Mozilla firefox, IE, Chrome, Opera, Safari etc...)
> Selenium supports various Programming and scripting languages to design and execute
tests.
PYTHON, C#, PHP, Perl, Java, Ruby, JavaScript

Limitations of Selenium
> Since it is open source tool, No reliable Technical support
> It doesn't support Desktop Applications/Windows Applications
> Difficult to use, New features may not work properly

History of the Selenium


1. In 2004 invented by Jason R. Huggins & team.
2. Original name is JavaScript Functional Tester [JSFT]
3. Open source browser based integration test framework built originally by Thoughtworks
4. 100% Javascript and HTML
5. Designed to make test writing easy
6. Selenium WebDriver launched at Google in 2006
7. In 2008 Selenium WebDriver merged with selenium RC, called as Selenium 2.0

Selenium License:
All selenium projects released under the license of Apache 2.0
Anybody can download and use

iv) Selenium supporting platforms/Environments


a) Application Environment
1) It doesn't support CUI based Application
2) It doesn't support I-tier, II-Tier (Desktop Applications or Windows based Applications)
3) It supports Web Applications
4) Mobile Applications which are having web forms

Web Browsers
1) IE 2) Firefox 3) Chrome 4) Safari 5) Opera ...!

Programming / Scripting Languages


1) PYTHON 2) C# 3) PHP 4) JAVA 5) PERL 6) RUBY
7) JavaScript

v) Selenium Suite of Tools


Block Diagram for Selenium suite:

a) Selenium IDE:
It is Firefox Add on , It is prototyping tool

b) Selenium RC (Remote Control):


It is Client-Server(Two-Tier) Applications:
Features:
1 Import Test Cases from Selenium IDE
2 It supports various browsers (IE, Firefox, Chrome, Safari..)
3 It supports various Programming/Sripting Lang.
4 Random Test execution is possible

c) Selenium WebDriver
1 It is an interface
2 Faster in Test Execution
3 Supports any Programming/Scripting Language(s)

d) Selenium Grid
Selenium Grid 1.0 supports Selenium RC tests only
Selenium Grid 2.0 supports WebDriver tests
1 It is used to grouping Tests
2 It is used execute Tests in parallel

Configure Selenium
1 Download and Install PYTHON
2 Download and Install PYCHARM
3 Download WebDriver Interface
4 Download and install Firebug and Firepath in Mozilla browser
5 Download browser drivers also

$pip install -U selenium


$pip show selenium
$pip install urllib3
$pip show urllib3

Why to choose Python over Java in Selenium


1. Java programs tend to run slower compared to Python programs.
2. Java uses traditional braces to start and ends blocks, while Python uses indentation.
3. Java is static typing, Python is dynamically typed.
4. Python is simpler and more compact compared to Java.
5. PYTHON Syntax is simple, JAVA Syntax is complex

Syntax:
import selenium

Syntax:
from selenium import webdriver

Example:
import selenium
print(dir(selenium))

Example:
from selenium import webdriver
print(dir(webdriver))

[Link]

Example1:To Open a Website


from selenium import webdriver
browser = [Link]()
[Link]('[Link]

Example2: For Facebook Login Test Script:


from selenium import webdriver
from [Link] import Keys
user = "ksrajupy@[Link]"
pwd = "*********"
driver = [Link]()
[Link]("[Link]
assert "Facebook" in [Link]
elem = driver.find_element_by_id("email")
elem.send_keys(user)
elem = driver.find_element_by_id("pass")
elem.send_keys(pwd)
elem.send_keys([Link])
[Link]()

Naresh i Technologies, HYDERABAD, 040-23746666

Compiled by SUBBA RAJU Data Scientist


GRAND REVIEW ON CORE

PYTHON

1 Output of the following script


pylist=[1,2,3,4,[5,6,7,8,[9,10,11,12,[13,14,15,16]]]]
print(pylist)
print(pylist[4][4][4][3])
2 Output of the following script
r = lambda q: q * 2; s = lambda q: q * 3
x = 3; x = r(x);x = s(x);x = r(x)
print (x,x)
3. Output of the following script
var1 = &#39;Hello NareshIT!&#39;
var2 = &quot;NareshITHYD&quot;
print(&quot;var1[0]: &quot;, var1[0])
print(&quot;var2[1:5]: &quot;, var2[1:5])
4 What is the value of this expression: bin(10-2)+bin(12^4)
5 What is the output of print([&#39;hello&#39;, &#39;morning&#39;][bool(True)])
6 Count the Number of Vowels in a String
7 Calculate the Number of Digits and Letters in a String
8 Check a Number is a Prime Number or Not
9 Output of the following
for i in range(10):
if i == 5:
break
else:
print(i)
else:
print(&quot;Here&quot;)
10 Output of the statement is: print(&#39;my_string&#39;.isidentifier())
11 What is the output of the code shown below?
l=[2, 3, [4, 5]]
l2=[Link]()
l2[0]=88
print(l)
print(l2)
12 What is the output of the following code?
l1=[10, 20, 30]
l2=[-10, -20, -30]
l3=[x+y for x, y in zip(l1, l2)]
print(l3)

Naresh i Technologies, HYDERABAD, 040-23746666

Compiled by SUBBA RAJU Data Scientist


13 What is the output of the code shown below?
l1=[1,2,3]
l2=[4,5,6]
l3=[7,8,9]
for x, y, z in zip(l1, l2, l3):
print(x, y, z)
14 What is the output of the code shown below?
a={}
print([Link]([1,2,3],&quot;check&quot;))
15 What is the output of the following code?
a={1,2,3}
b=[Link](4)
print(b)
16 What is the output of the following piece of code?
a=(2,3,1,5);[Link]();print(a)
17 What is the output of the following piece of code?
a=list((45,)*4)
print((45)*4)
print(a)
18 What is the output of the following piece of code?
print([[i+j for i in &quot;abc&quot;] for j in &quot;def&quot;])
19 What is the output of the snippet of code shown below?
x=set(&#39;abcde&#39;)
y=set(&#39;xyzbd&#39;)
x.difference_update(y)
print(x)
print(y)
20 Python Program to Reverse a Given Number
21 Python Program to Find the Sum of Digits in a Number
22 Python Program to Check if a Number is a Palindrome
23 Python Program to Print an Inverted Star Pattern
*****
****
***
**
*
24 Python Program to Swap the First and Last Value of a List
25 Print the multiplication table for given number with specific range[rows]

Naresh i Technologies, Hyderabad

Prepared By Subba Raju Data Scientist


1 Python Program to Reverse a Given Number
2 Python Program to Print an Inverted Star Pattern
*****
****
***
**
*
3 What is the output of the following?
x = [&#39;ab&#39;, &#39;cd&#39;]
for i in x:
[Link]()
print(x)
a) [‘ab’, ‘cd’]
b) [‘AB’, ‘CD’]
c) [None, None]
d) none of the mentioned
4 What is the output of the following?
x = &quot;abcdef&quot;
i = &quot;a&quot;
while i in x:
x = x[:-1]
print(i, end = &quot; &quot;)
a) i i i i i i
b) a a a a a a
c) a a a a a
d) none of the mentioned
5 What is the output of the following?
x = &#39;abcd&#39;
for i in range(len(x)):
x = &#39;a&#39;
print(x)
a) a
b) abcd abcd abcd
c) a a a a
d) none of the mentioned
6 What is the output of the following?
for i in &#39;&#39;.join(reversed(list(&#39;abcd&#39;))):
print (i)
a) a b c d

Naresh i Technologies, Hyderabad

Prepared By Subba Raju Data Scientist


b) d c b a
c) error
d) none of the mentioned
7 What is the output of the following?
for i in range(10):
if i == 5:
break
else:
print(i)
else:
print(&quot;Here&quot;)
a) 0 1 2 3 4 Here
b) 0 1 2 3 4 5 Here
c) 0 1 2 3 4
d) 1 2 3 4 5
8 What is the output of the following?
string = &quot;my name is x&quot;
for i in &#39; &#39;.join([Link]()):
print (i, end=&quot;, &quot;)
a) m, y, , n, a, m, e, , i, s, , x,
b) m, y, , n, a, m, e, , i, s, , x
c) my, name, is, x,
d) error
9 What is the output of the following?
print(&#39;*&#39;,&quot;abcde&quot;.center(6),&#39;*&#39;,sep=&#39;&#39;)
a) * abcde *
b) * abcde *
c) *abcde *
d) * abcde*
10 What is the output of the following?
print(&quot;abc. DEF&quot;.capitalize())
a) abc. def
b) ABC. DEF
c) Abc. def
d) Abc. Def
11 What is the output of the following?
print(&#39;a@ 1,&#39;.islower())
a) True

Naresh i Technologies, Hyderabad


Prepared By Subba Raju Data Scientist
b) False
c) None
d) Error
12. Which of the following is modes of both writing and reading in
binary format in file.?
a) wb+
b) w
c) wb
d) w+
13. How do you change the file position to an offset value from the
start?
a) [Link](offset, 0)
b) [Link](offset, 1)
c) [Link](offset, 2)
d) none of the mentioned
14. Which of the following is not a valid namespace?
a) Global namespace
b) Public namespace
c) Built-in namespace
d) Local namespace
15. Which of the following can be used to create a symbolic link?
a) [Link]()
b) os.symb_link()
c) [Link]()
d) [Link]()
16. Overriding means changing behavior of methods of derived class
methods in the base class. Is the statement true or false?
a) True
b) False
17 What is the output of the following piece of code?
class A:
def one(self):
return [Link]()
def two(self):
return &#39;A&#39;
class B(A):
def two(self):
return &#39;B&#39;
obj2=B()
print([Link]())

Naresh i Technologies, Hyderabad

Prepared By Subba Raju Data Scientist


a) A
b) An exception is thrown
c) A B
d) B
18. Which function overloads the // operator?
a) __flrdiv__()
b) __ceildiv__()
c) __floordiv__()
d) __truediv__()
19 What is the output of the following piece of code?
class A:
def __init__(self):
self._x = 5
class B(A):
def display(self):
print(self._x)
def main():
obj = B()
[Link]()
main()
a) Error, invalid syntax for object declaration
b) Nothing is printed
c) 5
d) Error, private class member can’t be accessed in a subclass
20. Which of the following blocks will be executed whether an
exception is thrown or not?
a) except
b) else
c) finally
d) assert
21 What is the output of the following piece of code?
def test(i,j):
if(i==0):
return j
else:
return test(i-1,i+j)
print(test(4,7))

Naresh i Technologies, Hyderabad

Prepared By Subba Raju Data Scientist


a) 13
b) 7
c) Infinite loop
d) 17
22 What is the output of the following piece of code?
def fun(n):
if (n &gt; 100):
return n - 5
return fun(fun(n+11));
print(fun(45))
a) 50
b) 100
c) 74
d) Infinite loop
23 What is the output of the following code?
class fruits:
def __init__(self):
[Link] = 100
self.__bags = 5
def display(self):
print(self.__bags)
obj=fruits()
[Link]()
a) The program has an error because display() is trying to print a private
class member
b) The program runs fine but nothing is printed
c) The program runs fine and 5 is printed
d) The program has an error because display() can’t be accessed
24. What is the output of the code shown below?
def f1(a,b=[]):
[Link](a)
return b
print(f1(2,[3,4]))
a) [3,2,4]
b) [2,3,4]
c) Error
d) [3,4,2]
25. What is the output of the following piece of code?

Naresh i Technologies, Hyderabad

Prepared By Subba Raju Data Scientist


class stud:
‘Base class for all students’
def __init__(self, roll_no, grade):
self.roll_no = roll_no
[Link] = grade
def display (self):
print(&quot;Roll no : &quot;, self.roll_no, &quot;, Grade: &quot;, [Link])
print(student.__doc__)
a) Exception is thrown
b) __main__
c) Nothing is displayed
d) Base class for all students

Example:1 To display odd number in the given numerical integer string


pylist=[1,2,3,4,5,6,7,8,9]
sum=0
for x in pylist:
if x%2!=0:
print("odd value:",x)
sum=sum+x
print("the sum is:",sum)
solution:
odd value: 1
odd value: 3
odd value: 5
odd value: 7
odd value: 9
the sum is: 25

Example:1 To display odd number in the given numerical integer string by using list
comprehension
pylist=[1,2,3,4,5,6,7,8,9]
print([x if x%2!=0 else 'odd value is' for x in range(10)])
solution:
['odd is', 1, 'odd is', 3, 'odd is', 5, 'odd is', 7, 'odd is', 9]

Example:1 To display odd number in the given numerical integer string by using filter
pylist=[1,2,3,4,5,6,7,8,9]
odd=list(filter(lambda x:x%2!=0,pylist))
print("odd values are",odd)
print("total sum is",sum(odd))
solution:
odd values are [1, 3, 5, 7, 9]
total sum is 25
"""Example:2 To display even number in the given numerical integer string
pylist=[1,2,3,4,5,6,7,8,9]
print([x if x%2==0 else 'even value is' for x in pylist])
solution:
['even is', 1, 'even is', 3, 'even is', 5, 'even is', 7, 'even is', 9]

Example:2 To display even number in the given numerical integer string


pylist=[1,2,3,4,5,6,7,8,9]
even=list(filter(lambda x:x%2==0,pylist))
print("even values are",even)
print("total sum is",sum(even))
solution:
odd values are [2,4,6,8]
total sum is 20"""

Example 2: to print first n even numbers'


n=int(input("enter value:"))
for x in range(1,n+1):
if x%2==0:
print('even is',x)
solution:
enter value:10
even is 2
even is 4
even is 6
even is 8
even is 10

'''Example:2 To display even number in the given numerical integer string


pylist=[1,2,3,4,5,6,7,8,9]
sum=0
for x in pylist:
if x%2==0:
print("even value:",x)
sum=sum+x
print("the sum is:",sum)
even value: 2
even value: 4
even value: 6
even value: 8
the sum is: 20'''
Example 2: to print first n even numbers'
n=int(input('enter the n value:'))
print('the even numbers between "1" and',n,'are:')
for x in range(1,n+1,1):
if (x%2==0):
print(x)

solution:
enter the n value:10
the even numbers between "1" and 10 are:
2
4
6
8
10
example 3:to sum first even numbers'
n=int(input("enter number:"))
sum=0
for x in range(1,n+1):
if x%2==0:
sum=sum+x
print(sum)
solution:
enter number:10
30
Example:5 To print first 'n' odd numbers
n=int(input("enter any value:"))
for x in range(n):
if x%2!=0:
print("odd value:",x)
solution:
enter any value:10
odd value: 1
odd value: 3
odd value: 5
odd value: 7
odd value: 9

Example:6 To print first sum odd numbers


sum=0
n=int(input("enter any value:"))
for x in range(n):
if x%2!=0:
print("odd value:",x)
sum=sum+x
print(sum)
solution:
enter any value:10
odd value: 1
odd value: 3
odd value: 5
odd value: 7
odd value: 9
25
Example 7:To find sum of first n natural numbers'
n=int(input("enter any value:"))
sum=0
for x in range(0,n+1):
sum=sum+x
print("first n natural numbers",sum)
solution:
enter any value:10
first n natural numbers 55
Example 8: To print natural numbers between given range n1:n2'
n=int(input("enter any value:"))
n1=int(input("enter any value:"))
for x in range(n,n1+1):
print(x)
solution:
enter any value:10
enter any value:20
10
11
12
13
14
15
16
17
18
19
20
Examples 9:Print the multiplication table for given number with specific range[rows]'
n=int(input("enter the table:"))
n1=int(input("enter the table rows:"))
for x in range(1,n1+1):
z=n*x
print("%d*%d=%d"%(n,x,z))
enter the table:7
enter the table rows:10
7*1=7
7*2=14
7*3=21
7*4=28
7*5=35
7*6=42
7*7=49
7*8=56
7*9=63
7*10=70
Examples 9:Print the multiplication table for given number with specific range[rows]'
n=int(input("enter the table:"))
n1=int(input("enter the table rows:"))
print([("%d*%d=%d"%(n,x,n*x)) for x in range(1,n1+1)])
enter the table:10
enter the table rows:10
['10*1=10', '10*2=20', '10*3=30', '10*4=40', '10*5=50', '10*6=60', '10*7=70', '10*8=80',
'10*9=90', '10*10=100']

Examples10:multiplication tables between some ranges


n=int(input("enter number of rows"))
n1=int(input("enter value:"))
n2=int(input("enter value:"))
for x in range(n1,n2+1):
for y in range(1,n+1):
print(x,'X',y,'=',x*y)
print('____________')
soluiton
enter number of rows10
enter value:2
enter value:6
2X1=2
2X2=4
2X3=6
2X4=8
2 X 5 = 10
2 X 6 = 12
2 X 7 = 14
2 X 8 = 16
2 X 9 = 18
2 X 10 = 20
____________
3X1=3
3X2=6
3X3=9
3 X 4 = 12
3 X 5 = 15
3 X 6 = 18
3 X 7 = 21
3 X 8 = 24
3 X 9 = 27
3 X 10 = 30
____________
4X1=4
4X2=8
4 X 3 = 12
4 X 4 = 16
4 X 5 = 20
4 X 6 = 24
4 X 7 = 28
4 X 8 = 32
4 X 9 = 36
4 X 10 = 40
____________
5X1=5
5 X 2 = 10
5 X 3 = 15
5 X 4 = 20
5 X 5 = 25
5 X 6 = 30
5 X 7 = 35
5 X 8 = 40
5 X 9 = 45
5 X 10 = 50
____________
6X1=6
6 X 2 = 12
6 X 3 = 18
6 X 4 = 24
6 X 5 = 30
6 X 6 = 36
6 X 7 = 42
6 X 8 = 48
6 X 9 = 54
6 X 10 = 60
Example:11 Unicode character of 'A' is 65
print alphabets with unicodes from 'A' to 'Z'
for x in range(65,91):
print(x,chr(x))
65 A
66 B
67 C
68 D
69 E
70 F
71 G
72 H
73 I
74 J
75 K
76 L
77 M
78 N
79 O
80 P
81 Q
82 R
83 S
84 T
85 U
86 V
87 W
88 X
89 Y
90 Z
Example:12: Unicode character of 'a' is 97
print alphabets with unicodes from 'a' to 'z'
for x in range(97,123):
print(x,'>***<==unicode==>***<',chr(x))
97 >***<==unicode==>***< a
98 >***<==unicode==>***< b
99 >***<==unicode==>***< c
100 >***<==unicode==>***< d
101 >***<==unicode==>***< e
102 >***<==unicode==>***< f
103 >***<==unicode==>***< g
104 >***<==unicode==>***< h
105 >***<==unicode==>***< i
106 >***<==unicode==>***< j
107 >***<==unicode==>***< k
108 >***<==unicode==>***< l
109 >***<==unicode==>***< m
110 >***<==unicode==>***< n
111 >***<==unicode==>***< o
112 >***<==unicode==>***< p
113 >***<==unicode==>***< q
114 >***<==unicode==>***< r
115 >***<==unicode==>***< s
116 >***<==unicode==>***< t
117 >***<==unicode==>***< u
118 >***<==unicode==>***< v
119 >***<==unicode==>***< w
120 >***<==unicode==>***< x
121 >***<==unicode==>***< y
122 >***<==unicode==>***< z
Example:13 find maximum number in given list
pylist=[1,2,3,5,8,9]
print(max(pylist))
solution
9
Example:13 find maximum number in given list
pylist=[1,2,3,5,8,9]
print('maximum number in given list ',pylist,' is:\t',max(pylist))
solution
maximum number in given list [1, 2, 3, 5, 8, 9] is: 9
Example:14 find minimum number in given list
pylist=[1,2,3,5,8,9]
print(max(pylist))
solution
1
Example:19 convert the positive integer numbers in the list into negative integer numbers'
li=[1,2,3,4,5,6,7,8,9,-10,-11]
print([x*-1 if x>0 else x for x in li])
solution
[-1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11]
Example:20 convert the odd integer numbers in the list into even integer numbers
li=[1,3,5,7,11,13]
for x in li:
print(x+1)
solution
2
4
6
8
12
14
Example:20 convert the odd integer numbers in the list into even integer numbers
li=[1,3,5,7,11,13]
print([x+1 for x in li])
solution
[2, 4, 6, 8, 12, 14]
Example:20 convert the odd integer numbers in the list into even integer numbers
li=[1,3,5,7,11,13,2,4,6,8]
print([x+1 if x%2!=0 else x for x in li])
solution
[2, 4, 6, 8, 12, 14, 2, 4, 6, 8]
Example:21 convert the even integer numbers in the list into odd integer numbers
li=[1,3,5,7,11,13,2,4,6,8]
print([x+1 if x%2==0 else x for x in li])
solution
[1, 3, 5, 7, 11, 13, 3, 5, 7, 9]
Example:26 To print marks of each subject, Grade,total marks,total grade and percentage
print('---------------------JNTU ANANTAPUR-------------------------')
print('==================MARKS MEMO OF ENGNINEERING=======--
=======')
print('---------------------SIETK PUTTUR-------------------------\n')
print('-----------------MECHANICAL ENGINEERING-------------------\n')
print("Maximum Marks:100")
td=int(input("Marks of Subject:Thermodynamics==>"))
if td<= 100 and td >= 90:
print("Grade:A+",td)
elif td<=90 and td >=80:
print("Grade:A",td)
elif td<=80 and td >=70:
print("Grade:B",td)
elif td<=70 and td >=60:
print("Grade:B+",td)
elif td<=60 and td >=50:
print("Grade:C",td)
else:
print("Failed",td)
print('=============================================================')
print("Maximum Marks:100")
te=int(input("Marks of Subject:Thermal Engineering==>"))
if te<= 100 and te >= 90:
print("Grade:A+",te)
elif te<=90 and te >=80:
print("Grade:A",te)
elif te<=80 and te >=70:
print("Grade:B",te)
elif te<=70 and te >=60:
print("Grade:B+",te)
elif te<=60 and te >=50:
print("Grade:C",te)
else:
print("Failed",te)
print('=============================================================')
print("Maximum Marks:100")
te1=int(input("Marks of Subject:Thermal Engineering I==>"))
if te1<= 100 and te1 >= 90:
print("Grade:A+",te1)
elif te1<=90 and te1 >=80:
print("Grade:A",te1)
elif te1<=80 and te1 >=70:
print("Grade:B",te1)
elif te1<=70 and te1 >=60:
print("Grade:B+",te1)
elif te1<=60 and te1 >=50:
print("Grade:C",te1)
else:
print("Failed",te1)
print('=============================================================')
print("Maximum Marks:100")
te2=int(input("Marks of subject:Thermal Engineering II==>"))
if te2<= 100 and te2 >= 90:
print("Grade:A+",te2)
elif te2<=90 and te2 >=80:
print("Grade:A",te2)
elif te2<=80 and te2 >=70:
print("Grade:B",te2)
elif te2<=70 and te2 >=60:
print("Grade:B+",te2)
elif te2<=60 and te2 >=50:
print("Grade:C",te2)
else:
print("Failed",te2)
print('=============================================================')
print("Maximum Marks:100")
ht=int(input("Marks of Subject:Heat Transfer==>"))
if ht<= 100 and ht >= 90:
print("Grade:A+",ht)
elif ht<=90 and ht >=80:
print("Grade:A",ht)
elif ht<=80 and ht >=70:
print("Grade:B",ht)
elif ht<=70 and ht >=60:
print("Grade:B+",ht)
elif ht<=60 and ht >=50:
print("Grade:C",ht)
else:
print("Failed",ht)

total=td+te1+te2+ht+te
percentage=(total/500)*100
print('=============================================================')
print("Total Marks",total)
print("Overall Percentage",percentage)
avg=(total/5)
if avg<=100 and avg>=90:
print("Average Grade:A+")
elif avg<=90 and avg >=80:
print("Average Grade:A")
elif avg<=80 and avg >=70:
print("Average Grade:B")
elif avg<=70 and avg >=60:
print("Average Grade:B+")
elif avg<=60 and avg >=50:
print("Average Grade:C ")
else:
print(" overall Grade & fail")
print('=============================================================')
print('Name of Examiner and Signature:\t\t\t\t\t')
print('Principal signature: ')
print('=============================================================')

Solution
---------------------JNTU ANANTAPUR-------------------------
==================MARKS MEMO OF ENGNINEERING=======--=======
---------------------SIETK PUTTUR-------------------------

-----------------MECHANICAL ENGINEERING-------------------

Maximum Marks:100
Marks of Subject:Thermodynamics==>80
Grade:A 80
=============================================================
Maximum Marks:100
Marks of Subject:Thermal Engineering==>90
Grade:A+ 90
=============================================================
Maximum Marks:100
Marks of Subject:Thermal Engineering I==>88
Grade:A 88
=============================================================
Maximum Marks:100
Marks of subject:Thermal Engineering II==>80
Grade:A 80
=============================================================
Maximum Marks:100
Marks of Subject:Heat Transfer==>90
Grade:A+ 90
=============================================================
Total Marks 428
Overall Percentage 85.6
Average Grade:A
=============================================================
Name of Examiner and Signature:
Principal signature:
=============================================================

Example:1 To display odd number in the given numerical integer string


total=0
pylist=[1,2,3,4,5,6,7,8,9]
print('the odd numbers in the given list',pylist,'are:')
for i in range(0,9,1):
if(pylist[i]%2!=0):
print(pylist[i])
total+=pylist[i]
print('\nSum of odd numbers of list is:',total)
solution:
the odd numbers in the given list [1, 2, 3, 4, 5, 6, 7, 8, 9] are:
1
3
5
7
9
Sum of odd numbers of list is: 25
"""Example:2 To display odd number in the given numerical integer string
total=0
pylist=[1,2,3,4,5,6,7,8,9]
print('the even numbers in the given list',pylist,'are:')
for i in range(0,9,1):
if(pylist[i]%2==0):
print(pylist[i])
total+=pylist[i]
print('\nSum of even numbers of list is:',total)
solution:
the even numbers in the given list [1, 2, 3, 4, 5, 6, 7, 8, 9] are:
2
4
6
8
Sum of even numbers of list is: 20"""
example 3:to sum first even numbers'
total=0
n=int(input('enter the n value:\t'))
print('the even numbers between "1" and',n,'are:')
for x in range(1,n+1,1):
if (x%2==0):
total+=x
print(x)
print('the sum of first',n,'even numbers are:',total)
solution:
enter the n value: 10
the even numbers between "1" and 10 are:
2
4
6
8
10
the sum of first 10 even numbers are: 30
Example 4:To print even numbers between given range n1:n2
n1=int(input('enter the n1 value:\t'))
n2=int(input('enter the n2 value:\t'))
print('the even numbers between',n1,'and',n2,'are:')
for x in range(n1,n2+1,1):
if (x%2==0):
print(x)
Solution:
enter the n1 value: 12
enter the n2 value: 20
the even numbers between 12 and 20 are:
12
14
16
18
20
Example:5 To print first 'n' odd numbers
n=int(input('enter the n value:\t'))
print('the odd numbers between "1" and',n,'are:')
for x in range(1,n+1,1):
if (x%2!=0):
print(x)
solution:
enter the n value: 10
the odd numbers between "1" and 10 are:
1
3
5
7
9
Example 7:To find sum of first n natural numbers'
total=0
n=int(input('enter the n value:\t'))
print('the natural numbers between "1" and',n,'are:')
for x in range(1,n+1,1):
total+=x
print(x)
print('the sum of first',n,'even numbers are:',total)
enter the n value: 10
the natural numbers between "1" and 10 are:
1
2
3
4
5
6
7
8
9
10
the sum of first 10 even numbers are: 55
Example 8: To print natural numbers between given range n1:n2'
n1=int(input('enter the n1 value:\t'))
n2=int(input('enter the n2 value:\t'))
print('the natural numbers between',n1,'and',n2,'are:')
for x in range(n1,n2+1,1):
print(x)
solution:
enter the n1 value: 10
enter the n2 value: 20
the natural numbers between 10 and 20 are:
10
11
12
13
14
15
16
17
18
19
20
Examples 9:Print the multiplication table for given number with specific range[rows]'
n1=int(input('enter the n1 value:\t'))
n2=int(input('how many rows:'))
for i in range(1,n2+1,1):
print(n1,'X',i,'=',n1*i)
enter the n1 value: 2
how many rows:10
2X1=2
2X2=4
2X3=6
2X4=8
2 X 5 = 10
2 X 6 = 12
2 X 7 = 14
2 X 8 = 16
2 X 9 = 18
2 X 10 = 20
Examples10:Print the multiplication table for given specific range between n1 and n2 with
specific range[rows]
n1=int(input('enter the n1 value:\t'))
n3=int(input('how many rows:'))
for i in range(1,n1+1,1):
for j in range(1,n3+1,1):
print(i,'X',j,'=',j*i)
print('--------------------------')
solution:
enter the n1 value: 5
how many rows:10
1X1=1
1X2=2
1X3=3
1X4=4
1X5=5
1X6=6
1X7=7
1X8=8
1X9=9
1 X 10 = 10
--------------------------
2X1=2
2X2=4
2X3=6
2X4=8
2 X 5 = 10
2 X 6 = 12
2 X 7 = 14
2 X 8 = 16
2 X 9 = 18
2 X 10 = 20
--------------------------
3X1=3
3X2=6
3X3=9
3 X 4 = 12
3 X 5 = 15
3 X 6 = 18
3 X 7 = 21
3 X 8 = 24
3 X 9 = 27
3 X 10 = 30
--------------------------
4X1=4
4X2=8
4 X 3 = 12
4 X 4 = 16
4 X 5 = 20
4 X 6 = 24
4 X 7 = 28
4 X 8 = 32
4 X 9 = 36
4 X 10 = 40
--------------------------
5X1=5
5 X 2 = 10
5 X 3 = 15
5 X 4 = 20
5 X 5 = 25
5 X 6 = 30
5 X 7 = 35
5 X 8 = 40
5 X 9 = 45
5 X 10 = 50
Example:11 Unicode character of 'A' is 65
print alphabets with unicodes from 'A' to 'Z'
for i in range(65,91,1):
print(' ',chr(i),'===========>','unicode:',i)
A ===========> unicode: 65
B ===========> unicode: 66
C ===========> unicode: 67
D ===========> unicode: 68
E ===========> unicode: 69
F ===========> unicode: 70
G ===========> unicode: 71
H ===========> unicode: 72
I ===========> unicode: 73
J ===========> unicode: 74
K ===========> unicode: 75
L ===========> unicode: 76
M ===========> unicode: 77
N ===========> unicode: 78
O ===========> unicode: 79
P ===========> unicode: 80
Q ===========> unicode: 81
R ===========> unicode: 82
S ===========> unicode: 83
T ===========> unicode: 84
U ===========> unicode: 85
V ===========> unicode: 86
W ===========> unicode: 87
X ===========> unicode: 88
Y ===========> unicode: 89
Z ===========> unicode: 90

Example:12: Unicode character of 'a' is 97


print alphabets with unicodes from 'a' to 'z'

for i in range(97,123,1):
print(' ',chr(i),'===========>','unicode:',i)
a ===========> unicode: 97
b ===========> unicode: 98
c ===========> unicode: 99
d ===========> unicode: 100
e ===========> unicode: 101
f ===========> unicode: 102
g ===========> unicode: 103
h ===========> unicode: 104
i ===========> unicode: 105
j ===========> unicode: 106
k ===========> unicode: 107
l ===========> unicode: 108
m ===========> unicode: 109
n ===========> unicode: 110
o ===========> unicode: 111
p ===========> unicode: 112
q ===========> unicode: 113
r ===========> unicode: 114
s ===========> unicode: 115
t ===========> unicode: 116
u ===========> unicode: 117
v ===========> unicode: 118
w ===========> unicode: 119
x ===========> unicode: 120
y ===========> unicode: 121
z ===========> unicode: 122
Example:13 find maximum number in given list
pylist=[1,2,3,5,8,9]
print(max(pylist))
solution
9
Example:13 find maximum number in given list
pylist=[1,2,3,5,8,9]
print('maximum number in given list ',pylist,' is:\t',max(pylist))
solution
maximum number in given list [1, 2, 3, 5, 8, 9] is: 9
Example:14 find minimum number in given list
pylist=[1,2,3,5,8,9]
print(max(pylist))
solution
1
Examples 14:
pylist=[1,2,3,5,8,9]
print('maximum number in given list ',pylist,' is:\t',max(pylist))
solution
minimum number in given list [1, 2, 3, 5, 8, 9] is: 1
Example:15
pylist=[1,2,3,5,8,9]
print('sum of given list ',pylist,' is:\t',sum(pylist))
solution
sum of given list [1,2,3,5,8,9] 28
Example:16
pylist=[4,2,6]
s=sum(pylist)
c=len(pylist)
x=s/c
print('the average of number in given list ',pylist,' is:\t',x)
solution
the average of number in given list [4,2,6] is :4
Example:17
import [Link] as plt
x=[1,2,3,4,5,6,7,8,9,10]
[Link](x,'bo-')
[Link]('time')
[Link]('money')
[Link]('life cycle')
[Link]()

Example:18
import [Link] as plt
x=[1,2,3,4,5]
[Link](x,'b-')
[Link](x,'ro')
[Link]('time')
[Link]('Y')
[Link]('wave with blue colour with red dots')
[Link]()
Example:19 convert the positive integer numbers in the list into negative integer numbers'
li=[1,2,3,4,5,6,7,8,9,-10,-11]
print([x*-1 if x>0 else x for x in li])
solution
[-1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11]
Example:19 convert the positive integer numbers in the list into negative integer numbers'
pylist=[1,2,3,4,-4,-6]
l=len(pylist)
pppq
if (pylist[i]>0):
pylist[i]*=-1
print(pylist[i])
solution
-1
-2
-3
-4
-4
-6
Example:20 convert the odd integer numbers in the list into even integer numbers
li=[1,3,5,7,11,13]
for x in li:
print(x+1)
solution
2
4
6
8
12
14
Example:20 convert the odd integer numbers in the list into even integer numbers
li=[1,3,5,7,11,13]
print([x+1 for x in li])
solution
[2, 4, 6, 8, 12, 14]
Example:20 convert the odd integer numbers in the list into even integer numbers
li=[1,3,5,7,11,13,2,4,6,8]
print([x+1 if x%2!=0 else x for x in li])
solution
[2, 4, 6, 8, 12, 14, 2, 4, 6, 8]
Example:20 convert the odd integer numbers in the list into even integer numbers
pylist=[1,2,3,4,5,6,7,8]
l=len(pylist)
for i in range(0,l,1):
if (pylist[i]%2!=0):
pylist[i]+=1
print(pylist[i])
solution
2
2
4
4
6
6
8
8
Example:21 convert the even integer numbers in the list into odd integer numbers
li=[1,3,5,7,11,13,2,4,6,8]
print([x+1 if x%2==0 else x for x in li])
solution
[1, 3, 5, 7, 11, 13, 3, 5, 7, 9]
Example:21 convert the even integer numbers in the list into odd integer numbers
pylist=[1,2,3,4,5,6,88,6,7]
l=len(pylist)
for i in range(0,l,1):
if (pylist[i]%2!=0):
pylist[i]
else:
pylist[i]+=1
print(pylist[i])
1
3
3
5
5
7
89
7
7
Example:22: covert the all numbers in a list into same number list
n=int(input('enter what u want'))
pylist=[1,2,3,4,5,6,7]
l=len(pylist)
for i in range(0,l,1):
if(pylist[i]==n):
print(pylist[i])
else:
pylist[i]=n
print(pylist[i])
solution:
enter what u want7
7
7
7
7
7
7
7
Example:23
pylist=[1,2,3,4,[5,6,7,8,[9,10,11,12,[13,14,15,16]]]]
print(pylist)
print(pylist[4][4][4][3])
solution
[1, 2, 3, 4, [5, 6, 7, 8, [9, 10, 11, 12, [13, 14, 15, 16]]]]
16
Example:24: convert the all alphabets in a list into same alpha list
list1=['a','b','c','d','e']
c=str(input('enter your favourate letter:\t'))
a=ord(c)
l=len(list1)
for i in range(0,l,1):
print(chr(a))
solution
enter your favourate letter: b
b
b
b
b
b
Example:25:covert the all alphabets in a list into same string list
list1=['a','b','c','d','e']
c=str(input('enter your favourate letter:\t'))
l=len(list1)
for i in range(0,l,1):
print(str(c))
enter your favourate letter: g
g
g
g
g
g
example 26: progress card
total=0
maximumtotal=0
counter=1
p=0
f=0
print('-------------------------------------------------------------')
print('==================SMART PROGRESS
CARD========================')
print('-------------------------------------------------------------\n')
n=int(input('enter how many subjects:\t\t\t\t'))
print('-------------------------------------------------------------\n')
counter
while counter<=n:
sub=input('enter subject name:\t\t\t\t\t')
m=int(input("Enter maximum marks:\t\t\t\t\t"))
m1=int(input('Enter secured marks:\t\t\t\t\t'))
while (m1>m or m1<0):
print("==========Invalid typing==========")
print('secured marks greaterthan amximum marks\n')
m1=int(input("Enter secured marks:\t\t\t\t\t"))
a=m1/m
grade1=a*100
if (grade1>50):
p=p+1
else:
f=f+1
if (grade1>100 or grade1<0):
print('invalid condition')
print('==========================================================
===')
elif (grade1>=90 and grade1<=100):
print('Grade:\t\t\t\t\t\t\tA+')
print('==========================================================
===')
elif (grade1>=80 and grade1<90):
print('Grade:\t\t\t\t\t\t\tA')
print('==========================================================
===')
elif (grade1>=70 and grade1<80):
print('Grade:\t\t\t\t\t\t\tB+')
print('==========================================================
===')
elif (grade1>=60 and grade1<70):
print('Grade:\t\t\t\t\t\t\tB')
print('==========================================================
===')
elif (grade1>=50 and grade1<60):
print('Grade:\t\t\t\t\t\t\tPASS')
print('==========================================================
===')
else:
print('Grade:\t\t\t\t\t\t\tFAIL')
print('==========================================================
===')
total=total+m1
maximumtotal=maximumtotal+m
percent=total/maximumtotal
grade=percent*100
counter=counter+1
print('Summary:')
print('---------')
print('Pass subjects:\t\t\t\t\t\t',p)
print('Fail subjects:\t\t\t\t\t\t',f)
print('total secured marks:\t\t\t\t\t',total)
print('maximum marks:\t\t\t\t\t\t',maximumtotal)
if(f==0):
print('total percentage of marks:\t\t\t\t',round(grade,2))
if (f==0 and grade>100 or grade<0):
print('invalid condition')
print('============================================================
=')
elif (f==0 and grade>=90 and grade<=100):
print('Overall Grade: \t\t\t\t\t\t A+')
print('============================================================
=')
elif (f==0 and grade>=80 and grade<90):
print('Overall Grade:\t\t\t\t\t\t A')
print('============================================================
=')
elif (f==0 and grade>=70 and grade<80):
print('Overall Grade:\t\t\t\t\t\t B+')
print('============================================================
=')
elif (f==0 and grade>=60 and grade<70):
print('Overall Grade:\t\t\t\t\t\t B')
print('============================================================
=')
elif (f==0 and grade>=50 and grade<60):
print('Overall Grade:\t\t\t\t\t\t PASS')
print('============================================================
=')
else:
print('Overall Grade:\t\t\t\t\t\t FAIL')
print('============================================================
=')
print('=============================================================')
print('Parent Signature:\t\t\t\t\t')
print('=============================================================')

solution
-------------------------------------------------------------
==================SMART PROGRESS CARD========================
-------------------------------------------------------------

enter how many subjects: 6


-------------------------------------------------------------

enter subject name: maths


Enter maximum marks: 100
Enter secured marks: 78
Grade: B+
=============================================================
enter subject name: chemistory
Enter maximum marks: 100
Enter secured marks: 80
Grade: A
=============================================================
enter subject name: physcis
Enter maximum marks: 100
Enter secured marks: 66
Grade: B
=============================================================
enter subject name: english
Enter maximum marks: 100
Enter secured marks: 77
Grade: B+
=============================================================
enter subject name: telugu
Enter maximum marks: \100
Enter secured marks: 100
Grade: A+
=============================================================
enter subject name: social
Enter maximum marks: 100
Enter secured marks: 88
Grade: A
=============================================================
Summary:
---------
Pass subjects: 6
Fail subjects: 0
total secured marks: 489
maximum marks: 600
total percentage of marks: 81.5
Overall Grade: A
=============================================================
=============================================================
Parent Signature:

Example:26 To print marks of each subject, Grade,total marks,total grade and percentage
print('---------------------JNTU ANANTAPUR-------------------------')
print('==================MARKS MEMO OF ENGNINEERING=======--
=======')
print('---------------------SIETK PUTTUR-------------------------\n')
print('-----------------MECHANICAL ENGINEERING-------------------\n')
print("Maximum Marks:100")
td=int(input("Marks of Subject:Thermodynamics==>"))
if td<= 100 and td >= 90:
print("Grade:A+",td)
elif td<=90 and td >=80:
print("Grade:A",td)
elif td<=80 and td >=70:
print("Grade:B",td)
elif td<=70 and td >=60:
print("Grade:B+",td)
elif td<=60 and td >=50:
print("Grade:C",td)
else:
print("Failed",td)
print('=============================================================')
print("Maximum Marks:100")
te=int(input("Marks of Subject:Thermal Engineering==>"))
if te<= 100 and te >= 90:
print("Grade:A+",te)
elif te<=90 and te >=80:
print("Grade:A",te)
elif te<=80 and te >=70:
print("Grade:B",te)
elif te<=70 and te >=60:
print("Grade:B+",te)
elif te<=60 and te >=50:
print("Grade:C",te)
else:
print("Failed",te)
print('=============================================================')
print("Maximum Marks:100")
te1=int(input("Marks of Subject:Thermal Engineering I==>"))
if te1<= 100 and te1 >= 90:
print("Grade:A+",te1)
elif te1<=90 and te1 >=80:
print("Grade:A",te1)
elif te1<=80 and te1 >=70:
print("Grade:B",te1)
elif te1<=70 and te1 >=60:
print("Grade:B+",te1)
elif te1<=60 and te1 >=50:
print("Grade:C",te1)
else:
print("Failed",te1)
print('=============================================================')
print("Maximum Marks:100")
te2=int(input("Marks of subject:Thermal Engineering II==>"))
if te2<= 100 and te2 >= 90:
print("Grade:A+",te2)
elif te2<=90 and te2 >=80:
print("Grade:A",te2)
elif te2<=80 and te2 >=70:
print("Grade:B",te2)
elif te2<=70 and te2 >=60:
print("Grade:B+",te2)
elif te2<=60 and te2 >=50:
print("Grade:C",te2)
else:
print("Failed",te2)
print('=============================================================')
print("Maximum Marks:100")
ht=int(input("Marks of Subject:Heat Transfer==>"))
if ht<= 100 and ht >= 90:
print("Grade:A+",ht)
elif ht<=90 and ht >=80:
print("Grade:A",ht)
elif ht<=80 and ht >=70:
print("Grade:B",ht)
elif ht<=70 and ht >=60:
print("Grade:B+",ht)
elif ht<=60 and ht >=50:
print("Grade:C",ht)
else:
print("Failed",ht)

total=td+te1+te2+ht+te
percentage=(total/500)*100
print('=============================================================')
print("Total Marks",total)
print("Overall Percentage",percentage)
avg=(total/5)
if avg<=100 and avg>=90:
print("Average Grade:A+")
elif avg<=90 and avg >=80:
print("Average Grade:A")
elif avg<=80 and avg >=70:
print("Average Grade:B")
elif avg<=70 and avg >=60:
print("Average Grade:B+")
elif avg<=60 and avg >=50:
print("Average Grade:C ")
else:
print(" overall Grade & fail")
print('=============================================================')
print('Name of Examiner and Signature:\t\t\t\t\t')
print('Principal signature: ')
print('=============================================================')

Solution
---------------------JNTU ANANTAPUR-------------------------
==================MARKS MEMO OF ENGNINEERING=======--=======
---------------------SIETK PUTTUR-------------------------

-----------------MECHANICAL ENGINEERING-------------------

Maximum Marks:100
Marks of Subject:Thermodynamics==>80
Grade:A 80
=============================================================
Maximum Marks:100
Marks of Subject:Thermal Engineering==>90
Grade:A+ 90
=============================================================
Maximum Marks:100
Marks of Subject:Thermal Engineering I==>88
Grade:A 88
=============================================================
Maximum Marks:100
Marks of subject:Thermal Engineering II==>80
Grade:A 80
=============================================================
Maximum Marks:100
Marks of Subject:Heat Transfer==>90
Grade:A+ 90
=============================================================
Total Marks 428
Overall Percentage 85.6
Average Grade:A
=============================================================
Name of Examiner and Signature:
Principal signature:

PYTHON Important Questions for Interview purpose


***************************************
[Link] is Scripting?
-loosely typed programming
-Weekly typed programming
-Light weighted programming
[Link] many scripts are there in software environment?
-Two types i)Client side ---which runs within the web broweser==>Angular
ii)Server side---which runs within the web server ===>Python
[Link] languages are .....declartion
-implicit
[Link] is the major diffrence between scripting vs programming langauges?
-scripting langauges are interpretor run mode
-programming lang. are compiler or compiler+interpreteor
[Link] is the diffrence between interprettor vs compiler?
-interprettor excutes line by line
-compiler excutes entire souce code
[Link] interprettor faster or compiler?
--compiler could fast
[Link] interprettor more accuracy or compiler?
--Interprettor
[Link] you define What is PYTHON in your own words and what you feel it?
-PYTHON is a simple & it can understand everyone very easily with minimum inteligence,
-PYTHON is a Genral purpose programming language it can suitable any application,
-PYTHON is a mixture of all languages it means it is a multipardigm programming lang.
-PYTHON is a interpreted programming lang.,
-PYTHON is a object oriented,procedural,structural,logical and functonal programming lang.
-PYTHON is a high level and genral public licenced programming lang.
-PYTHON is a dynamic programming lang.
[Link] invented the PYTHON?
-Guido Van Rossum: He is frustated while he was doing job in th ABC domin,
He had taken all technologies pros\cons\limitation and
implemented one simple lang i.e, PYTHON
[Link] is the best feature of python?
-it can integrate with any software application like number of alternatives are there--
jython,cython,Ironpython,pydoop,pypy
[Link] you tell me some applications of python where it could be used?
--Webscrapping,Data science,Automation,web devlopment,IOT,AI,DL,Graphics,ML,and
gamming many more applications
--where human inteligence is there,there can be suitable simply
[Link] is this symbol:- >>>
--triple cheveron in idle
[Link] is the full form of IDLE
---Integrated Devlopment Learning enviornment
[Link] are the run modes basically?
---Interactive Run Mode
---Script mode run or batchor development mode
--comand prompt
[Link] is the full fom of CLI
--command line interface
[Link] is the shortcut to show the previous command in IDLE?
---Ctl+P
[Link] is the shortcut to show the next command in IDLE?
--Ctl+N
[Link] can you set shortcuts in IDLE?
---Options==>configure IDLE==>keys
[Link] can you quit from IDLE?
--quit(),exit(),Ctl+d
[Link] could you open script run mode?
---Idle==>Ctl+N
---idle==>file+N
[Link] is the short cut to excute or run in script mode?
--Alt+F5 =======>in some pcs
---Function+F5==>in some pcs
[Link] to clear screen IDLE?
--there is no synatx availabul for clearing screen but we can go give some space
by using this syntax: print("\n"*number)
[Link] to clear screen in Linux/Unix?
--Ctl+L
[Link] develop Python files in realtime what are the enviornments used?
---basically two types 1)editors 2)IDEs
25. Tell me diffrent types editor modes?
----Notepad,Notepad++,Editplus,Vi,nano,gedit
[Link] me what are the diffrent types of IDEs?
--[Link],[Link]([Link] [Link])[Link] [Link],[Link],[Link]
[Link] are the print Builtin parameters?
--[Link],[Link],3,end,[Link],[Link]
[Link] is representation of Single quotation
--Charector objects
[Link] is representation of Double quotation
--Multiple objects
[Link] is representation of Triple quotation
--Charector documentation
[Link] is the defination of string concatination?
--adding morethan one string to other string
[Link] is the defination of input function?
--Read the data from the user
[Link] is the syntax of input function in 2.x?
--raw_input()
[Link] is the purpose of single lone underscore?
--it is automatically stores recent output value in interpreter
[Link] do you know about PSf?
--PSF means python software founadtion ,it is a coummunity for providing packages openly
to develop the python
[Link] to find path of python file or software?
--import os;print([Link]())
--import sys;print([Link])
[Link] to find which version of python ?
--import sys;print([Link])
--import platform;print(platform.python_version())
[Link] to find which keywords of python ?
--import keyword;print([Link])
[Link] are the major diffrences between python vs java
--in java all variables E?xplicitely diclared where as python not like that
--java statically typed where as python dynamically typed
--lesser program productivity in java,python higher productivity
--no perfect libraries for DL,ML,AI,IOT
--java faster but complex syntax
--for structural coading in java must use braces where as python indentation used
[Link] is the use of comment in python?and tell me defination?
--comment is non excutable or ignore statement
--project description purpose used
---can be represented by #
[Link] is debugging?
--identifying and fixing the problem
[Link] form of spyder?
-Scientific python development eniviornment
[Link] form of jupyter?
-juliya,python and R language
[Link] is identifier?
-it is allies of variable name
[Link] is literals?
-it is allies of constant or fixed values
[Link] means?
-first char should be small letters
[Link] case?
-first char should be Capital letters
48.a=b=c=d=40 then what print(a+b+c+d)
--160
49.a=2020,b=2121 then swap it what is the value of a,b=?
--a=2121,b=2020
50.x=10;y=30; z=complex(x+y) then print(type(z)).......?
-<class 'complex'>
[Link](type(none))=............
-<class 'None'>
[Link](format(143,'8f'))?
-143.000000(because the format can specify upto 6 digits)
[Link](0b10001)?
-17
[Link](bin(18))?
-0b10010
[Link](int("10101",2))?
-21
[Link](int("10101",8))?
-4161
[Link](int("10101",16))?
-65793
[Link](oct(20))?
-0o24
[Link](hex(300))?
-0x12c
[Link] is PEMDAS? which is higher priority?
-parenthasis,exponential
[Link](chr(82),chr(65),chr(74),chr(85),chr(83),chr(73),chr(82))?
-RAJUSIR
[Link](ord('S'))?
-83
[Link]("i wish you happy advance %d %s day"%(72,"independence"))
-i wish you happy advance 72 independence day
[Link] fraction import Fraction; print(Fraction(0.5))........?
-1/2
[Link](abs(-242))....?
-242
[Link](ceil(-34.33))......?
- -34
[Link](floor(-34.35))......?
- -35
[Link]([Link](2,5))...?
-32
[Link](round(101.556,2))....?
- 101.56
[Link](round(101.45,1))....?
-101.5
[Link](round(101.1256,3))...?
-101.126
[Link]([Link](256))....?
-16
[Link]([Link]())....?
-0.37182119165430616
73.x=85;y=x+3;y=int(str(y)+"2".............?
-82
74word=input("enter a word:");enter a word:cheese; print(word+'shop')......?
-cheese shop
[Link]="7";spam=spam+"0;eggs=int(spam)+3;print(float(eggs))......?
-73.0
[Link] is the output of this coade:int("3"+"4").......?
-34
[Link]("210"*int(input("enter a number:")));enter a number:2;what is the output....?
-210210.0
[Link] is the output of this code:print('print("print")')...?
--print("print")
[Link] is the output:print(not 1==1)...??
-false
79.a=True;b=False;c=False;print(a and b or c or not b) what is the output....?
-True
80.a=True;b=True;c=False;print(a or b and c or not c) what is the output....?
-True
[Link] is the output of the code:print(not 1 >7)...?
-True
[Link]="salary";print("a" in job)....?
-True
[Link]="king";king="queen";print( king is not queen)....
-True
84.a=20;b=13;print(a&b)...what is the output of this code?
-4
85.a=7;b=6;print(a|b)....what is the output of this code?
-7
86.a=15;b=12;print(a^b)...what is the output of this code?
-3
[Link](~11)...what is the output of this code?
-(-12)
[Link](15<<2).....what is the output of this code?
-60
[Link](20>>2)...what is the output of this code?
-5
[Link] is the output of this code? s=str(none);print(s)...
-None
[Link] is the output of this code? a="10";b=a*0+1;print(b)..
-typeError:canot concatinate to str
92.a=10;a+=5;print(a)
-15
93.a=10;a*=10;print(a)
-100
94.a=20;a**=2;print(a)
-400
95.a=15;a//=2;print(a)
-7.0
96.a=21;a%=2;print(a)
-1
[Link] means...
-# its comment symbol
[Link](len("hi how are you")
-14
99.a='Rajusir';b=123;print(a+b)...
--Error:can not concatinate with string to int
100.a='rajusir';b='py';print(a+b)...
-rajusirpy

How to generate PDF using PYTHON:


We are going to learn how to generate PDF using python. Python has many supporting
libraries and world's largest community. Sometimes we need to convert our text files into
PDFs.
Installation:
$pip install fpdf

Example:
from fpdf import FPDF
pdf = FPDF()
pdf.add_page()
pdf.set_font('Arial',size=25)
[Link](200,100,txt='Hello, You are in [Link] ', align='C')
[Link]("[Link]")
print("Say Hey PDF File Creted Successfully")

NOTE:
1 We import FPDF and create an object for it. Now we create a page. we set font_size,
font_family. align represents the position of content in the cell, “C” -center, “R”-right, “L”-
left.
2 [Link]() method generate the output file. we need to give the output file name.

Generate pdf file from text file:


Example:
from fpdf import FPDF
f = open('[Link]','r')
content = ''
for i in f:
content =i
pdf = FPDF()
pdf.add_page()
pdf.set_font('Arial',size=18)
[Link](100,10,txt=content,align='C')
[Link]("[Link]")

NOTE:
open() helps us to grab our text file from our current directory in our system. ‘r’ represents
the mode of the file
Created one string empty variable "content" which helps us to store our text from the text file.
Used here a for loop to get that text from textfile and store it into "content".
[Link]() we reassign the txt parameter to "content" because we were storing the data in a
variable content.

What is QR Code?
Quick Response code was firstly designed in 1994 by Hara Masahiro in Japan in the
automotive industry. It is a type of barcode matrix that can help us to store the details. It is a
two-dimensional barcode that is readable by smartphones. It allows to encode over 4000
characters in a two dimensional barcode. We can store every detail of us in the form of QR
code that may be personal details, product details, other info.

How to generate QR code in python


This is a very simple step by step guide to generating QR code in python. we will discuss
1 Generate QR code
2 Generate QR code with links
3 Styling your QR code
4 Generate QR code with user input data
5 Read QR code data using python

Generate QR code
Generate a QR code in python is very simple. Before we generate our QR code, we need to
install these below packages.
$pip install qrcode #To generate QR code
$pip install Pillow #To manage Images

Example:
import qrcode
qr = [Link]('Hello QR World')
[Link]()
[Link]('[Link]')

Generate QR code with links


We can generate a QR code with hyperlinks.

Example:
import qrcode
data = '[Link]'
qr = [Link](data)
[Link]('[Link]')
[Link]()

Styling your QR code


Well, we generate a QR code with default colors like background white and foreground with
black. I need a QR code with my favorite colors.

Example:
import qrcode
qr = [Link](
version=5,
box_size=5,
border=2
)
data = '[Link]'
qr.add_data(data)
[Link](fit=True)
img = qr.make_image(fill_color='green',back_color='white')
[Link]('[Link]')

Explanation:
[Link]() will take 3 parameters like version, box_size, border.
version represents the size of the QR code. It is a range of 1 to 40.
border represents the border of the QR code.
box_size represents the box size of the QR code.
qr.make_image(fill_color=’green’,back_color=’white’) take 2 parameters. Here we can
stylish our QR code.
fill_color represents the foreground color i,e pattern color of QR code.
back_color represents the background color.

Generate QR code with user input data


Example:
import qrcode
qr = [Link](
version=5,
box_size=5,
border=2
)
name = input('Enter Name:')
age = int(input('Enter Age:'))
Education = input('Enter [Link]:')
data = {'name':name,'age':age,'edu':Education}
qr.add_data(data)
[Link](fit=True)
img = qr.make_image(fill_color='black',back_color='white')
[Link]('[Link]')
[Link]()

$pip install pyzbar

Read QR code data using python


Example:
import qrcode
from [Link] import decode
from PIL import Image
import ast
data = decode([Link]('[Link]'))
info = data[0].[Link]('ascii')
data = ast.literal_eval(info)
#print(type(data))
print(data['name'].upper())
print(data['age'])

pyzbar helps us to decode our QR code.


ast help us to convert string to dictionary format.
Pillow helps us to manage our images.

Our QR code data encoded as binary code so we need to decode it by using pyzbar. Our data
is in string format but we have to separate our data like name, age, and Edu. so we need to
convert that output string to a dictionary. so we use ast.

Most Common Errors in PYTHON Programming:


1. Name Error:
A NameError means that Python tried to use a variable or function name, Because there's no
such name core defined in your code.
Example:
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
y
NameError: name 'y' is not defined

NameError ==> It is Error Code


name 'y' is not defined ==> Error Message

2. Attribute Error:
AttributeError can be defined as an error that is raised when an attribute reference or
assignment fails.
These errors are generally raised when an invalid attribute reference is made.
Example:
>>> PyList=[1,2,3,4,5]
>>> [Link](6)
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
[Link](6)
AttributeError: 'list' object has no attribute 'Append'

3. Syntax Error:
Syntax errors are the most basic type of error. They arise when the Python parser is unable to
understand a line of code. Most syntax errors are typos, incorrect indentation, or incorrect
arguments.

Example:
File "[Link]", line 201
cdata=table[0]
^
SyntaxError:invalid syntax

4. Module Not Found Error:


A ModuleNotFoundError is raised when Python cannot successfully import a module. This
error is encountered when you forget to install a dependency for a project.

Example:
>>> import sklearn
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
import sklearn
ModuleNotFoundError: No module named 'sklearn'

5. EOL Error
EOL stands for End Of Line. This error means that there was an open quote somewhere, but
the line ended before a closing quote was found.

Example:
>>> print("Hello
SyntaxError: EOL while scanning string literal

6. Indentation Error
The indentation in Python is very important. Python uses indentation to indicate a block of
code. Indentation refers to the spaces at the beginning of a code line. Indentation Error
generally occurs when the code contains a mix of both tabs and spaces for indentation.

Example:
if x>0:
print(x)
else:
print(x)
SyntaxError: unindent does not match any outer indentation level

Raju Sir Coding challenge


There are 100 doors, In the first iteration, we will open all doors and in the next iteration, we
will close the doors. The instructions are given below.
[Link] doors — 100 doors
1,2,3,4_,_________________100 – open
2,4,6,_,___________100 -close
3,6,9_,__________________ 99 – open
4,8,12_,__________________100 -close
And finally, calculate the below
#calculate [Link] doors opened
#calculate No. of doors closed

Example:
c = 'close'
p ='open'
j =1
l=1
n=100 # [Link] Rooms
open_door = 0
close_door =0

while l<n:
for i in range(0,n+1,j):
if i==0:
print('Iteration:',j)
continue
if j%2!=0 :
print(i,p)
open_door +=1
else:
print(i,c)
close_door +=1
print('')
l+=1
j+=1
if n%2==0:
print('[Link] Doors opened:',open_door)
print('[Link] Doors Closed:',close_door+1)
else:
print('[Link] Doors opened:',open_door+1)
print('[Link] Doors Closed:',close_door)

Create 2 variables for open and close the doors. Now i took "n" as [Link] rooms.
Used while loop for iteration rooms.
range(0,10,2) : This function give all the even numbers. the output like below.
>>>list(range(0,10,2))
Here,
# 0 - start index
# 10 - end index
# 2 - step size

Output:
[0, 2, 4, 6, 8]
if, else condition blocks are just simple, you can understand easily.
Aadd another if-else condition out of the while loop because using the range function we
iterate (j-1) iterations.
If [Link] rooms are even then we increase the close_door with 1 at last. and for odd [Link]
rooms, we add 1 to open_door.

if n%2==0:
print('[Link] Doors opened:',open_door)
print('[Link] Doors Closed:',close_door+1)
else:
print('[Link] Doors opened:',open_door+1)
print('[Link] Doors Closed:',close_door)

Guessing game in python


Step -1
We need import python random function that can help us to generate random numbers in
python.

import random

Step -2
Greet your friend who is playing you game today.

print("Hello..! What's Your Name: ")


name = input("Enter Here: ")

Step -3
Generate a random number by using the python random function. this is our secret number
which will guess by our friend in our guessing game in python. Here i am taking a range of 1
to 20. you can choose your own.

secret_number = [Link](1,20)
Step – 4
Going to create one for loop that can help us to restrict our friend guesses in minimal guesses.
We give 5 chances to our friend to guess our number.

for i in range(1,6):
print('Take a Guess:')
guess = int(input())

if guess > secret_number:


print('Sorry..! your guess is too high ' +name+'.')
elif guess < secret_number:
print('Sorry..! your guess is too low '+name+'.')
else:
break

Step5
Now finally, if our friend guesses our number then congratulate them else give them a new
trial for free by our guessing game in python program.

if guess == secret_number:
print('Good job, '+name+'! you guessed my number in '+str(i)+'guesses.')
else:
print('Nope, you exceeded guess times. My number is '+str(secret_number)+'.')

Example:
import random
print("Hello..! what's your name..?")
name = input()
print('well,'+name+ ' I am thinking of a number between range of 1 to 20..')
secret_number = [Link](1,20)
for i in range(1,6):
print('Take a Guess:')
guess = int(input())
if guess > secret_number:
print('Sorry..! your guess is too high ' +name+'.')
elif guess < secret_number:
print('Sorry..! your guess is too low '+name+'.')
else:
break
if guess == secret_number:
print('Good job, '+name+'! you guessed my number in '+str(i)+'guesses.')
else:
print('Nope, you exceeded guess times. My number is '+str(secret_number)+'.')

[Link]
Microsoft Python Certification 98-381

INTRODUCTION TO PROGRAMMING USING PYTHON


Exam Pattern:
Number of Questions: 40
Duration:45 Mins
Quetions Type: Multiple Choice, Drag & Drop, Selection from drop down list
Passing Score:70%
No Negative Marking

Syllabus:
Perform Operations using Data Types and Operators (20-25%)
Evaluate an expression to identify the data type Python will assign to each variable
Identify str, int, float, and bool data types
Perform data and data type operations
Convert from one data type to another type; construct data structures; perform indexing and
slicing operations
Determine the sequence of execution based on operator precedence
Assignment; Comparison; Logical; Arithmetic; Identity (is); Containment (in)
Select the appropriate operator to achieve the intended result
Assignment; Comparison; Logical; Arithmetic; Identity (is); Containment (in)

Control Flow with Decisions and Loops (25-30%)


Construct and analyze code segments that use branching statements
if; elif; else; nested and compound conditional expressions
Construct and analyze code segments that perform iteration
while; for; break; continue; pass; nested loops and loops that include compound conditional
expressions

Perform Input and Output Operations (20-25%)


Construct and analyze code segments that perform file input and output operations
Open; close; read; write; append; check existence; delete; with statement
Construct and analyze code segments that perform console input and output operations
Read input from console; print formatted text; use of command line arguments

Document and Structure Code (15-20%)


Document code segments using comments and documentation strings
Use indentation, white space, comments, and documentation strings; generate documentation
by using pydoc
Construct and analyze code segments that include function definitions
Call signatures; default values; return; def; pass

Perform Troubleshooting and Error Handling (5-10%)


Analyze, detect, and fix code segments that have errors
Syntax errors; logic errors; runtime errors
Analyze and construct code segments that handle exceptions
Try; except; else; finally; raise

Perform Operations Using Modules and Tools (1-5%)


Perform basic operations using built-in modules
Math; datetime; io; sys; os; [Link]; random
Solve complex computing problems by using built-in modules
Math; datetime; random

[Link]
Skills measured:
This exam measures your ability to accomplish the technical tasks listed below. View video
tutorials about the variety of question types on Microsoft exams.

All NIIT (Any Day Any Time Pearson VUE)


3,696.00 INR*

[Link]
Certified Python Developer

[Link]

Cost Rs.3,499
Benefits of Certification
Government certification
Certification valid for life
Lifelong e-learning access
Free Practice Tests
Get tagged as 'Vskills Certified' On [Link]

How It Works
1. Select Certification & Register
2. Receive a.) Online e Learning Access (LMS) b.) Hard copy - study material
3. Take exam at chosen Date and Venue
4. Get certified & Increase Employability

Test Details
Duration: 60 minutes
No. of questions: 50
Maximum marks: 50, Passing marks: 25 (50%).
There is NO negative marking in this module.
70 exam centres in India.

Become Certified PYTHON Programmer:


To enter Good Projects
To get Good Salaries
To get onsite Opportunities
To get quick and Good Job
To get great Salary or Increment

PCEP Certification (Entry-Level) Python Institute


[Link]
Naresh i Technologies, HYDERANAD,

04023746666

Prepared By Subba Raju Data Scientist


1 Output of the following:
var1 = &#39;NIT&#39;
print(&quot;Orignal String :-&quot;, var1)
print(&quot;Updated String :- &quot;, var1[:5] + &#39;for&#39; +
&#39;Training&#39;)
2 Output of the following:
print(&#39;\x25\x26&#39;)
3 Output of the following:
list = [1, 2, 3, None, (1, 2, 3, 4, 5), [&#39;A&#39;, &#39;B&#39;,
&#39;C&#39;]]
print(len(list))
4 Output of the following:
list = [&#39;python&#39;, &#39;learning&#39;, &#39;@&#39;, &#39;NareshIT&#39;,
&#39;for&#39;, &#39;Training&#39;]
print(list[::])
print(list[0:6:2])
print(list[ :6: ])
print(list[ :6:2])
print(list[ ::3])
print(list[ ::-2])
5 Output of the following:
d1 = [10, 20, 30, 40, 50]
d2 = [1, 2, 3, 4, 5]
print(d1- d2)
6 Output of the following:
dictionary1 = {&#39;Google&#39; : 1,
&#39;Facebook&#39; : 2,
&#39;Microsoft&#39; : 3
}
dictionary2 = {&#39;GFG&#39; : 1,
&#39;Microsoft&#39; : 2,
&#39;Youtube&#39; : 3
}
[Link](dictionary2);
for key, values in [Link]():
print(key, values)
7 Output of the following:
dictionary1 = {&#39;GFG&#39; : 1,
&#39;Google&#39; : 2,
&#39;GFG&#39; : 3
}
print(dictionary1[&#39;GFG&#39;]);
8 Output of the following:
temp = dict()
temp[&#39;key1&#39;] = {&#39;key1&#39; : 44, &#39;key2&#39; : 566}
temp[&#39;key2&#39;] = [1, 2, 3, 4]
for (key, values) in [Link]():
print(values, end = &quot;&quot;)
9 Output of the following:
temp = {&#39;GFG&#39; : 1,
&#39;Facebook&#39; : 2,
&#39;Google&#39; : 3
}
for (key, values) in [Link]():
print(key, values, end = &quot; &quot;)
10 Output of the following:
data = 50
try:
data = data/0
except ZeroDivisionError:
print(&#39;Cannot divide by 0 &#39;, end = &#39;&#39;)
else:
print(&#39;Division successful &#39;, end = &#39;&#39;)
try:
data = data/5
except:
print(&#39;Inside except block &#39;, end = &#39;&#39;)
else:
print(&#39;GFG&#39;, end = &#39;&#39;)
11 Output of the following:
data = 50
try:
data = data/10
except ZeroDivisionError:
print(&#39;Cannot divide by 0 &#39;, end = &#39;&#39;)
finally:
print(&#39;NareshIT &#39;, end = &#39;&#39;)
else:
print(&#39;Division successful &#39;, end = &#39;&#39;)
12 Output of the following:
value = [1, 2, 3, 4]
data = 0
try:
data = value[4]
except IndexError:
print(&#39;NiT&#39;, end = &#39;&#39;)
except:

Naresh i Technologies, HYDERANAD,

04023746666

Prepared By Subba Raju Data Scientist


print(&#39;NareshIT &#39;, end = &#39;&#39;)
13 Output of the following:
value = [1, 2, 3, 4, 5]
try:
value = value[5]/0
except (IndexError, ZeroDivisionError):
print(&#39;NareshIT &#39;, end = &#39;&#39;)
else:
print(&#39;NiT &#39;, end = &#39;&#39;)
finally:
print(&#39;nit &#39;, end = &#39;&#39;)
14 Output of the following:
data = [2, 3, 9]
temp = [[x for x in[data]] for x in range(3)]
print (temp)
15 Output of the following:
data = [x for x in range(5)]
temp = [x for x in range(7) if x in data and
x%2==0]
print(temp)
16 Output of the following:
temp = [&#39;NareshIT&#39;, &#39;for&#39;, &#39;Hyd&#39;]
arr = [i[0].upper() for i in temp]
print(arr)
17 Output of the following:
temp = &#39;Nareshit 22536 for 445 Nit&#39;
data = [x for x in (int(x) for x in temp if
[Link]()) if x%2 == 0]
print(data)
18 Output of the following:
data = [x for x in (x for x in &#39;Naresh 22966
for ItHyd&#39; if [Link]()) if
(x in ([x for x in range(20)]))]
print(data)
19 Output of the following:
print type(type(int))
20 Output of the following:
L = [&#39;a&#39;,&#39;b&#39;,&#39;c&#39;,&#39;d&#39;]
print &quot;&quot;.join(L)
21 Output of the following:

What is Colaboratory?
Colaboratory, or "Colab" for short, allows you to write and execute Python in your browser,
with Zero configuration required, Free access to GPUs, Easy sharing Whether you're a
student, a data scientist or an AI researcher, Colab can make your work easier.

GoogleColab:
It is a free Jupyter notebook environment that runs entirely in the cloud. It Colab support
many popular machine learning libraries which can be easily loaded in your notebook.
[Link]

Some basic commands in GoogleCoLab:


1. !cat /proc/cpuinfo
2. !cat /proc/meminfo
3 !pip install pandas
4. import pandas as pd
5. df = pd.read_csv('/content/[Link]')
6. [Link]()
etc...............!!
Python Libraries:
A Python library is a reusable chunk of code that you may want to include in your programs/
projects. A library is a collection of modules.

Python Libs:
1 NumPy:
It is widely used for carrying out mathematical operations that involve matrices.

2 SciPy
It contains various models for mathematical optimization, linear algebra, Fourier Transforms,
etc.

3 Matplotlib
It is a plotting library for the Python programming language and its numerical mathematics
extension NumPy.

4 Pandas(PANel Data System)


It is an open-source Python Library for Data Analysis, Data Manipulation and Data
Visualization.

EXAMPLE:
import scipy
import pandas
import numpy
import sklearn
print(scipy.__version__)
print(pandas.__version__)
print(sklearn.__version__)
print(numpy.__version__)

NumPy-Introduction
It stands for NUMeric PYthon or NUMerical PYthon. It is the core library for scientific
computing in [Link] was developed in 1995 by Travis Oliphant
OR
It is the fundamental library for array computing with Python
OR
A NumPy array is a homogeneous block of data organized in a multi-dimensional finite grid.
Features of Numpy
1 Multidimensional arrays.
2 Functions and operators for these arrays.
3 Python Alternative to MATLAB.
4 ndarray- n-dimensional arrays.
5 Linear algebra and random number generation.

Install NumPy
Windows & Mac OS:
$pip install numpy

Python Libraries:
A Python library is a reusable chunk of code that you may want to include in your programs/
projects. A library is a collection of modules.

Python Libs:
1 NumPy:
It is widely used for carrying out mathematical operations that involve matrices.

2 SciPy
It contains various models for mathematical optimization, linear algebra, Fourier Transforms,
etc.

3 Matplotlib
It is a plotting library for the Python programming language and its numerical mathematics
extension NumPy.

4 Pandas(PANel Data System)


It is an open-source Python Library for Data Analysis, Data Manipulation and Data
Visualization.

EXAMPLE:
import scipy
import pandas
import numpy
import sklearn
print(scipy.__version__)
print(pandas.__version__)
print(sklearn.__version__)
print(numpy.__version__)

NumPy-Introduction
It stands for NUMeric PYthon or NUMerical PYthon. It is the core library for scientific
computing in [Link] was developed in 1995 by Travis Oliphant
OR
It is the fundamental library for array computing with Python
OR
A NumPy array is a homogeneous block of data organized in a multi-dimensional finite grid.

Features of Numpy
1 Multidimensional arrays.
2 Functions and operators for these arrays.
3 Python Alternative to MATLAB.
4 ndarray- n-dimensional arrays.
5 Linear algebra and random number generation.

Install NumPy
Windows & Mac OS:
$pip install numpy

Linux OS:
$sudo apt-get install python-numpy

NumPy Array v/s List


We use python numpy array instead of a list because of the below three reasons:
1 Less Memory
2 Fast
3 Convenient

NUMPY ==> 32 Bit,


5 ==> 00000000 00000000 00000000 0000 0101
16 Bit
00000000 0000 0101
8 Bit
0000 0101

List: It is builtin type in PYTHNON: It represents the following:


Size
00000000 00000000 00000000 0001110
Reference Count
01010101 1001010 01000110 10011000 00001100 11000011 00000000 0000 0101
Object Type
11001010 10011110 01100001 01000100 11111100 00100011 00011100 00111101
Object Value
00000000 00000000 00000000 00000000 00000000 00000000 00000000 0000 0101

Example:
import numpy as np
PyArr=[Link]([2,4,5,6,7,8])
print(PyArr)
print(PyArr/2)

Example:
PyList=[2,4,5,6,7,8]
print(PyList)
print(PyList/2)
Example:
import numpy as np
print(dir(np))

Example:
import numpy as np
PyArr=[Link]([2,4,5,6,7,8])
print(help([Link]))

NumPy - Ndarray Object:


Numpy array is a powerful N-dimensional array object which is in the form of rows and
columns. We can initialize numpy arrays from nested Python lists and access it elements.

Syntax:
[Link](object, dtype = None, copy = True, order = None, subok = False, ndmin = 0)

Import NumPy
Once NumPy is installed, import it in your applications by adding the import keyword:
import numpy==> Now NumPy is imported and ready to use.

Example
import numpy
PyArr = [Link]([1, 2, 3, 4, 5])
print(PyArr)

NumPy as np=> NumPy is usually imported under the np alias.


Create an alias with the as keyword while importing:
import numpy as np => Now the NumPy package can be referred to as np instead of numpy.

Example:
import numpy as np
PyArr = [Link]([1, 2, 3, 4, 5])
print(PyArr)

Checking NumPy Version


The version string is stored under __version__ attribute.

Example
import numpy as np
print(np.__version__)

Dimensions in Arrays:
A dimension in arrays is one level of array depth (nested arrays).
nested array: are arrays that have arrays as their elements.

0-D Arrays
0-D arrays, or Scalars, are the elements in an array. Each value in an array is a 0-D array.

Example
import numpy as np
PyArr = [Link](24)
print(PyArr)

1-D Arrays
These are basic and most common arrays. It is an array that is having 0-D arrays as its
elements and thus is called as a uni-dimensional or 1-D array. A 1D array is a vector; its
shape is just the number of components.
Example: Single Dimension Array
import numpy as np
PyArr=[Link]([1,2,3,4])
print(type(PyArr))#<class '[Link]'>
print(PyArr)#[1 2 3 4]

Example:
import numpy as np
PyArr=[Link]((1,2,3,4))
print(type(PyArr))#<class '[Link]'>
print(PyArr)#[1 2 3 4]

2-D arrays
These are those arrays that contain 1-D arrays as its elements are called as 2-D arrays. 2-D
arrays are often used to represent a matrix. It is a matrix; its shape is (number of rows,
number of columns).
Example:
import numpy as np
PyArr=[Link]([[1,2,3,4],[5,6,7,8]])
print(type(PyArr))#<class '[Link]'>
print(PyArr)

O/P:
[[1 2 3 4]
[5 6 7 8]]

Example:
import numpy as np
PyArr = [Link]([[1, 2], [3, 4]])
print(PyArr)

O/P:
[[1 2]
[3 4]]

3-D arrays
An array that has 2-D arrays (matrices) as its elements is called 3-D array. These are often
used to represent a 3rd order tensor.
Example:
import numpy as np
PyArr = [Link]([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])
print(PyArr)
Checking the Number of Dimensions of Array:
ndim:
You can find the dimension of the array, whether it is a two-dimensional array or a single
dimensional array.

Example:
import numpy as np
PyArr = [Link]([1,2,3])
print([Link])

NOTE: The output is 1, it is a Single-dimensional array (one dimension).

Example:
import numpy as np
PyArr = [Link]([(1,2,3),(4,5,6)])
print([Link])

NOTE: The output is 2, it is a two-dimensional array (multi dimension).

Example:
import numpy as np
PyArr = [Link]([[(1,2,3),(4,5,6),(7,8,9),(10,11,12)]])
print([Link])

NOTE: The output is 3, it is a three-dimensional array (multi dimension).

Example:
import numpy as np
PyArr1 = [Link](4)
PyArr2 = [Link]([1, 2, 3, 4, 5])
PyArr3 = [Link]([[1, 2, 3], [4, 5, 6]])
PyArr4 = [Link]([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])
print([Link])
print([Link])
print([Link])
print([Link])

Example:
import numpy as np
# 0-d array
PyArr1 = [Link](4)
# 1-d array
PyArr2 = [Link]([1, 2, 3])
# 2-d array
PyArr3 = [Link]([[11, 62, 3], [46,95,96]])
# 3-d array
PyArr4 = [Link]([[[11, 2, 3], [48,85, 6]], [[17,78,78], [44,95, 6]]])
print([Link])
print([Link])
print([Link])
print([Link])

Higher Dimensional Arrays


An array can have any number of dimensions. You can define the number of dimensions by
using the ndmin argument.

Example:
import numpy as np
PyArr = [Link]([1, 2, 3, 4], ndmin=5)
print(PyArr)
print('number of dimensions :', [Link])

Data Types in NumPy


NumPy has some extra data types, and refer to data types with one character, like i for
integers, u for unsigned integers etc. Below is a list of all data types in NumPy and the
characters used to represent them.
i - integer
b - boolean
u - unsigned integer
f - float
m - timedelta
M - datetime
O - object
S - string
U - unicode string
V - void

int ==> refers [Link]


float ==> refers [Link]
bool ==> refers [Link]
complex ==> refers [Link].. etc.

Checking the Data Type of an Array:


dtype:
You can find the data type of the elements that are stored in an array

Example:
import numpy as np
PyArr = [Link]([1, 2, 3, 4])
print([Link])

Example:
import numpy as np
PyArr = [Link](['1', '2', '3', '4'])
print([Link]) #<U1

Example:
import numpy as np
PyArr = [Link](['11', '21', '13', '14'])
print([Link]) #<U2
Example:
import numpy as np
PyArr = [Link](['Data', 'BigData', 'Hadoop'])
print([Link]) #U7(7 bytes)

Example:
import numpy as np
PyArr = [Link]([(1,2,3)])
print([Link])

Example:size Attribute:
import numpy as np
PyArr = [Link]([1,2,3,4,5])
print([Link])

Creating Arrays With a Defined Data Type


dtype that allows us to define the expected data type of the array elements

Example:
import numpy as np
PyArr = [Link]([1, 2, 3, 4], dtype='S')
print(PyArr)
print([Link])

NOTE: For i, u, f, S and U we can define size as well. Here 'b' represents bytes string.

Example:
import numpy as np
PyArr = [Link]([1, 2, 3, 4], dtype=complex)
print(PyArr)
print([Link])

Example: Create an array with data type 4 bytes integer:


import numpy as np
PyArr = [Link]([1, 2, 3, 4], dtype='i4')
print(PyArr)
print([Link])

What if a Value Can Not Be Converted?


If a type is given in which elements can't be casted then NumPy will raise a ValueError.

NOTE:
A non integer string like 'a' can not be converted to integer (will raise an error):

Example:
import numpy as np
PyArr = [Link](['a', '2', '3'], dtype='i')
print(PyArr)
astype() method:
Converting Data Type on Existing Arrays.

Syntax:
astype(datatype)

Example:
import numpy as np
PyArr = [Link]([1.1, 2.1, 3.1])
NewArr = [Link]('i')
print(NewArr)
print([Link])

Example
Change data type from float to integer by using int as parameter value:

Example:
import numpy as np
PyArr = [Link]([1.1, 2.1, 3.1])
NewArr = [Link](int)
print(NewArr)
print([Link])

Example:
import numpy as np
PyArr = [Link]([1, 0, 3])
NewArr = [Link](bool)
print(NewArr)
print([Link])

Example:
import numpy as np
PyArr= [Link]([1.1, 2.1, 3.1])
NewArr = [Link](int)
print(NewArr)
print([Link])

itemsize:
You can calculate the byte size of each element.

Example:
import numpy as np
PyArr = [Link]([1,2,3])
print([Link])

NOTE: Every int element occupies 4 byte in the above numpy array.

Python NumPy Array Creation - Empty, Zeroes and Ones


In Numpy, a new ndarray object can be constructed by the following given array creation
routines or using a low-level ndarray constructor
1 [Link]
2 [Link]
3 [Link]
4. [Link]

[Link]:
This is used to create an uninitialized array of specified shape and dtype. Elements in an array
will show random values because they are not initialized.

Syntax:
[Link](shape, dtype)

Example:
import numpy as np
# an array with 4 rows and 3 columns
PyArr = [Link]([4,3], dtype = int)
print (PyArr)

Zero Value Array - Using [Link]


This is used to return a new array of the specified size and each array item will be initialized
with 0.

Syntax:
[Link](shape, dtype)

Example:
import numpy as np
PyArr = [Link]((3,3), dtype = int)
print(PyArr)

One Value Array - Using [Link]


This is used to return a new array of the specified size and each array item will be initialized
as 1.

Syntax:
[Link](shape, dtype)

Example:
import numpy as np
PyArr = [Link]((3,3), dtype = int)
print(PyArr)

[Link]():
Return a new array with the same shape and type as a given array filled with a fill_value.

Syntax:
[Link](shape, fill_value, dtype = None)

Parameters:
shape : Number of rows
fill_value : [bool, optional] Value to fill in the array.
dtype : [optional, float(by Default)] Data type of returned array.

Example:
import numpy as np
PyArr = [Link]([2, 2], 67, dtype = int)
print("\nMatrix a : \n", PyArr)

PyArr = [Link]([3, 3], 10.1)


print("\nMatrix c : \n", PyArr)

What is Pandas?
Pandas is a Python library. Pandas is used to analyze data.
Pandas is a Python library used for working with data sets.
It has functions for analyzing, cleaning, exploring, and manipulating data.
The name "Pandas" has a reference to both "Panel Data", and "Python Data Analysis" and
was created by Wes McKinney in 2008.

Why Use Pandas?


Pandas allows us to analyze big data and make conclusions based on statistical theories.
Pandas can clean messy data sets, and make them readable and relevant.
Relevant data is very important in data science.

What Can Pandas Do?


1 High performance data analysis tool
2 Working with large data sets
3 Supports different file formats
4 Working with missing data
5 Data represents in tabular format
6 Indexing-Slicing-Subsetting the large data sets
[Link] merge and join two different data sets
8. Reshape the datasets.

Installation of Pandas
If you have Python and PIP already installed on a system, then installation of Pandas is very
easy.

Install it using this command:


$pip install pandas

Syntax:
import pandas

Checking Pandas Version


The version string is stored under __version__ attribute.

Example
import pandas as pd
print(pd.__version__)

Show installed versions:


Need to know the versions of pandas' dependencies.

Example:
import pandas as pd
print(pd.show_versions())

Pandas as pd ==> Pandas is usually imported under the pd alias.


alias: In Python alias are an alternate name for referring to the same thing.

Syntax:
import pandas as pd

Pandas deals with the following three data structures:


The best way to think of these data structures is that the higher dimensional data structure is a
container of its lower dimensional data structure.

Data Structure Dimensions Description


Series 1 1D homogeneous array, size-immutable.
Data Frames 2 2D size-mutable tabular structure(Rows&Cols)
Panel 3 Multi-Dimensional(3D), size-mutable array.

NOTE:
DataFrame is widely used and one of the most important data structures. Panel is used much
less.

Pandas Series
A Pandas Series is like a column in a table. It is a one-dimensional array holding data of any
type. We can easily convert the list, tuple, and dictionary into series using "series' method.

1. Empty Series
2. Series using Arrays
3. Series using Lists
4. Series using Dictionary

1. Empty Series
We can easily create an empty series in Pandas which means it will not have any value.

Syntax:
<series object> = [Link]()

Example:
import pandas as pd
PySer = [Link]()
print (PySer) #Series([], dtype: float64)

Creating a Series using inputs:


1 Array
2 Scalar value
3. List
4 Dict

Creating Series from Array:


We have to import the numpy module and then use array() function in the program.

Example:
import pandas as pd
import numpy as np
PyData = [Link](['P','a','n','d','a','s'])
PySer = [Link](PyData)
print(PySer)

Scalar value
If we take the scalar values, then the index must be provided. The scalar value will be
repeated for matching the length of the index.

Example:
import pandas as pd
PySer= [Link](4, index=[0, 1, 2, 3])
print(PySer)
print(type(PySer))

Create a Series from List


Example
Create a simple Pandas Series from a list:
import pandas as pd
PyArr=[1, 7, 2]
PyVar = [Link](PyArr)
print(PyVar)

Create a Series from dict


If the dictionary object is being passed as an input and the index is not specified, then the
dictionary keys are taken in a sorted order to construct the index.

Example:
import pandas as pd
PyDict = {'PY' : 100, 'DS' : 91, 'ML' : 62}
PySer = [Link](PyDict)
print (PySer)

Example
import pandas as pd
Calories = {"day1": 420, "day2": 380, "day3": 390}
PyVar = [Link](Calories)
print(PyVar)

Example:
import pandas as pd
Calories = {"day1": 420, "day2": 380, "day3": 390}
PyVar = [Link](Calories, index = ["day1", "day2"])
print(PyVar)

Accessing data from series with Position:


If nothing else is specified, the values are labeled with their index number. First value has
index 0, second value has index 1 etc. This label can be used to access a specified value.

Example
import pandas as pd
PyArr=[1, 7, 2]
PyVar = [Link](PyArr)
print(PyVar)
print(PyVar[0])
print(PyVar[1])

With the index argument, you can name your own labels.
Example:
import pandas as pd
PyArr=[1, 7, 2]
PyVar = [Link](PyArr, index = ["x", "y", "z"])
print(PyVar)

Example:
import pandas as pd
PyArr=[1, 7, 2]
PyVar=[Link](PyArr, index = ["x", "y", "z"])
print(PyVar["y"])

Series object attributes


The Series attribute is defined as any information related to the Series object such as size,
datatype. etc.

Attributes Description
[Link] Defines the index of the Series.
[Link] It returns a tuple of shape of the data.
[Link] It returns the data type of the data.
[Link] It returns the size of the data.
[Link] It returns True if Series object is empty, otherwise returns false.
[Link] It returns True if there are any NaN values, otherwise returns false.
[Link] It returns the number of bytes in the data.
[Link] It returns the number of dimensions in the data.

Example:
import pandas as pd
PySer=[Link](data=[11.2,18.6,22.5], index=['a','b','c'])
print([Link])
print([Link])
print([Link])
print([Link])
print([Link])
print([Link])
print([Link])
print([Link])
print([Link])

Series Functions
It is used to map the values from two series that have a common column.

Syntax:
[Link](arg, na_action=None)

Parameters
arg: function, dict, or Series.
na_action: {None, 'ignore'}, Default value None. If ignore, it returns null values

Example:
import pandas as pd
import numpy as np
a = [Link](['PYTHON', 'ML', 'DL', [Link]])
print([Link]({'PYTHON': 'DS','ML':'MATHS'}))

Example:
import pandas as pd
import numpy as np
a = [Link](['PYTHON', 'JAVA', 'C++', [Link]])
[Link]({'PYTHON': 'DS'})
print([Link]('I like {}'.format, na_action='ignore'))

Pandas [Link]()
It is defined as a function for calculating the standard deviation of the given set of numbers,
DataFrame, column, and rows.

Syntax:
[Link]()

Example:
import numpy as np
print([Link]([4,7,2,1,6,3]))
print([Link]([6,9,15,2,-17,15,4]))

Example:
import pandas as pd
info = {
'Name':['Raju','Sara','John','Sita'],
'sub1_Marks':[52,38,42,37],
'sub2_Marks':[41,35,29,36]}
data = [Link](info)
print([Link]())
Pandas Series.to_frame()
It is used to convert the series object to the DataFrame.

Syntax:
Series.to_frame(name=None)

Example:
import pandas as pd
PyData = [Link](["Raju", "Rama", "John"],
name="Vals")
print(PyData.to_frame())

Pandas [Link]()
To extract the unique values from the columns.

Syntax:
[Link](values)

Example:
import pandas as pd
print([Link]([Link]([2, 1, 3, 3])))
print([Link]([Link]([2, 3, 3, 3])))
print([Link]([Link]([2, 3, 3, 3,0,0,1])))

Pandas Series.value_counts()
It returns a Series that contain counts of unique values.

Syntax:
Series.value_counts()

Example:
import pandas as pd
import numpy as np
PyData = [Link]([2, 1, 1, [Link], 3])
print(PyData.value_counts())

Example:
import pandas as pd
import numpy as np
PyData = [Link]([1, 3, 2, 2, 1, [Link]])
print(PyData.value_counts())
PyData = [Link]([1, 3, 2, 2, 1, [Link]])
print(PyData.value_counts(dropna=False))

Pandas DataFrames
A Pandas DataFrame is a 2 dimensional data structure, like a 2 dimensional array, or a table
with rows and columns. It is an efficient data structure.

Parameter & Description:


data: It consists of different forms like ndarray, series, map, constants, lists, array.
index: The Default [Link](n) index is used for the row labels if no index is passed.
columns: The default syntax is [Link](n) for the column labels. It shows only true if no
index is passed.
dtype: It refers to the data type of each column.
copy(): It is used for copying the data.

Create a DataFrame
We can create a DataFrame using following ways:
1 dict
2 Lists
3 Numpy ndarrrays
4 Series

Create an empty DataFrame


Example:
import pandas as pd
df = [Link]()
print (df)

Create a DataFrame using List:


Example:
import pandas as pd
PyList=['Python', 'Pandas']
df = [Link](PyList)
print(df)

Create a DataFrame from Dict of ndarrays/ Lists


Example:
import pandas as pd
PyData = {'ID' :[101, 102, 103],'Department' :['Programmer','Tester','NetworkEng.',]}
df = [Link](PyData)
print (df)

Named Indexes
With the index argument, you can name your own indexes.

Example:
import pandas as pd
PyData = {'ID' :[101, 102, 103],'Department' :['Programmer','NetworkEng','Tester']}
df = [Link](PyData,index=['First','Second','Third'])
print (df)

Create a DataFrame from Dict of Series:


Example:
import pandas as pd
PySer={'One' : [Link]([1, 2, 3 ], index=['a', 'b', 'c']),
'Two' : [Link]([1, 2, 3, 4, 5], index=['a', 'b', 'c', 'd', 'e'])}
df = [Link](PySer)
print (df)
Column Selection
Example:
import pandas as pd
PySer={'One' : [Link]([1, 2, 3 ], index=['a', 'b', 'c']),
'Two' : [Link]([1, 2, 3, 4, 5], index=['a', 'b', 'c', 'd', 'e'])}
df = [Link](PySer)
print (df['One'])

Column Addition
import pandas as pd
PySer={'One' : [Link]([1, 2, 3 ], index=['a', 'b', 'c']),
'Two' : [Link]([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}
df = [Link](PySer)
df['Three']=[Link]([20,40,60],index=['a','b','c'])
df['Four']=df['One']+df['Three']
print (df)

Common questions

Powered by AI

A for loop with an else clause in Python is particularly useful in scenarios where you want to execute a block of code once the loop has exhausted its iteration over the sequence, without interruption by a break statement. Its unique feature is that the else clause executes only if the loop completes all iterations normally, providing a way to handle post-loop actions contingent on the loop's completion .

Nested if-else structures enhance conditional logic in Python by allowing the evaluation of multiple conditions in a hierarchical manner. This is particularly useful in scenarios where one needs to check conditions that depend on the outcome of preceding conditions. For instance, when determining a student's grade based on scores, one might first check if a score is passing, then further nest conditions to assign a specific letter grade .

The ndim attribute in NumPy arrays is used to determine the number of dimensions of an array, which is crucial in data analysis for shaping data correctly for processing and computational requirements. For instance, determining if data should be reshaped or kept in its original form while applying functions computationally is vital. Knowing the dimensions helps in array manipulation, ensuring the appropriate functions are used with the intended data structure .

The break statement immediately terminates the enclosing loop, bypassing the else clause if present. On the other hand, the continue statement skips the remainder of the current loop iteration and moves on to the next iteration. When a loop is terminated by a break statement, any else block attached to the loop is ignored. However, if a loop exits normally without encountering a break, the else clause is executed .

Inheritance in Python is a concept where a class (derived/child class) inherits attributes and behaviors from another class (base/parent class). This facilitates reuse of code, relationship modeling, and structure in complex systems. Types include single, multiple, multilevel, and hierarchical inheritance. For example, in multilevel inheritance, a base class provides common features, a derived class builds on it, and another derived class can extend or customize features further. This design structure supports scalability and organized code architecture .

The join() method in Python is specifically designed to concatenate iterable elements (like list strings) into a single string using a specified separator. It is generally more efficient than using the + operator in loops to concatenate strings, as it avoids the overhead of creating several intermediate strings. While + concatenation is simple and works well in small, static concatenations, join() is preferable for larger or dynamic concatenations as it offers better performance and flexibility .

The elif statement in Python is used to check multiple expressions for TRUE and execute a block of code as soon as one of the conditions evaluates to TRUE. This differs from a simple if-else structure by allowing the addition of multiple conditional checks, rather than just a single binary choice. The elif chain can have multiple elif blocks, providing greater flexibility in complex decision-making scenarios .

Polymorphism in Python allows for defining methods in the derived classes that have the same name as in their parent classes, where the definition of the method in the derived class will override the parent class's method. This is known as method overriding. For example, if a base class 'A' has a method named 'display', a derived class 'B' can also define a 'display' method. When called on an instance of 'B', the 'display' method specific to 'B' is executed, which demonstrates polymorphism .

A try-except block with multiple except clauses is designed to handle different types of exceptions by specifying a distinct block of code for each type of exception. This allows the program to handle unexpected events or errors gracefully, avoiding crashes and ensuring continuity of program execution. It's beneficial for robust program design because it provides specific responses to different error scenarios, such as handling arithmetic errors separately from file I/O errors, improving program reliability and user experience .

In Python, a list is mutable, ordered, and allows duplicate elements, enclosed by square brackets []. A tuple is similar to a list but is immutable, meaning it cannot be altered after creation, and is enclosed in parentheses (). A set is mutable and does not allow duplicate elements but is unordered, enclosed in curly brackets {}. A dictionary is also mutable and uses key-value pairs, where keys are immutable (hashable) and must be unique; it's also enclosed in curly brackets {} .

You might also like