0% found this document useful (0 votes)
10 views134 pages

Class Python

The document provides an overview of Python, a versatile programming language created in 1991, detailing its applications in web development, software development, and data handling. It covers fundamental concepts such as syntax, variables, data types, control structures, and string manipulation, along with examples for clarity. Additionally, it emphasizes Python's simplicity and efficiency, making it suitable for both beginners and experienced developers.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views134 pages

Class Python

The document provides an overview of Python, a versatile programming language created in 1991, detailing its applications in web development, software development, and data handling. It covers fundamental concepts such as syntax, variables, data types, control structures, and string manipulation, along with examples for clarity. Additionally, it emphasizes Python's simplicity and efficiency, making it suitable for both beginners and experienced developers.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 134

Software Developer And Training Center

SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

PYTHON

Rohan S. Suryawanshi Mob No.:-7276702802


Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

PYTHON
Python is a popular programming language. It was created by Guido van
Rossum, and released in 1991.

It is used for:


• web development (server-side),
• software development,
• mathematics,
• system scripting.

What can Python do


• Used on a server to create web applications.
• Used alongside software to create workflows.
• Connect to database systems. It can also read and modify files.
• Used to handle big data and perform complex mathematics.
• Used for rapid prototyping, or for production-ready software
development. Rohan S. Suryawanshi Mob No.:-7276702802
Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

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/

Rohan S. Suryawanshi Mob No.:-7276702802


Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

PYTHON
Python Commands
• Check version
python --version
• Execute Programs
python helloworld.py
• Simple Example helloworld.py

print("Hello, World!")

Rohan S. Suryawanshi Mob No.:-7276702802


Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

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

>>> print("Hello, World!")

Hello, World!

Rohan S. Suryawanshi Mob No.:-7276702802


Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

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!")

•(Note – Syntax Error)


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!")

Comments can be used to explain Python code.


#This is a comment
print("Hello, World!")

Rohan S. Suryawanshi Mob No.:-7276702802


Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

Python Variables
•In Python, variables are created when you assign a value to it:

x=5
y = "Hello, World!“

•Variables are containers for storing data values.


•Unlike other programming languages, Python has no command for declaring a variable.
•A variable is created the moment you first assign a value to it.
•Variables do not need to be declared with any particular type and can even change type after they have been
set.
•String variables can be declared either by using single or double quotes:
•A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume). Rules for Python
variables:
• A variable name must start with a letter or the underscore character
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
• Variable names are case-sensitive (age, Age and AGE are three different variables)

•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

Python Data Types


•Built-in Data Types
oVariables can store data of different types, and different types can
do different things.
oPython has the following data types built-in by default, in these
categories:
Text Type:str
Numeric Types:int, float, complex
Sequence Types:list, tuple, range
Mapping Type:dict
Set Types:set, frozenset
Boolean Type:bool
Binary Types:bytes, bytearray, memoryview

Rohan S. Suryawanshi Mob No.:-7276702802


Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

Python Data Types


•Example
x=5
print(type(x)) #Geting Type Of Value Stored

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 If ... Else


•Python supports the usual logical conditions from mathematics:
Equals: a == b
Not Equals: a != b
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
•These conditions can be used in several ways, most commonly in "if statements"
and loops.
•An "if statement" is written by using the if keyword.

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

The pass Statement


if statements cannot be empty, but if you for some reason have an if statement
with no content, put in the pass statement to avoid getting an error.
Example
a = 33
b = 200

if b > a:
pass

Rohan S. Suryawanshi Mob No.:-7276702802


Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

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

The break Statement


With the break statement we can stop the loop even if the while condition is true

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

The continue Statement


With the continue statement we can stop the current iteration, and continue with the next
Example
i=0
while i < 6:
i += 1
if i == 3:
continue
print(i)

The else Statement


i=1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")

Rohan S. Suryawanshi Mob No.:-7276702802


Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

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)

Looping Through a String


for x in "banana":
print(x)

The break Statement


With the break statement we can stop the loop before it has looped through all the items
Example
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break
Rohan S. Suryawanshi Mob No.:-7276702802
Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

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)

Else in For Loop


The else keyword in a for loop specifies a block of code to be executed when the loop is
finished
Example
for x in range(6):
print(x)
else:
print("Finally finished!")
Rohan S. Suryawanshi Mob No.:-7276702802
Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

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)

