Python Notes
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.
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
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:
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
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]......!!
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...!!
>>> 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)
Colors Meaning
Black Standard Input
Blue Standard Output
Red Error or Comment
Green String or Charater data
Purple/Orange Function/Statement/Keyword...!!
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
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.
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 #
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.
Example:
1. Goto IDLE, Select File and click on New or Ctrl+N (to Open New Window)
2. Enter required python statements or commands
INSIDE PYTHON
After successful installation of Python, It is the combination of Interpreter and Support
Library.
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)
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.
Example:
import py_compile
print(dir(py_compile))
Example:
import compileall
print(dir(compileall))
Example:
import py_compile
py_compile.compile("[Link]")
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.
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])
Debugging in PYCHARM:
It is the process of identifying and fixing problems in Code. The following short-cut keys are
required to debug..!!
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.
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..!!
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.
Define Conda?
It is an open source package management system and environment management system for
installing multiple versions of software packages.
What is pip
It is a package manager for Python programming language.
Installation
$python [Link]
$pip install pip
Syntax:
pip list [options]
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]
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
more@=1000000
#illegal because it contains special character
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.
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
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])
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)
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
Example1:
x1q3z9ocd = 35.0
x1q3z9afd = 12.50
x1q3p9afd = x1q3z9ocd * x1q3z9afd
print(x1q3p9afd)
Example2:
a = 3;b = 2;print(a*b)
Syntax:
bin(number)
Example:
x = 0b101010
print(x )
Example
x = bin(65)
print(x)
Syntax:
oct(number)
Example
x = oct(65)
print(x)
Syntax:
hex(number)
Example:
x = hex(19)
print(x)
Example:
x = hex(64)
print(x)
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.
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.
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)
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))
Syntax:
float(value)
Example:
a=100
print(float(a))
NOTE:
We can convert any value to float type except complex type.
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"
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)
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))#ف
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)
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.
Example:
if True:
print("True")
else:
print("False")
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
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)
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)
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)
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)
Example:
PyStr1 = "Hello"; PyStr2 = "World"
# or operator on string
print("PyStr1 or PyStr2: ", PyStr1 or PyStr2)
print("PyStr2 or PyStr1: ", PyStr2 or PyStr1)
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
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)
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)
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
Example:
print("%s having %s Years Experience in IT." %("KSRAJU","15+"))
print("%s having %d Years Experience in IT." %("KSRAJU",15))
Example:
name = "RaaJ"
Example:
name = "RaaJ"
age = 23
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))
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
OPERATOR MEANING
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
~ Bitwise complement
<< Shift left
>> Shift right
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
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
Syntax:
Bitwise Exclusive OR Operation = a ^ b
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
In Mathematical Approach:
x=10 ==> 0000 1010 (is Binary Number)
Binary Ones Complement is ==> 1111 0101
STEP1:
x=10 ==> 0000 1010 (is Binary Number)
0000 1010
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.
STEP3:
Binary TWOs Complement:
In PYTHON adding '1' to Binary Ones Complement is called Binary TWOs Complement.
0000 1011
+1
-----------------
0000 1100 ==> -12
----------------
EXAMPLE:
a=10
print(a<<2)#40
print(a>>2)#2
Example:
print("First Line");print("Second Line");print("Third Line")
5 == equal
6 != not equal
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)
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:
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")
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)
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)
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; # 20 + (150/5)
print ("Value of a + (b * c) / d is ", e)
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.
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]())
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])
Syntax:
range(a) range(a,b) range(a,b,c)
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})
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)
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)
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 :)')
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")
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:
# 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")
Syntax
for [first iterating variable] in [outer loop]: # Outer loop
[do something] # Optional
for [second iterating variable] in [nested loop]: # Nested loop
[do something]
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(1,pattern+1):
for j in range(1,pattern+2-i):
print("*",end="")
print()
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
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:
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])
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=" ")
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)
Example:
from sys import argv
print(argv[0])
print(argv[1])
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.
Example:
first="First"; second="Second"
fullstr=first+" "+second
print(fullstr)
Example:String Repetition
print('Spam'*3)
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)
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])
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])
Example:
PyStr='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:
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.
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]())
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))
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
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))
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]())
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]())
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']
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)
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[:])
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])
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")
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)
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)
Syntax:
[Link](iterable)
Example:
alist1 = ['a', 'b', 'c']
[Link](['d', 'e','f'])
print(alist1)
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)
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)
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))
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)
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']
Example:
PyList=['cc','b','aaa','eeee','ddddddd']
print(PyList)
[Link](key=len)
print(PyList)
Example:
PyList=["Big Data", "Hadoop", "Spark", "IoT"]
print(PyList)
[Link]()
print(PyList)
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)
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)
pop()
1) Remove last element from the List.
2) It will return removed element.
3) If List has no items then we get Error.
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)
Example:
PyList=[]
for i in range(10):
if i%2==1:
[Link](i)
print(PyList)
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
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)
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.
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]))
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]()])
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 )
Example:
myList=[1,2,3,4,5,6]
print(myList)
yourList=myList
print(yourList)
myList[0]="NareshIT"
print(myList)
print(yourList)
Example:
import copy
print(dir(copy))
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)
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)
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
Create an Array
We can create a Python array with comma separated elements between 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:
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:
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])
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])
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])
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"
Example:
PyTuple = ("Data Science")
print(type(PyTuple))#<class 'tuple'>
PyTuple = "Data Science",
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)
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)
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])
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']
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
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)
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)
Syntax:
tuple(iterable)
Parameter:
iterable (optional) an iterable (list, range etc.) or an iterator object
#tuple to List
MyTuple=(1,2,3,4)
print(type(MyTuple))
print(MyTuple)
MyList=list(MyTuple)
print(type(MyList))
print(MyList)
Python Sets
SET is an unordered collection of unique elements
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'>
Example:
NumSet = set([0, 1, 2, 3, 4, 5])
for n in NumSet:
print(n)
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()
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)
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)
Syntax:
[Link](element)
Example:
NumSet = set([0, 1, 2, 3, 4, 5])
[Link](0)
print(NumSet)
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)
Syntax:
[Link](set2)
Example:
PySetx=set(["Big Data", "Data Science"])
PySety=set(["Data Science", "Spark"])
PySeta = PySetx |PySety #Union
print (PySeta)
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)
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)
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))
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))
Syntax:
[Link]()
Example:
PySetx = set(["Big Data", "Data Science"])
PySetd = [Link]()
print(PySetd)
Example:
PySet={4,5,8,2.2}
print(PySet)#{8, 2.2, 4, 5}
print(sorted(PySet))#[2.2, 4, 5, 8]
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
Limitations:
1 Access Very Slow
2 No Index to access
3 We sholud travel sequentially
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
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.
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)
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'}
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))
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))
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')
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
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'])
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}
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.!
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()
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()
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))
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)
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 )
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()
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))
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()
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:
# 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()
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)
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)
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)
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
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)
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))
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)
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.
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: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)
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()
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")
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
@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.
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()
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()
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()
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))
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()
Syntax:
import module1[, module2[,... moduleN]
Example:[Link]
import MyMod
MyMod.MyFun1()
MyMod.MyFun2()
print("END")
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)
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)
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))
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.
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))
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)))
Syntax:
[Link](x,y)
Example:
import math
print([Link](100, 2))
print([Link](2, 4))
print([Link](3, 0))
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))
Example:
import random
print([Link]())
print([Link]())
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))
Syntax:
[Link](x,y)
Example:
import random
print([Link](1,20))
print([Link](1,20))
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))
Syntax:
[Link](x)
Example:
import random
items=[1,2,3,4,5,6,7]
print(items)
[Link](items)
print(items)
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))
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))
Example:
from decimal import Decimal
x=1/3
print(type(x))
print(x)
y = Decimal(1) / Decimal(3)
print(type(y))
print(y)
print("----------------------")
x = Decimal('0.1') + Decimal('0.1') + Decimal('0.1')
print(x == Decimal('0.3'))
print(float(x) == 0.3)
print(x)
Example:
import string
print(string.ascii_letters)
print(string.ascii_lowercase)
print(string.ascii_uppercase)
print([Link])
print([Link])
print([Link])
PIC: PackageModuleStructure:
Syntax:
import [Link]
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])
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)
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.
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)
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)
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))
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)
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
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)
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)
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))
Syntax
formatmonth(theyear, themonth, withyear=True)
Example:
import calendar
cal=[Link](firstweekday=0)
print([Link](2020,2))
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))
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)
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)
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
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.
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)
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]()
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)
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-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")
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)
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
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
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:
#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)
Example:
Reading Octal values and Display Decimal Value..!!
def OctToDec(value):
try:
return int(value, 8)
except ValueError:
return "Invalid Octal Value"
#Reading Values
input1 = input("Enter Valid Hexa Value: ")
input2 = input("Enter Valid Hexa Value: ")
input3 = input("Enter Valid Hexa Value: ")
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 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")
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")
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]);
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 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")
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])
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:
MyFile1=open("[Link]",mode="rb")
MyFile2=open("[Link]",mode="wb")
Byts=[Link]()
[Link](Byts)
print("New Image is : [Link]")
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)
Syntax
[Link](current_file_name, new_file_name)
Example:
import os
[Link]("[Link]","[Link]")
Syntax
[Link](file_name)
Example
import os
[Link]("[Link]")
Syntax
[Link]("newdir")
Example
import os
[Link]("PYTHON")
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()
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.
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.
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]
Syntax:
[Link]([chars]);
Example:
path="[Link]"
lines=[line for line in open(path)]
print(lines[0])
print(lines[1].strip())
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..!!
Each built-in logging level has been assigned its numeric value.
1 NOTSET ==> 0
2 DEBUG ==> 10
3 INFO ==> 20
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")
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..!!')
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..!!')
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.
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.
#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...!!
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
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
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:
from re import *
StrPatt = '^s...a$'
PyStr = 'subba'
PyResult = match(StrPatt, PyStr)
if(PyResult):
print("Striing Pattern Matched")
else:
print("String Pattern Not Matched")
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))
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)
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:
import re
result=[Link](r'\w+','Naresh i Technologies Leader in IT Training')
print (result)
Example:
import re
result=[Link](r'\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)
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)
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'))
NOTE: We can also use method [Link]() to replace these multiple delimiters with one as
space.
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)
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()
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
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))
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")
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")
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.
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:
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]=[]
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__()
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'
Example:
class Student:
roll_num = 101
name = "Joseph"
def display(self):
print(self.roll_num,[Link])
st = Student()
[Link]()
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
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.
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__)
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.
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
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.
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__)
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
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:
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...")
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])
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
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:
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()
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 )
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)
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'>
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()
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
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
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.
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: ")
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]()
Multiple Inheritance:-
You can derive a child class from more than one base (Parent) class.
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()
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
obj = C()
[Link]()
print([Link]())
Example2:Case-2
class A:
def process(self):
print('A process()')
class B:
def process(self):
print('B process()')
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()')
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]()
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()
SS=Second()
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])
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]()
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....")
def main():
obj1=D()
obj1.m()
if __name__=="__main__":
main()
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)
if __name__=="__main__":
main()
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()
def main():
obj1=D()
obj1.m()
if __name__=="__main__":
main()
if __name__ =='__main__':
__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__)
# [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].
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.
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])
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()
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
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)
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.
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])
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()
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
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
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)
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"))
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.
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.
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!")
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..!
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]()
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)
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]())
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
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
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
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
Example:
from abc import ABC
class BaseClass(ABC): #Abstract Base Class
def BaseMethod(self):
print("AbstractBaseClass")
#Driver code
CC=Concrete()
[Link]()
Multi Tasking:
Executing several tasks simultaneously is the concept of multitasking.
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.
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!")
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..!
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]()
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)
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
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
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]()
[Link]()
[Link]()
[Link]()
[Link]()
print("done in : ",[Link]()-t)
Save the above XML source code with [Link] @ spyder or @PyCharm installed
location..!!
NOTE:
Go to [Link] file, change book as magzine and run the following script.
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>
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..!!")
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]
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")
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.
Example:
import [Link]
mydb = [Link](host="localhost",user="root",passwd="root")
mycursor = [Link]()
[Link]("SHOW DATABASES")
for data in mycursor:
print(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]
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")
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.
Example:
import [Link]
mydb = [Link](host="localhost",user="root",passwd="root")
mycursor = [Link]()
[Link]("SHOW DATABASES")
for data in mycursor:
print(data)
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")
Example:
import [Link]
mydb = [Link](host="localhost",user="root",passwd="root",
database='student')
mycursor = [Link]()
[Link]("SHOW TABLES")
for data in mycursor:
print(data)
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")
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)
Example:
import [Link]
mydb = [Link](host="localhost",user="root",passwd="root",
database='student')
mycursor = [Link]()
[Link]("SELECT * FROM students")
myresult = [Link]()
print(myresult)
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)
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)
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")
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 )");
ORACLE:
It is an ORDBMS developed and marketed by Oracle Corporation.
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.
Update Oracle
$pip install -U 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)
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
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.
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
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.
Example:
$django-admin startproject BFSI
$cd BFSI
$ tree /f
__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.
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.
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.
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]()
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)
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()
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]()
2. Unsupervised Learning
Group and interpret data based only on input data.
a. Clustering
b. Principal Component Analysis
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
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
Disadvantages:
1 It takes MoreTime/MoreResources/Both
2 Comparing large amount of data is difficult
3 Less Test Coverage, Less Accuracy
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
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
Selenium License:
All selenium projects released under the license of Apache 2.0
Anybody can download and use
Web Browsers
1) IE 2) Firefox 3) Chrome 4) Safari 5) Opera ...!
a) Selenium IDE:
It is Firefox Add on , It is prototyping tool
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
Syntax:
import selenium
Syntax:
from selenium import webdriver
Example:
import selenium
print(dir(selenium))
Example:
from selenium import webdriver
print(dir(webdriver))
[Link]
PYTHON
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]
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
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:
=============================================================
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========================
-------------------------------------------------------------
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:
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.
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.
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]')
Example:
import qrcode
data = '[Link]'
qr = [Link](data)
[Link]('[Link]')
[Link]()
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.
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.
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
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
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)
import random
Step -2
Greet your friend who is playing you game today.
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())
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
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)
[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.
[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.
04023746666
04023746666
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]
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.
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.
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
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]))
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)
Example:
import numpy as np
PyArr = [Link]([1, 2, 3, 4, 5])
print(PyArr)
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])
Example:
import numpy as np
PyArr = [Link]([(1,2,3),(4,5,6)])
print([Link])
Example:
import numpy as np
PyArr = [Link]([[(1,2,3),(4,5,6),(7,8,9),(10,11,12)]])
print([Link])
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])
Example:
import numpy as np
PyArr = [Link]([1, 2, 3, 4], ndmin=5)
print(PyArr)
print('number of dimensions :', [Link])
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])
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])
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.
[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)
Syntax:
[Link](shape, dtype)
Example:
import numpy as np
PyArr = [Link]((3,3), dtype = int)
print(PyArr)
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)
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.
Installation of Pandas
If you have Python and PIP already installed on a system, then installation of Pandas is very
easy.
Syntax:
import pandas
Example
import pandas as pd
print(pd.__version__)
Example:
import pandas as pd
print(pd.show_versions())
Syntax:
import pandas as pd
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)
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))
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)
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"])
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.
Create a DataFrame
We can create a DataFrame using following ways:
1 dict
2 Lists
3 Numpy ndarrrays
4 Series
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)
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)
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 {} .