Class Python
Class Python
PYTHON
PYTHON
Python is a popular programming language. It was created by Guido van
Rossum, and released in 1991.
PYTHON
Python works on different platforms (Windows, Mac, Linux, Raspberry
Pi, etc).
Python has a simple syntax similar to the English language.
Python has syntax that allows developers to write programs with fewer
lines than some other programming languages.
Python runs on an interpreter system, meaning that code can be
executed as soon as it is written. This means that prototyping can be very
quick.
Python can be treated in a procedural way, an object-orientated way or
a functional way.
Download
https://www.python.org/
PYTHON
Python Commands
• Check version
python --version
• Execute Programs
python helloworld.py
• Simple Example helloworld.py
print("Hello, World!")
PYTHON
Python Command Line.
To test a short amount of code in python sometimes it is quickest and
easiest not to write the code in a file. This is made possible because
Python can be run as a command line itself.
C:\Users\Your Name>python
C:\Users\Your Name>py
Hello, World!
PYTHON
Python Indentation
•Indentation refers to the spaces at the beginning of a code line.
•Where in other programming languages the indentation in code is for readability only, the indentation in Python is very
important.
•Python uses indentation to indicate a block of code.
•Example
if 5 > 2:
print("Five is greater than two!")
if 5 > 2:
print("Five is greater than two!")
print("Five is greater than two!")
if 5 > 2:
print("Five is greater than two!")
print("Five is greater than two!")
Python Variables
•In Python, variables are created when you assign a value to it:
x=5
y = "Hello, World!“
•Example
x=5
y = "John"
print(x)
print(y)
Rohan S. Suryawanshi Mob No.:-7276702802
Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER
Python Variables
•Assign Value to Multiple Variables
Python allows you to assign values to multiple variables in one line:
•Example-
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
#######################
x = "awesome"
print("Python is " + x)
#######################
x = "Python is "
y = "awesome"
z= x+y
print(z)
#######################
x=5
y = 10
print(x + y)
#######################
x=5
y = "John"
print(x + y)
Rohan S. Suryawanshi Mob No.:-7276702802
Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER
y=float(x)
x = str("Hello World") -> str
x = int(20) -> int
x = float(20.5) -> float
x = complex(1j) -> complex
x = list(("apple", "banana", "cherry")) -> list
x = tuple(("apple", "banana", "cherry")) -> tuple
x = range(6) -> range
x = dict(name="John", age=36) -> dict
x = set(("apple", "banana", "cherry")) -> set
x = frozenset(("apple", "banana", "cherry")) -> frozenset
x = bool(5) -> bool
x = bytes(5) -> bytes
x = bytearray(5) -> bytearray
x = memoryview(bytes(5)) -> memoryview
Rohan S. Suryawanshi Mob No.:-7276702802
Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER
Python Elif
•The elif keyword is pythons way of saying "if the previous conditions were not true,
then try this condition".
Python Else
The else keyword catches anything which isn't caught by the preceding conditions.
Rohan S. Suryawanshi Mob No.:-7276702802
Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER
Example
a = 33
b = 200
if b > a:
print("b is greater than a")
######################################
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
#####################################
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
Rohan S. Suryawanshi Mob No.:-7276702802
Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER
Example
a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")
############################
a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions is True")
#############################
#Nested If
x = 41
if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")
Rohan S. Suryawanshi Mob No.:-7276702802
Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER
if b > a:
pass
While loop
With the while loop we can execute a set of statements as long as a condition is
true.
Example
i=1
while i < 6:
print(i)
i += 1
Example
i=1
while i < 6:
print(i)
if i == 3:
break
i += 1
Rohan S. Suryawanshi Mob No.:-7276702802
Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER
While loop
For loop
A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set,
or a string).
Example
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
For loop
The continue Statement
With the continue statement we can stop the current iteration of the loop, and continue
with the next
Example
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)
For loop
Nested Loops
A nested loop is a loop inside a loop.
Example
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
for x in adj:
for y in fruits:
print(x, y)
For loop
The range() Function
To loop through a set of code a specified number of times, we can use the range() function,
The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1
(by default), and ends at a specified number-1.
Example
for x in range(6):
print(x)
#range(6) is not the values of 0 to 6, but the values 0 to 5.
The range() function defaults to 0 as a starting value, however it is possible to specify the starting
value by adding a parameter: range(2, 6), which means values from 2 to 6 (but not including 6).
Example
for x in range(2, 6):
print(x)
The range() function defaults to increment the sequence by 1, however it is possible to specify the
increment value by adding a third parameter: range(2, 30, 3)
Example
for x in range(2, 30, 3):
print(x)
Rohan S. Suryawanshi Mob No.:-7276702802
Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER
String
String in python are surrounded by either single quotation marks, or double quotation
marks.
Example
print("Hello")
a = "Hello"
print(a)
Slicing
You can return a range of characters by using the slice syntax.
b = "Hello, World!"
print(b[2:5])
b = "Hello, World!"
print(b[-5:-2])
Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802
Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER
String Length
a = "Hello, World!"
print(len(a))
String Methods
Strip-The strip() method removes any whitespace from the beginning or the end:
a = " Hello, World! "
print(a.strip()) # returns "Hello, World!"
The split() method splits the string into substrings if it finds instances of the separator:
a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']
Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802
Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER
String Methods
String Concatenation
To concatenate, or combine, two strings you can use the + operator.
a = "Hello"
b = "World"
c=a+b
print(c)
a = "Hello"
b = "World"
c=a+""+b
print(c)
Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802
Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER
String Format
age = 36
txt = "My name is John, I am " + age
txt = "My name is John, I am " + str(age)
print(txt)
age = 36
txt = "My name is John, and I am {}"
print(txt.format(age))
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))
quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))
Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802
Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER
Python Operators
Arithmetic operators
+ Addition x + y
-Subtraction x - y
-* Multiplication x * y
-/ Division x / y
-% Modulus x % y
-** Exponentiation x ** y
-// Floor division x // y
Assignment operators
= , += , -= , *= ,/= , %= , //= , **= ,&= , |= ,^=,>>=,<<=
Python Operators
Comparison operators
== Equal
!= Not equal
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to x <= y
Logical operators
and - Returns True if both statements are true x < 5 and x < 10 or Returns True if one of the statements is true x < 5 or - x < 4 not
Reverse the result, returns False if the result is true not(x < 5 and x < 10)
Identity operators
is -Returns true if both variables are the same object x is y
is not -Returns true if both variables are not the same object x is not y
Membership operators
in - Returns True if a sequence with the specified value is present in the object x in y
not in -Returns True if a sequence with the specified value is not present in the object x not in y
Bitwise operators
& AND Sets each bit to 1 if both bits are 1
| OR Sets each bit to 1 if one of two bits is 1
^ XOR Sets each bit to 1 if only one of two bits is 1
~ NOT Inverts all the bits
<< Zero fill left shift Shift left by pushing zeros in from the right and let the leftmost bits fall off
>> Signed right shift Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off
Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802
Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER
List
A list is a collection which is ordered and changeable. In Python lists are written
with square brackets.
Example
Create a List:
thislist = ["apple", "banana", "cherry"]
print(thislist)
List
Example
Access Items
You access the list items by referring to the index number:
Range of Indexes
List
Change Item Value
To change the value of a specific item, refer to the index number:Example
Change the second item:
thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant"
print(thislist)
List Length
thislist = ["apple", "banana", "cherry"]
print(len(thislist))
Add Items
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)
Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802
Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER
List
thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange")
print(thislist)
List
Copy a List
You cannot copy a list simply by typing list2 = list1, because: list2 will only be a
reference to list1, and changes made in list1 will automatically also be made in
list2.
There are ways to make a copy, one way is to use the built-in List method copy().
List
Join Two Lists
for x in list2:
list1.append(x)
print(list1)
###############################################
Use the extend() method to add list2 at the end of list1:
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
list1.extend(list2)
print(list1)
Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802
Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER
Tuple
A tuple is a collection which is ordered and unchangeable. In Python tuples are written with round brackets.
Example
Create a Tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple)
Tuple
Change Tuple Values
Once a tuple is created, you cannot change its values. Tuples are unchangeable, or
immutable as it also is called.
But there is a workaround. You can convert the tuple into a list, change the list, and
convert the list back into a tuple.
print(x)
Set
A set is a collection which is unordered and unindexed. In Python sets are written with curly brackets.
Example
thisset = {"apple", "banana", "cherry"}
print(thisset)
print("banana" in thisset)
Change Items
Once a set is created, you cannot change its items, but you can add new items.
thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
print(thisset)
Set
Get the Length of a Set
thisset = {"apple", "banana", "cherry"}
print(len(thisset))
Remove Item
thisset = {"apple", "banana", "cherry"}
thisset.remove("banana")
print(thisset)
Set
Join Two Sets
There are several ways to join two or more sets in Python.
You can use the union() method that returns a new set containing all items from both sets,
or the update() method that inserts all the items from one set into another:
Example
The union() method returns a new set with all items from both sets:
set1 = {1, 2 , 3, 4}
set2 = {4, 2, 5}
set1.update(set2)
print(set1)
Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802
Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER
Set
Join Two Sets
The intersection() method returns a new set with common items in both sets:
set1 = {1, 2 , 3, 4}
set2 = {4, 2, 5}
set3 = set1.intersection(set2) OR set3 = set1 & set2
print(set3)
The difference() method returns a new set of items only in set1 but not in set2 :
set1 = {1, 2 , 3, 4}
set2 = {4, 2, 5}
set3 = set1.difference(set2) OR set3 = set1 - set2
print(set3)
The symmetric_difference() method returns a new set with except common items in both sets :
set1 = {1, 2 , 3, 4}
set2 = {4, 2, 5}
set3 = set1. symmetric_difference(set2) OR set3 = set1 ^ set2
print(set3)
Dictionary
A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are written
with curly brackets, and they have keys and values.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
x = thisdict["model"]
print(x)
x = thisdict.get("model")
print(x)
Change Values
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018
Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802
Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER
Dictionary
for x in thisdict:
print(x)
for x in thisdict:
print(thisdict[x])
for x in thisdict.values():
print(x)
for x, y in thisdict.items():
print(x, y)
Dictionary Length
print(len(thisdict))
Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802
Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER
Dictionary
Adding Items
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)
Removing Items
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)
Dictionary
Removing Items
The del keyword removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)
Dictionary
Copy a Dictionary
You cannot copy a dictionary simply by typing dict2 = dict1, because: dict2 will only be a reference to dict1,
and changes made in dict1 will automatically also be made in dict2.
There are ways to make a copy, one way is to use the built-in Dictionary method copy().
Example
Make a copy of a dictionary with the copy() method:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = thisdict.copy()
print(mydict)
#################################################
child1 = {
"name" : "Emil",
"year" : 2004
}
child2 = {
"name" : "Tobias",
"year" : 2007
}
child3 = {
"name" : "Linus",
"year" : 2011
}
myfamily = {
"child1" : child1,
"child2" : child2,
"child3" : child3
}
Dictionary
Nested Dictionaries
myfamily = {
"child1" : {
"name" : "Emil",
"year" : 2004
},
"child2" : {
"name" : "Tobias",
"year" : 2007
},
"child3" : {
"name" : "Linus",
"year" : 2011
}
}
#################################################
child1 = {
"name" : "Emil",
"year" : 2004
}
child2 = {
"name" : "Tobias",
"year" : 2007
}
child3 = {
"name" : "Linus",
"year" : 2011
}
myfamily = {
"child1" : child1,
"child2" : child2,
"child3" : child3
}
Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802
Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER
Python Functions
Example
def my_function():
print("Hello from a function")
my_function()
Python Functions
Arguments
Information can be passed into functions as arguments.
Arguments are specified after the function name, inside the parentheses. You can add as
many arguments as you want, just separate them with a comma.
Example
def my_function(fname):
print(fname + " Patil")
my_function(“Raj")
my_function(“Rahul")
my_function(“Rohit")
Note
The terms parameter and argument can be used for the same thing: information that are
passed into a function.
From a function's perspective:
A parameter is the variable listed inside the parentheses in the function definition.
An argument is the value that are sent to the function when it is called.
Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802
Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER
Python Functions
Arguments
function must be called with the correct number of arguments. Meaning that if your function
expects 2 arguments, you have to call the function with 2 arguments, not more, and not less.
Example
def my_function(fname, lname):
print(fname + " " + lname)
my_function(“Raj", “Patil")
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
Python Functions
Return Values
function return a value, use the return statement
Example
def my_function(x):
return 5 * x
Y=my_function(3)
Print(Y)
print(my_function(3))
print(my_function(5))
print(my_function(9))
Python Functions
Recursion
Python also accepts function recursion, which means a defined function can call itself
This has the benefit of meaning that you can loop through data to reach a result
Example
def tri_recursion(k):
if(k>0):
result = k+tri_recursion(k-1)
print(result)
else:
result = 0
return result
Python Functions
Arbitrary Arguments, *args
If you do not know how many arguments that will be passed into your function, add a *
before the parameter name in the function definition
This way the function will receive a tuple of arguments, and can access the items accordingly.
Example
def my_function(*kids):
print("The youngest child is " + kids[2])
my_function(child1 = " Raj ", child2 = " Rahul ", child3 = " Rohit ")
Python Functions
Arbitrary Keyword Arguments, **kwargs
If you do not know how many keyword arguments that will be passed into your function,
add two asterix: ** before the parameter name in the function definition.
This way the function will receive a dictionary of arguments, and can access the items
accordingly
Example
def my_function(**kid):
print("His last name is " + kid["lname"])
Python Functions
Arbitrary Keyword Arguments, **kwargs
If you do not know how many keyword arguments that will be passed into your function,
add two asterix: ** before the parameter name in the function definition.
This way the function will receive a dictionary of arguments, and can access the items
accordingly
Example
def my_function(**kid):
print("His last name is " + kid["lname"])
Python Functions
Return Multiple Values
Return keywords return multiple values at a time
Example
def mycal(a,b):
x = a+b
y = a*b
return x,y
add,mul=mycal(10,20)
Print(“Add-”,add)
Print(“Mul-”,mul)
result=mycal(10,20)
type(result) - >Tuple
Print(result)
o/p- (30,200)
Python Functions
Scope Of Variable
Local Variable
Global Variable
Example
a=10 # Global variable
def mycal():
b=20 #local variable
x = a+b
return x
add=mycal()
Print(“Add-”,add)
Python Functions
Scope Of Variable - Global Keywords
Changing and Updating value of global variable from a function definition we required
‘global’ keyword for it.
Example
Python Functions
Nested Function / Function Inside Function / Inner Function
•Function defined inside body of another function
•Nested Function Call Within the scop
Example
def myfunc():
x = 300
def myinnerfunc():
print(x)
myinnerfunc()
myfunc()
Python Modules
Consider a module to be the same as a code library.
A file containing a set of functions you want to include in your application.
Create a Module
To create a module just save the code you want in a file with the file extension .py
Example
#mymodule.py
def Namedisplay(name):
print("Hello, " + name)
Use a Module
Now we can use the module we just created, by using the import statement:
Example
import mymodule
mymodule. Namedisplay(“Raj")
Python Modules
Variables in Module
The module can contain functions, as already described, but also variables of all types
(arrays, dictionaries, objects etc):
Example
#mymodule.py
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
Example
Import the module named mymodule, and access the person1 dictionary:
import mymodule
a = mymodule.person1["age"]
print(a)
Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802
Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER
Python Modules
Re-naming a Module
You can name the module file whatever you like, but it must have the file extension .py
You can create an alias when you import a module, by using the as keyword:
Example
Create an alias for mymodule called mx
import mymodule as mx
a = mx.person1["age"]
print(a)
Example
def greeting(name):
print("Hello, " + name)
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
Example
#Import only the person1 dictionary from the module:
from mymodule import person1
print (person1["age"])
Python Modules
Built-in Modules
Get List Using Command
>>>help()
Help> ‘modules’
Python Modules
Decimal - In Python, there is a module called Decimal, which is used to do some decimal floating point
related tasks. This module provides correctly-rounded floating point arithmetic.
To use it at first we need to import it the Decimal standard library module.
import decimal
s= decimal.Decimal('25.36’)
Print(s)
my_dec = decimal.Decimal(25.36)
print(my_dec)
Output
25.36
25.3599999999999994315658113919198513031005859375
import decimal
my_dec = decimal.Decimal(25.36)
print(my_dec.ln())
print(my_dec.log10())
Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802
Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER
Python packages
Packages are namespaces which contain multiple packages and modules. They are simply directories,
Each package in Python is a directory which MUST contain a special file called __init__.py. This file can be
empty, and it indicates that the directory it contains is a Python package, so it can be imported the same
way a module can be imported.
If we create a directory called foo, which marks the package name, we can then create a module inside
that package called bar. We also must not forget to add the __init__.py file inside the foo directory.
import foo.bar
Or
from foo import bar
in the first method, we must use the foo prefix whenever we access the module bar. In the second
method, we don't, because we import the module to our module's namespace.
The __init__.py file can also decide which modules the package exports as the API, while keeping other
modules internal, by overriding the __all__ variable
__init__.py:
__all__ = ["bar"]
Python packages
import Game.Level.start
Game.Level.start.select_difficulty(2)
Python packages
from Game.Level import start
start.select_difficulty(2)
Python packages
Import numpy as np
list1=[1,2,3,4,5]
Arr=np.list(list1)
Print Arr
Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802
Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER
Class − A user-defined prototype for an object that defines a set of attributes that characterize
any object of the class. The attributes are data members and methods, accessed via dot
notation.
Class variable − A variable that is shared by all instances of a class. Class variables are defined
within a class but outside any of the class's methods.
Function overloading − The assignment of more than one behavior to a particular function. The
operation performed varies by the types of objects or arguments involved.
Instance variable − A variable that is defined inside a method and belongs only to the current
instance of a class.
Inheritance − The transfer of the characteristics of a class to other classes that are derived from
it.
Method − A special kind of function that is defined in a class definition.
Object − A unique instance of a data structure that's defined by its class. An object comprises
both data members and methods.
Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802
Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER
Create Object
Use class name to create objects:
Example –
p1 = MyClass()
print(p1.x)
p1.print_hello()
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
Example
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
p1.myfunc()
Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802
Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER
class Person:
def __init__(mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age
def myfunc(abc):
print("Hello my name is " + abc.name)
p1 = Person("John", 36)
p1.myfunc()
Delete Objects
Example
del p1
# Initializing
def __init__(self):
print('Employee created.')
obj = Employee()
del obj
# Initializing
def __init__(self):
print('Employee created')
# Calling destructor
def __del__(self):
print("Destructor called")
def Create_obj():
print('Making Object...')
obj = Employee()
print('function end...')
return obj
Inheritance allows us to define a class that inherits all the methods and properties from
another class.
Parent class is the class being inherited from, also called base class.
Child class is the class that inherits from another class, also called derived class.
It provides reusability of a code. We don’t have to write the same code again and again.
Also, it allows us to add more features to a class without modifying it.
It is transitive in nature, which means that if class B inherits from another class A, then all
the subclasses of B would automatically inherit from class A.
# Constructor
def __init__(self, name):
self.name = name
def getName(self):
return self.name
def isEmployee(self):
return False
class Employee(Person):
def isEmployee(self):
return True
Output-Geek1 False
Geek2 True
Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802
Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER
1. Single inheritance: When a child class inherits from only one parent class, it is called as
single inheritance.
2. Multiple inheritance: When a child class inherits from multiple parent classes, it is
called as multiple inheritance.
3. Multilevel inheritance: When we have child and grand child relationship.
4. Hierarchical inheritance More than one derived classes are created from a single base.
5. Hybrid inheritance: This form combines more than one form of inheritance. Basically, it
is a blend of more than one type of inheritance.
1. Single inheritance:
Class A:
…..
Class B(A):
…..
2. Multiple inheritance:
Class A:
…..
Class B:
…..
Class C(A,B):
…..
Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802
Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER
4. Hierarchical inheritance More than one derived classes are created from a single base.
Class A:
…..
Class B(A):
…..
Class C(A):
…..
class Calculation1:
def Summation(self,a,b):
return a+b;
class Calculation2:
def Multiplication(self,a,b):
return a*b;
class Derived(Calculation1,Calculation2):
def Divide(self,a,b):
return a/b;
d = Derived()
print(issubclass(Derived,Calculation2))
print(issubclass(Calculation1,Calculation2))
Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802
Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER
class Calculation1:
def Summation(self,a,b):
return a+b;
class Calculation2:
def Multiplication(self,a,b):
return a*b;
class Derived(Calculation1,Calculation2):
def Divide(self,a,b):
return a/b;
d = Derived()
print(isinstance(d,Derived))
class Animal:
def speak(self):
print("speaking")
class Dog(Animal):
def speak(self):
print("Barking")
d = Dog()
d.speak()
class Employee:
__count = 0;
def __init__(self):
Employee.__count = Employee.__count+1
def display(self):
print("The number of employees",Employee.__count)
emp = Employee()
print(emp.__count)
Output:
AttributeError: 'Employee' object has no attribute '__count'
Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802
Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER
Python also has a super() function that will make the child class inherit all the methods
and properties from its parent
Example
class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
Example
class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.graduationyear = year
Python Exception
•An exception can be defined as an unusual condition in a program resulting in the
interruption in the flow of the program.
•Whenever an exception occurs, the program stops the execution, and thus the further
code is not executed.
•Therefore, an exception is the run-time errors that are unable to handle to Python script.
An exception is a Python object that represents an error
•Python provides a way to handle the exception so that the code can be executed without
any interruption. If we do not handle the exception, the interpreter doesn't execute all the
code that exists after the exception.
Python Exception
Common Exceptions
•Python provides the number of built-in exceptions, but here we are describing the
common standard exceptions. A list of common exceptions that can be thrown from a
standard Python program is given below.
Python Exception
Example
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
print("a/b =“, c)
#other code:
print("Hi I am other part of the program")
Output:
Enter a:10
Enter b:0
Traceback (most recent call last):
File "exception-test.py", line 3, in <module>
c = a/b;
ZeroDivisionError: division by zero
Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802
Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER
Since the try block raises an error, the except block will be executed. Without the try block,
the program will crash and raise an error:
The finally block lets you execute code, regardless of the result of the try- and except
blocks.
Example
try:
print(x)
except:
print("An exception occurred")
try:
#block of code
except Exception_Class as Variable_Name:
#block of code
except:
#block of code
Example
try:
#block of code
else:
#block of code
Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802
Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER
Output:
Arithmetic Exception
You can use the else keyword to define a block of code to be executed if no errors were
raised:
Example
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
Output:
Enter a:10
Enter b:0
can't divide by zero
<class 'Exception'>
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
print("a/b = %d"%c)
# Using exception object with the except statement
except Exception as e:
print("can't divide by zero")
print(e)
else:
print("Hi I am else block")
Output:
Enter a:10
Enter b:0
can't divide by zero
division by zero
Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802
Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER
Example
try:
f = open("demofile.txt")
f.write("Lorum Ipsum")
except:
print("Something went wrong when writing to the file")
finally:
f.close()
Raise an exception
As a Python developer you can choose to throw an
exception if a condition occurs.
To throw (or raise) an exception, use the raise keyword.
Syntax
raise Exception_class,<value>
Example
x = -1
if x < 0:
raise Exception("Sorry, no numbers below zero")
x = "hello"
if not type(x) is int:
raise TypeError("Only integers are allowed")
Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802
Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER
Raise an exception
Example
try:
age = int(input("Enter the age:"))
if(age<18):
raise ValueError
else:
print("the age is valid")
except ValueError:
print("The age is not valid")
Output:
Enter the age:17
The age is not valid
Raise an exception
Example
try:
num = int(input("Enter a positive integer: "))
if(num <= 0):
# we can pass the message in the raise statement
raise ValueError("That is a negative number!")
except ValueError as e:
print(e)
Output:
Enter a positive integer: -5
That is a negative number!
try:
raise ErrorInCode(2000)
except ErrorInCode as ae:
print("Received error:", ae.data)
Output:
Received error: 2000
Thread
Running several threads is similar to running several
different programs concurrently
Multiple threads within a process share the same data space with the main thread and can
therefore share information or communicate with each other more easily than if they were
separate processes
Threads sometimes called light-weight processes and they do not require much memory
overhead; they are cheaper than processes.
Thread
Starting a New Thread
This method call enables a fast and efficient way to create new threads in both Linux and
Windows.
The method call returns immediately and the child thread starts and calls function with the
passed list of args.
Here, args is a tuple of arguments; use an empty tuple to call function without passing any
arguments. kwargs is an optional dictionary of keyword arguments.
Thread
Example
import thread
import time
# Define a function for the thread
def print_time( threadName, delay):
count = 0
while count < 5:
time.sleep(delay)
count += 1
print "%s: %s" % ( threadName, time.ctime(time.time()) )
while 1:
pass
Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802
Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER
Thread
The Threading Module Methods
Thread
Creating Thread Using Threading Module
Once you have created the new Thread subclass, you can create an instance of it and then
start a new thread by invoking the start(), which in turn calls run() method.
Thread
Creating Thread Using Threading Module
import threading
import time
exitFlag = 0
class myThread (threading.Thread):
def __init__(self, threadID, name, mdelay):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self. mdelay = mdelay
def run(self):
print "Starting " + self.name
print_time(self.name, 5, self. mdelay)
print "Exiting " + self.name
def print_time(threadName, counter, delay):
while counter:
if exitFlag:
threadName.exit()
time.sleep(delay)
print "%s: %s" % (threadName, time.ctime(time.time()))
counter -= 1
Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802
Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER
Thread
Creating Thread Using Threading Module
Thread
Synchronizing Threads
The acquire(blocking) method of the new lock object is used to force threads to
run synchronously. The optional blocking parameter enables you to control
whether the thread waits to acquire the lock.
If blocking is set to 0, the thread returns immediately with a 0 value if the lock
cannot be acquired and with a 1 if the lock was acquired. If blocking is set to 1,
the thread blocks and wait for the lock to be released.
The release() method of the new lock object is used to release the lock when it is
no longer required.
Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802
Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER
Thread
Synchronizing Threads
import threading
import time
class myThread (threading.Thread):
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self):
print "Starting " + self.name
# Get lock to synchronize Threads
threadLock.acquire()
print_time(self.name, self.counter, 3)
# Free lock to release next thread
threadLock.release()
Thread
Synchronizing Threads
threadLock = threading.Lock()
threads = []
f = open("demofile.txt", "r")
print(f.read())
f = open("D:\\myfiles\welcome.txt", "r")
print(f.read())
f = open("demofile.txt", "r")
print(f.readline())
print(f.readline())
f.close()
Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802
Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
# f.writelines(“abc”)
f.close()
rename(current-name, new-name)
import os
#rename file2.txt to file3.txt
os.rename("file2.txt","file3.txt")
import os
os.remove("demofile.txt")
import os
if os.path.exists("demofile.txt"):
os.remove("demofile.txt")
else:
print("The file does not exist")
os.mkdir("new")
os.getcwd()
Deleting directory
os.rmdir(directory name)
import os
#removing the new directory
os.rmdir("directory_name")
Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802
Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER
Python Database
Create Connection
1- Import Package
import mysql.connector
2- connection
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword"
)
print(mydb)
Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802
Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER
Python Database
Creating a Database
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword"
)
mycursor = mydb.cursor()
Python Database
List Of Database
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword"
)
mycursor = mydb.cursor()
mycursor.execute("SHOW DATABASES")
for x in mycursor:
print(x)
Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802
Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER
Python Database
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mydb.commit()
Python MYSQL
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user=“root",
password="",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = "INSERT INTO customers (name, address) VALUES (‘John’, ‘Highway 21’)“
mycursor.execute(sql)
mydb.commit()
Python MYSQL
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword“
database="test"
)
print(mydb)
mycursor = mydb.cursor()
sql = "INSERT INTO customers (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')
]
mycursor.executemany(sql, val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")
Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802
Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER
Python MYSQL
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword“
database="test"
)
print(mydb)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchall()
for x in myresult:
#print(x)
print(x[0],x[1])