The pass Statement


for loops cannot be empty, but if you for some reason have a for loop with no
content, put in the pass statement to avoid getting an error.
Example
for x in [0, 1, 2]:
pass
Rohan S. Suryawanshi Mob No.:-7276702802
Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

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)

Strings are Arrays


a = "Hello, World!"
print(a[1])
print(a[-2])

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 lower() method returns the string in lower case:


a = "Hello, World!"
print(a.lower())

The upper() method returns the string in upper case:


a = "Hello, World!"
print(a.upper())

The replace() method replaces a string with another string:


a = "Hello, World!"
print(a.replace("H", "J"))

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

Check if the phrase "ain" is present in the following text:


txt = "The rain in Spain stays mainly in the plain"
x = "ain" in txt
print(x)
txt = "The rain in Spain stays mainly in the plain"
x = "ain" not in txt
print(x)

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

Operators are used to perform operations on variables and values.


Python divides the operators in the following groups:

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
= , += , -= , *= ,/= , %= , //= , **= ,&= , |= ,^=,>>=,<<=

Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802


Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

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

Python Collections (Arrays)

List is a collection which is ordered and changeable. Allows duplicate members.


Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
Set is a collection which is unordered and unindexed. No duplicate members.
Dictionary is a collection which is unordered, changeable and indexed. No duplicate
members.

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)

Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802


Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

List
Example

Access Items
You access the list items by referring to the index number:

Print the second item of the list:


thislist = ["apple", "banana", "cherry"]
print(thislist[1])

thislist = ["apple", "banana", "cherry"]


print(thislist[-1])

Range of Indexes

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]


print(thislist[2:5])

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]


print(thislist[:4])

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]


print(thislist[2:])

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]


print(thislist[-4:-1])
Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802
Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

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)

thislist = ["apple", "banana", "cherry"]


for x in thislist:
print(x)

thislist = ["apple", "banana", "cherry"]


if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")

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)

thislist = ["apple", "banana", "cherry"]


thislist.remove("banana")
print(thislist)

thislist = ["apple", "banana", "cherry"]


thislist.pop()
print(thislist)

thislist = ["apple", "banana", "cherry"]


del thislist[0]
print(thislist)

thislist = ["apple", "banana", "cherry"]


del thislist
print(thislist) #Error

thislist = ["apple", "banana", "cherry"]


thislist.clear()
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
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().

thislist = ["apple", "banana", "cherry"]


mylist = thislist.copy()
print(mylist)

thislist = ["apple", "banana", "cherry"]


mylist = list(thislist)
print(mylist)

Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802


Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

List
Join Two Lists

list1 = ["a", "b" , "c"]


list2 = [1, 2, 3]

list3 = list1 + list2


print(list3)
##############################################
#Append list2 into list1:
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]

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)

thistuple = ("apple", "banana", "cherry")


for x in thistuple:
print(x)

thistuple = ("apple", "banana", "cherry")


print(thistuple[1])

thistuple = ("apple", "banana", "cherry")


print(thistuple[-1])

thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")


print(thistuple[2:5])

thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")


print(thistuple[-4:-1])
Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802
Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

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.

x = ("apple", "banana", "cherry")


y = list(x)
y[1] = "kiwi"
x = tuple(y)

print(x)

Check if Item Exists


thistuple = ("apple", "banana", "cherry")
if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")
Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802
Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

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)

thisset = {"apple", "banana", "cherry"}


for x in thisset:
print(x)

Check if "banana" is present in the set:


thisset = {"apple", "banana", "cherry"}

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)

Add multiple items to a set, using the update() method:


thisset = {"apple", "banana", "cherry"}
thisset.update(["orange", "mango", "grapes"])
print(thisset)
Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802
Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

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)

thisset = {"apple", "banana", "cherry"}


thisset.discard("banana")
print(thisset)

#The clear() method empties the set:


thisset = {"apple", "banana", "cherry"}
thisset.clear()
print(thisset)

#The del keyword will delete the set completely:


thisset = {"apple", "banana", "cherry"}
del thisset
print(thisset)
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
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}

set3 = set1.union(set2) OR set3 = set1 | set2


print(set3)

The update() method inserts the items in set2 into set1:


set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}

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)

Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802


Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

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)

Check if Key Exists


thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")

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)

The popitem() method removes the last inserted item


thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.popitem()
print(thisdict)

Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802


Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

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)

The del keyword can also delete the dictionary completely:


thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict
print(thisdict) #this will cause an error because "thisdict" no longer exists.

The clear() keyword empties the dictionary:


thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.clear()
print(thisdict)
Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802
Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

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)

Make a copy of a dictionary with the dict() method:


thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = dict(thisdict)
print(mydict)
Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802
Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

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

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

•A function is a block of code which only runs when it is called.


•You can pass data, known as parameters, into a function.
•A function can return data as a result.
In Python a function is defined using the def keyword.

Example
def my_function():
print("Hello from a function")

To call a function, use the function name followed by parenthesis


Example
def my_function():
print("Hello from a function")

my_function()

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
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")

Default Parameter Value


If we call the function without argument, it uses the default value
Example
def my_function(country = "Norway"):
print("I am from " + country)

my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")

Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802


Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

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))

The pass Statement


function definitions cannot be empty, but if you for some reason have a function definition
with no content, put in the pass statement to avoid getting an error.
Example
def myfunction():
pass

Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802


Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

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

print("\n\nRecursion Example Results")


tri_recursion(6)

Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802


Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

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(" Raj ", “Rahul", “Rohit")

Keyword Arguments or Kwargs


You can also send arguments with the key = value syntax.
This way the order of the arguments does not matter
Example
def my_function(child3, child2, child1):
print("The youngest child is " + child3)

my_function(child1 = " Raj ", child2 = " Rahul ", child3 = " Rohit ")

Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802


Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

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"])

my_function(fname = “Raj", lname = “Patil")

Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802


Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

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"])

my_function(fname = “Raj", lname = “Patil")

Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802


Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

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)

Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802


Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

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)

Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802


Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

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

a=10 # Global variable a=10 # Global variable

def mycall(): def mycall():


a=20 global a # reference to global ‘a’
a=20

Print(“ a value -”,a) Print(“ a value -”,a)


mycall() mycall()
Print(“ a value -”,a) Print(“ a value -”,a)

Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802


Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

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()

Pass by value or Pass by reference(Call by value or Call by reference)


by default call by reference concept is applied.

Variable length argument


Check variable length argument of function
Def myfunc(* args)
print(args._len_());
Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802
Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

Python Functions – In Built functions


Data type and object
type() - Returns the type of an object
abs() - Returns the absolute value of a number
all() - Returns True if all items in an iterable object are true
any() - Returns True if any item in an iterable object is true
id() - Returns the id of an object
callable() - Returns True if the specified object is callable, otherwise False
isinstance() - Returns True if a specified object is an instance of a specified object
hasattr() - Returns True if the specified object has the specified attribute (property/method)

Input Output functions


input() - Allowing user input
print() - Prints to the standard output device

Files and Expression functions


open() - Opens a file and returns a file object
complex() - Returns a complex number
eval() - Evaluates and executes an expression

Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802


Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

Python Functions – In Built functions


Data Conversions Functions
bin() - Returns the binary version of a number
bool() - Returns the boolean value of the specified object
chr() - Returns a character from the specified Unicode code.
float() - Returns a floating point number
hex() - Converts a number into a hexadecimal value
int() - Returns an integer number
list() - Returns a list
oct() - Converts a number into an octal
str() - Returns a string object
ord() - Convert an integer representing the Unicode of the specified character
tuple() - Returns a tuple

Class and Inheritance function


@staticmethod() - Converts a method into a static method
super() - Returns an object that represents the parent class
issubclass() - Returns True if a specified class is a subclass of a specified object

Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802


Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

Python Functions – In Built functions


Mathematical Functions
max() - Returns the largest item in an iterable
min() - Returns the smallest item in an iterable
next() - Returns the next item in an iterable
pow() - Returns the value of x to the power of y
range() - Returns a sequence of numbers, starting from 0 and increments by 1 (by default)
sum() - Sums the items of an iterator

For built in help


help() - Executes the built-in help system

Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802


Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

Python Functions – In Built functions


Other Functions
round() - Rounds a numbers
sorted() - Returns a sorted list
bytearray() - Returns an array of bytes
bytes() - Returns a bytes object
delattr() - Deletes the specified attribute (property or method) from the specified object
dict() - Returns a dictionary (Array)
exec() - Executes the specified code (or object)
hash() - Returns the hash value of a specified object
len() - Returns the length of an object
map() - Returns the specified iterator with the specified function applied to each item

Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802


Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

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")

Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802


Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

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)

Import From Module


You can choose to import only parts from a module, by using the from keyword.

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"])

Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802


Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

Python Modules

Built-in Modules
Get List Using Command
>>>help()
Help> ‘modules’

Some Numeric and mathematical Modules are


• Decimal
• Fractions
• Itertools
• Match
• Operator
• Random.

Functional Programming modules


• lambda expression
• map function
• filter function
• reduce function
Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802
Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

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

There are some logarithmic functions in the Decimal module


ln() method - This method is used to find the natural logarithm of the decimal number.
log10() method - This method is used to find the logarithmic value where base is 10.

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"]

Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802


Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

Python packages
import Game.Level.start
Game.Level.start.select_difficulty(2)

Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802


Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

Python packages
from Game.Level import start
start.select_difficulty(2)

from Game.Level.start import select_difficulty


select_difficulty(2)

Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802


Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

Python packages

New packages installation


For Linux Platform-
>python
>>>pip install numpy
>>>pip install scipy
>>>pip install matplotlib

For windows Platform-


python -m pip install numpy or pip install numpy
python -m pip install --upgrade numpy or pip install --upgrade numpy

After install new package – use it

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

Python Object Oriented Programming


Python Classes/Objects
Class is as User Define data type
Python is an object oriented programming language.
Almost everything in Python is an object, with its properties and methods

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

Python Object Oriented Programming


Creating Classes
To create a class, use the keyword class:
Example –
class MyClass:
x=5
def print_hello()
print(‘Hello.!’)

Create Object
Use class name to create objects:
Example –
p1 = MyClass()
print(p1.x)
p1.print_hello()

The __init__() Function OR (Constructor and Parameterized Constructor )


All classes have a function called __init__(), which is always executed when the class is being initiated.
Use the __init__() function to assign values to object properties, or other operations that are necessary
to do when the object is being created

Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802


Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

Python Object Oriented Programming


The __init__() Function OR (Constructor and Parameterized Constructor )
Example
class Person:
name=“”
age =0
def __init__(self, name, age):
self.name = name
self.age = age

p1 = Person("John", 36)

print(p1.name)
print(p1.age)

Constructor With Default Parameter


class Person:
def __init__(self, name=“Raj”, age=26):
self.name = name
self.age = age

NOTE- Constructor Overloading Is Not Allowed In Python


Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802
Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

Python Object Oriented Programming


The self Parameter
The self parameter is a reference to the current instance of the class, and is used to access
variables that belongs to the class.
It does not have to be named self , you can call it whatever you like, but it has to be the
first parameter of any function in the class:

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

Python Object Oriented Programming


The self Parameter
Use the words mysillyobject and abc instead of self:

class Person:
def __init__(mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age

def myfunc(abc):
print("Hello my name is " + abc.name)

p1 = Person("John", 36)
p1.myfunc()

Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802


Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

Python Object Oriented Programming


Delete Object Properties
Example
del p1.age

Delete Objects
Example
del p1

The pass Statement


class definitions cannot be empty, but if you for some reason have a class definition with
no content, put in the pass statement to avoid getting an error.
Example
class Person:
pass

Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802


Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

Python Object Oriented Programming


Destructor OR the _ _ del _ _() method
The __del__() method is a known as a destructor method in Python. It is called when all references to the
object have been deleted
Example
# Python program to illustrate destructor
class Employee:

# Initializing
def __init__(self):
print('Employee created.')

# Deleting (Calling destructor)


def __del__(self):
print('Destructor called, Employee deleted.')

obj = Employee()
del obj

Output: Employee created.


Destructor called, Employee deleted.
Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802
Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

Python Object Oriented Programming


Destructor OR the _ _ del _ _() method
Example
class Employee:

# 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

print('Calling Create_obj() function...')


obj = Create_obj()
print('Program End...')

Output: Calling Create_obj() function...


Making Object...
Employee created
function end...
Program End...
Destructor called
Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802
Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

Python Object Oriented Programming


Python Inheritance

Inheritance allows us to define a class that inherits all the methods and properties from
another class.
Parent class is the class being inherited from, also called base class.
Child class is the class that inherits from another class, also called derived class.

It represents real-world relationships well.

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.

Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802


Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

Python Object Oriented Programming


Python Inheritance
Syntax
class BaseClass(object):
….
….
class DerivedClass(BaseClass):
….
….

Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802


Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

Python Object Oriented Programming


Python Inheritance
Example
class Person(object):

# 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

emp = Person("Geek1") # An Object of Person


print(emp.getName(), emp.isEmployee())

emp = Employee("Geek2") # An Object of Employee


print(emp.getName(), emp.isEmployee())

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

Python Object Oriented Programming


Python Inheritance
Types Of Inheritance

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.

Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802


Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

Python Object Oriented Programming


Python 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

Python Object Oriented Programming


Python Inheritance
3. Multilevel inheritance
Class A:
…..
Class B(A):
…..
Class C(B):
…..

4. Hierarchical inheritance More than one derived classes are created from a single base.
Class A:
…..
Class B(A):
…..
Class C(A):
…..

Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802


Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

Python Object Oriented Programming


The issubclass(sub,sup) method
The issubclass(sub, sup) method is used to check the relationships between the specified classes.
It returns true if the first class is the subclass of the second class, and false otherwise

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

Python Object Oriented Programming


The isinstance (obj, class) method
The isinstance() method is used to check the relationship between the objects and classes.
It returns true if the first parameter, i.e., obj is the instance of the second parameter, i.e.,
class

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))

Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802


Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

Python Object Oriented Programming


Method Overriding
implementation of the parent class method in our child class. When the parent class
method is defined in the child class with some specific implementation, then the concept
is called method overriding.
We may need to perform method overriding in the scenario where the different definition
of a parent class method is needed in the child class.

class Animal:
def speak(self):
print("speaking")
class Dog(Animal):
def speak(self):
print("Barking")
d = Dog()
d.speak()

Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802


Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

Python Object Oriented Programming


Data abstraction in python
An object's attributes may or may not be visible outside the class definition.
In python, we can also perform data hiding by adding the double underscore (___) as a prefix to
the attribute which is to be hidden.
After this, the attribute will not be visible outside of the class through the object.

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 Object Oriented Programming


Use the super() Function (Constructor and Destructor inheritance)

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

x = Student("Mike", "Olsen", 2019)

Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802


Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

Python Object Oriented Programming


Overloading Methods

This doesn't work

Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802


Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

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.

Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802


Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

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.

•ZeroDivisionError: Occurs when a number is divided by zero.


•NameError: It occurs when a name is not found. It may be local or global.
•IndentationError: If incorrect indentation is given.
•IOError: It occurs when Input Output operation fails.
•EOFError: It occurs when the end of the file is reached, and yet operations are being
performed.

Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802


Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

Exception Name & Description


1 Exception
Base class for all exceptions
2 StopIteration
Raised when the next() method of an iterator does not point to any object.
3 SystemExit
Raised by the sys.exit() function.
4 StandardError
Base class for all built-in exceptions except StopIteration and SystemExit.
5 ArithmeticError
Base class for all errors that occur for numeric calculation.
6 OverflowError
Raised when a calculation exceeds maximum limit for a numeric type.
7 FloatingPointError
Raised when a floating point calculation fails.
8 ZeroDivisionError
Raised when division or modulo by zero takes place for all numeric types.

Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802


Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

Exception Name & Description


9 AssertionError
Raised in case of failure of the Assert statement.
10 AttributeError
Raised in case of failure of attribute reference or assignment.
11 EOFError
Raised when there is no input from either the raw_input() or input() function and the end
of file is reached.
12 ImportError
Raised when an import statement fails.
13 KeyboardInterrupt
Raised when the user interrupts program execution, usually by pressing Ctrl+c.
14 LookupError
Base class for all lookup errors.
15 IndexError
Raised when an index is not found in a sequence.
16 KeyError
Raised when the specified key is not found in the dictionary.

Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802


Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

Exception Name & Description


17 NameError
Raised when an identifier is not found in the local or global namespace.
18 UnboundLocalError
Raised when trying to access a local variable in a function or method but no value has
been assigned to it.
19 EnvironmentError
Base class for all exceptions that occur outside the Python environment.
20 IOError
Raised when an input/ output operation fails, such as the print statement or the open()
function when trying to open a file that does not exist.
21 IOError
Raised for operating system-related errors.
22 SyntaxError
Raised when there is an error in Python syntax.
23 IndentationError
Raised when indentation is not specified properly.

Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802


Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

Exception Name & Description


24 SystemError
Raised when the interpreter finds an internal problem, but when this error is encountered
the Python interpreter does not exit.
25 SystemExit
Raised when Python interpreter is quit by using the sys.exit() function. If not handled in
the code, causes the interpreter to exit.
26 TypeError
Raised when an operation or function is attempted that is invalid for the specified data
type.
27 ValueError
Raised when the built-in function for a data type has the valid type of arguments, but the
arguments have invalid values specified.
28 RuntimeError
Raised when a generated error does not fall into any category.
29 NotImplementedError
Raised when an abstract method that needs to be implemented in an inherited class is not
actually implemented.

Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802


Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

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

Python Try Except


When an error occurs, or exception as we call it, Python will normally stop and generate an
error message.

These exceptions can be handled using the try statement


The try block lets you test a block of code for errors.

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.

Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802


Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

Python Try Except


Syntax:
try:
#Line Of Code
except Exception_Class as Variable_Name:
#Line Of Code
else:
#Line Of Code

Example
try:
print(x)
except:
print("An exception occurred")

Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802


Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

Python Try Except


Many Exceptions
You can define as many exception blocks as you want, e.g. if you want to execute a special block of code for a
special kind of error:
Example

try:
#block of code
except Exception_Class as Variable_Name:
#block of code
except:
#block of code

Example
try:
#block of code

except (<Exception 1>,<Exception 2>,<Exception 3>,...<Exception n>)


#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

Python Try Except


Many Exceptions
try:
a=10/0;
except(ArithmeticError, IOError):
print("Arithmetic Exception")
else:
print("Successfully Done")

Output:
Arithmetic Exception

Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802


Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

Python Try Except Else

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")

Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802


Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

Python Try Except Else


Example
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
print("a/b = %d"%c)
# Using Exception with except statement. If we print(Exception) it will return exception class
except Exception:
print("can't divide by zero")
print(Exception)
else:
print("Hi I am else block")

Output:
Enter a:10
Enter b:0
can't divide by zero
<class 'Exception'>

Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802


Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

Python Try Except Else


Example
The except statement using with exception variable

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

Python Try Except Finally

The finally block, if specified, will be executed regardless if


the try block raises an error or not.
Example
try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")

Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802


Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

Python Try Except Finally

Example
try:
f = open("demofile.txt")
f.write("Lorum Ipsum")
except:
print("Something went wrong when writing to the file")
finally:
f.close()

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

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:
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!

Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802


Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

Custom Exception or User Exception


The Python allows us to create our exceptions that can be
raised from the program and caught using the except clause.
Example
class ErrorInCode(Exception):
def __init__(self, data):
self.data = data
def __str__(self):
return repr(self.data)

try:
raise ErrorInCode(2000)
except ErrorInCode as ae:
print("Received error:", ae.data)

Output:
Received error: 2000

Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802


Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

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.

It can be pre-empted (interrupted)


It can temporarily be put on hold (also known as sleeping) while other threads are running
- this is called yielding.

Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802


Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

Thread
Starting a New Thread

thread.start_new_thread ( function, args[, kwargs] )

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.

When function returns, the thread terminates.

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.

Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802


Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

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()) )

# Create two threads as follows


try:
thread.start_new_thread( print_time, ("Thread-1", 2, ) )
thread.start_new_thread( print_time, ("Thread-2", 4, ) )
except:
print "Error: unable to start thread"

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

threading.activeCount() − Returns the number of thread objects that are active.


threading.currentThread() − Returns the number of thread objects in the caller's thread
control.
threading.enumerate() − Returns a list of all thread objects that are currently active.
run() − The run() method is the entry point for a thread.
start() − The start() method starts a thread by calling the run method.
join([time]) − The join() waits for threads to terminate.
isAlive() − The isAlive() method checks whether a thread is still executing.
getName() − The getName() method returns the name of a thread.
setName() − The setName() method sets the name of a thread.

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

Define a new subclass of the Thread class.


Override the __init__(self [,args]) method to add additional arguments.
Then, override the run(self [,args]) method to implement what the thread should do when
started.

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.

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

# Create new threads


thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)

# Start new Threads


thread1.start()
thread2.start()

print "Exiting Main Thread"

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

The threading module provided with Python includes a simple-to-implement


locking mechanism that allows you to synchronize threads. A new lock is created
by calling the Lock() method, which returns the new lock.

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()

def print_time(threadName, delay, counter):


while counter:
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
Synchronizing Threads
threadLock = threading.Lock()
threads = []

# Create new threads


thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)

# Start new Threads


thread1.start()
thread2.start()

# Add threads to thread list


threads.append(thread1)
threads.append(thread2)

# Wait for all threads to complete


for t in threads:
t.join()

print "Exiting Main Thread"


Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802
Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

Python File Open


Python has several functions for creating, reading, updating, and deleting files.
The key function for working with files in Python is the open() function.
The open() function takes two parameters; filename, and mode.
There are four different methods (modes) for opening a file:
"r" - Read - Default value. Opens a file for reading, error if the file does not exist
"a" - Append - Opens a file for appending, creates the file if it does not exist
"w" - Write - Opens a file for writing, creates the file if it does not exist
"x" - Create - Creates the specified file, returns an error if the file exists
In addition you can specify if the file should be handled as binary or text mode
"t" - Text - Default value. Text mode
"b" - Binary - Binary mode (e.g. images)
Example
f = open("demofile.txt") #reading
f = open("demofile.txt", "rt")

Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802


Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

Python File Open


Python has several functions for creating, reading, updating, and deleting files.
The key function for working with files in Python is the open() function.
The open() function takes two parameters; filename, and mode.
There are four different methods (modes) for opening a file:
"r" - Read - Default value. Opens a file for reading, error if the file does not exist
"a" - Append - Opens a file for appending, creates the file if it does not exist
"w" - Write - Opens a file for writing, creates the file if it does not exist
"x" - Create - Creates the specified file, returns an error if the file exists
In addition you can specify if the file should be handled as binary or text mode
"t" - Text - Default value. Text mode
"b" - Binary - Binary mode (e.g. images)
Example
f = open("demofile.txt") #reading
f = open("demofile.txt", "rt")

Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802


Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

Python File Open


To open the file, use the built-in open() function.

f = open("demofile.txt", "r")
print(f.read())

f = open("D:\\myfiles\welcome.txt", "r")
print(f.read())

# Return the 5 first characters of the file:


f = open("demofile.txt", "r")
print(f.read(5))

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

Write to an Existing File


To write to an existing file, you must add a parameter to the open()
function:
"a" - Append - will append to the end of the file
"w" - Write - will overwrite any existing content

f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
# f.writelines(“abc”)
f.close()

#open and read the file after the appending:


f = open("demofile2.txt", "r")
print(f.read())

Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802


Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

Python Renaming the file

It provides us the rename() method to rename the specified file to a


new name

rename(current-name, new-name)

import os
#rename file2.txt to file3.txt
os.rename("file2.txt","file3.txt")

Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802


Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

Python Delete File


To delete a file, you must import the OS module, and run its
os.remove() function.

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")

Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802


Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

Python Delete File

Creating the new directory


mkdir(directory name)

os.mkdir("new")

The getcwd() method


This method returns the current working directory.

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

Download and install "MySQL Connector":

python -m pip install mysql-connector-python

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()

mycursor.execute("CREATE DATABASE mydatabase")

Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802


Software Developer And Training Center
SOFTRON SOFTWARE DESIGN, WEBDESIGN, PROFESSIONAL TRAINING CENTER

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

Insert Into Table

import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)

mycursor = mydb.cursor()

sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"


val = ("John", "Highway 21")
mycursor.execute(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=“root",
password="",
database="mydatabase"
)

mycursor = mydb.cursor()

sql = "INSERT INTO customers (name, address) VALUES (‘John’, ‘Highway 21’)“
mycursor.execute(sql)

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()
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])

Website: www.Softron.in Rohan S. Suryawanshi Mob No.:-7276702802

You might also like