Professional Documents
Culture Documents
www.careerin.co.in
INTRODUCTION( CONTD….)
Python version 1.0 was released in January 1994. The
major new features included in this release were the
functional programming tools lambda, map, filter and
reduce.
In October 2000, Python 2.0 was introduced. This
release included list comprehensions, a full garbage
collector and it was supporting unicode.
Python flourished for another 8 years in the versions 2.x
before the next major release as Python 3.0
www.careerin.co.in
INTRODUCTION
Python was conceptualized in the late 1980s.
www.careerin.co.in
PYTHON
VARIABLES
www.careerin.co.in
PYTHON - VARIABLES
what's a variable? As the name implies, a variable is
something which can change.
A variable is a way of referring to a memory location
used by a computer program.
www.careerin.co.in
Eg: int x;
int y;
www.careerin.co.in
PYTHON - VARIABLES
If a variable is of type integer, solely integers can be
saved in the variable for the duration of the program. In
those programming languages every variable has to be
declared before it can be used. Declaring a variable
means binding it to a data type.
It's a lot easier in Python. There is no declaration of
variables required in Python. It's not even possible. If
there is need of a variable, you think of a name and start
using it as a variable.
www.careerin.co.in
The value of a variable may change during program
execution but the type as well. You can assign an integer
value to a variable, use it as an integer for a while and
then assign a string to the same variable.
x=5
x = "John"
print(x)
Output: john
www.careerin.co.in
VARIABLE NAMES
www.careerin.co.in
ASSIGN VALUE TO MULTIPLE VARIABLES
Output: orange
banana
cherry
www.careerin.co.in
OUTPUT VARIABLES
www.careerin.co.in
You can also use the + character to add a variable to
another variable:
Example
x = "Python is "
y = "awesome"
z = x + y
print(z)
www.careerin.co.in
For numbers, the + character works as a mathematical
operator:
Example
x=5
y = 10
print(x + y)
Output: 15
www.careerin.co.in
f you try to combine a string and a number, Python will
give you an error:
Example
x=5
y = "John"
print(x + y)
Output:
TypeError: unsupported operand type(s) for +: 'int' and
'str'
www.careerin.co.in
Python Data Types
www.careerin.co.in
PYTHON DATA TYPES
www.careerin.co.in
Getting the Data Type
You can get the data type of any object by using the
type() function:
Example
x=5
print(type(x))
www.careerin.co.in
PYTHON NUMBERS
float
Complex
Example
x = 1 # int
y = 2.8 # float
z = 1j # complex
www.careerin.co.in
INT
Integers:
x=1
y = 35656222554887711
z = -3255522
www.careerin.co.in
FLOAT
Example
Floats:
x = 1.10
y = 1.0
z = -35.59
www.careerin.co.in
COMPLEX
Example
Complex:
x = 3+5j
y = 5j
z = -5j
www.careerin.co.in
RANDOM NUMBER
Example
Import the random module, and display a random
number between 1 and 9:
import random
print(random.randrange(1,10))
www.careerin.co.in
PYTHON CASTING
There may be times when you want to specify a type on
to a variable. This can be done with casting.
Casting in python is therefore done using constructor
functions:
int() - constructs an integer number from an integer
literal, a float literal (by rounding down to the previous
whole number), or a string literal (providing the string
represents a whole number)
www.careerin.co.in
float() - constructs a float number from an integer literal,
a float literal or a string literal (providing the string
represents a float or an integer)
str() - constructs a string from a wide variety of data
types, including strings, integer literals and float literals
www.careerin.co.in
Example
Integers:
x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
www.careerin.co.in
Floats:
x = float(1) # x will be 1.0
y = float(2.8) # y will be 2.8
z = float("3") # z will be 3.0
w = float("4.2") # w will be 4.2
www.careerin.co.in
Strings:
x = str("s1") # x will be 's1'
y = str(2) # y will be '2'
z = str(3.0) # z will be '3.0'
www.careerin.co.in
PYTHON STRINGS
www.careerin.co.in
PYTHON STRINGS
Example
print("Hello")
print('Hello')
www.careerin.co.in
Assigning a string to a variable is done with the variable
name followed by an equal sign and the string:
a = "Hello"
print(a)
www.careerin.co.in
a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.""“
print(a)
www.careerin.co.in
STRINGS ARE ARRAYS
a = "Hello, World!"
print(a[1])
Output: e
www.careerin.co.in
STRING SLICING
Output: llo
www.careerin.co.in
NEGATIVE INDEXING
Output: orl
www.careerin.co.in
STRING LENGTH
a = "Hello, World!"
print(len(a))
Output:13
www.careerin.co.in
STRING METHODS
a = "Hello, World!"
print(a.lower())
www.careerin.co.in
The upper() method returns the string in upper case:
a = "Hello, World!"
print(a.upper())
www.careerin.co.in
The split() method splits the string into substrings if it
finds instances of the separator:
a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']
www.careerin.co.in
CHECK STRING
www.careerin.co.in
Check if the phrase "ain" is NOT present in the
following text:
txt = "The rain in Spain stays mainly in the plain"
x = "ain" not in txt
print(x)
Output: false
www.careerin.co.in
STRING FORMAT
www.careerin.co.in
Output:
My name is John, and I am 36
www.careerin.co.in
The format() method takes unlimited number of
arguments, and are placed into the respective
placeholders. We use { } as place holder.
Example
quantity = 3
itemno = 567
price = 49.95
myorder = ("I want { } pieces of item { } for { }
dollars.“)
print(myorder.format(quantity, itemno, price))
www.careerin.co.in
Output:
I want 3 pieces of item 567 for 49.95 dollars.
www.careerin.co.in
You can use index numbers {0} to be sure the arguments
are placed in the correct placeholders:
Example
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))
www.careerin.co.in
Output:
www.careerin.co.in
PYTHON
BOOLEANS
www.careerin.co.in
PYTHON BOOLEANS
www.careerin.co.in
print(10 > 9)
print(10 == 9)
print(10 < 9)
Output:
True
False
False
www.careerin.co.in
Example: Print a message based on whether the
condition is True or False.
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
Output: b is not greater than a
www.careerin.co.in
EVALUATE VALUES AND VARIABLES
print(bool("Hello"))
print(bool(15))
Output:
True
True
www.careerin.co.in
Almost any value is evaluated to True if it has some sort
of content.
Any string is True, except empty strings.
Example
bool("abc")
bool(123)
www.careerin.co.in
Output:True
True
True
www.careerin.co.in
In fact, there are not many values that evaluates to False,
except empty values, such as (), [], {}, "", the number 0,
and the value None. And of course the value False
evaluates to False.
Example
bool(False)
bool(None)
bool(0)
bool("")
bool(())
bool([])
www.careerin.co.in
bool({})
Output:
False
False
False
False
False
False
False
www.careerin.co.in
PYTHON
OPERATORS
www.careerin.co.in
PYTHON OPERATORS
Arithmetic operators
Assignment operators
Comparison operators
www.careerin.co.in
Logical operators
Identity operators
Membership operators
Bitwise operators
www.careerin.co.in
PYTHON ARITHMETIC OPERATORS
www.careerin.co.in
PYTHON ASSIGNMENT OPERATORS
www.careerin.co.in
PYTHON COMPARISON OPERATORS
www.careerin.co.in
PYTHON LOGICAL OPERATORS
www.careerin.co.in
PYTHON IDENTITY OPERATORS
www.careerin.co.in
x = ["apple", "banana"]
y = ["apple", "banana"]
z=x
print(x is z)
print(x is y)
# returns False because x is not the same object as y, even if they have the same content
print(x == y)
# to demonstrate the difference betweeen "is" and "==": this comparison returns True
because x is equal to y www.careerin.co.in
x = ["apple", "banana"]
y = ["apple", "banana"]
z=x
print(x is not z)
print(x is not y)
# returns True because x is not the same object as y, even if they have the same content
print(x != y)
# to demonstrate the difference betweeen "is not" and "!=": this comparison returns
False because x is equal to y www.careerin.co.in
PYTHON MEMBERSHIP OPERATORS
Operator Description
in Returns True if a sequence with
the specified value is present in the
object
not in Returns True if a sequence with the
specified value is not present in the object
www.careerin.co.in
x = ["apple", "banana"]
print("banana" in x)
x = ["apple", "banana"]
print("pineapple" not in x)
www.careerin.co.in
PYTHON BITWISE OPERATORS
www.careerin.co.in
INDENTATION IN YTHON
if a==1:
print(a)
if b==2:
print(b)
print('end')
www.careerin.co.in
PYTHON USER INPUT
EXAMPLE:
username = input("Enter username:")
print("Username is: " + username)
www.careerin.co.in
OUTPUT:
www.careerin.co.in
INTEGER AS AN INPUT
EXAMPLE:
x = int(input("Enter a number: "))
Print(x)
Print(y)
Output:
Enter a number: 22
22
25 www.careerin.co.in
PYTHON
CONDITIONAL
STATEMENTS
www.careerin.co.in
PYTHON IF ... ELSE
b is greater than a
www.careerin.co.in
ELIF
www.careerin.co.in
ELSE
www.careerin.co.in
PYTHON WHILE LOOPS
Example
Print i as long as i is less than 6:
i=1
while i < 6:
print(i)
i += 1
Output: 1 2 3 4 5
www.careerin.co.in
THE BREAK STATEMENT
The break statement can stop the loop even if the while
condition is true.
i=1
while i < 6:
print(i)
if i == 3:
break
i += 1
Output: 1 2 3
www.careerin.co.in
THE CONTINUE STATEMENT
Output: 1 2 4 5 6
www.careerin.co.in
THE ELSE STATEMENT
www.careerin.co.in
PYTHON FOR
LOOPS
www.careerin.co.in
PYTHON FOR LOOPS
A for loop is used for iterating over a sequence (that is either a
list, a tuple, a dictionary, a set, or a string)
Syntax is for followed by a variable followed by in and followed
by the variable to iterate and colon
Indentation is applied in for
Example
www.careerin.co.in
LOOPING THROUGH A STRING
Even strings are iterable objects, they contain a sequence of
characters
Example
for x in "banana":
print(x)
Output: b
a
n
a
n
a
www.careerin.co.in
THE BREAK STATEMENT
The break statement stops the loop before it has looped
through all the items
Example
banana
www.careerin.co.in
THE CONTINUE STATEMENT
The continue statement stops the current iteration of the
loop, and continue with the next
Example
cherry
www.careerin.co.in
THE RANGE() FUNCTION
for x in range(6):
print(x)
Output: 0 1 2 3 4 5
Example
www.careerin.co.in
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
www.careerin.co.in
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
finally finished
www.careerin.co.in
NESTED LOOPS
A nested loop is a loop inside a loop.
The "inner loop" will be executed one time for each
iteration of the "outer loop"
Example: print the colour of fruit along with name
www.careerin.co.in
PYTHON
FUNCTIONS
www.careerin.co.in
PYTHON FUNCTIONS
www.careerin.co.in
CREATING A FUNCTION
Example
def my_function():
print("Hello from a function")
www.careerin.co.in
CALLING A FUNCTION
def my_function():
print("Hello from a function")
my_function()
output: Hello from a function
www.careerin.co.in
ARGUMENTS
www.careerin.co.in
Example
def my_function(fname):
print(fname + " kumar")
my_function(“Muthu")
my_function(“Ramesh")
my_function(“Raj")
Output: muthu kumar
Ramesh kumar
Raj kumar
www.careerin.co.in
ARGUMENT TYPE
The Function arugments are of four types
Required arguments
Keyword arguments
Default arguments
Variable-length arguments
www.careerin.co.in
REQUIRED ARGUMENTS
print (str )
printme(“hello”)
Output: hello
www.careerin.co.in
KEYWORD ARGUMENTS
www.careerin.co.in
Example
def printinfo( name, age ):
Output:
Name: miki
Age 50
www.careerin.co.in
DEFAULT ARGUMENTS
Example:
A default argument is an argument that assumes a default
value if a value is not provided in the function call for
that argument.
Example:
printinfo( name="miki" )
www.careerin.co.in
VARIABLE-LENGTH ARGUMENTS
A function for more arguments than you specified while
defining the function. These arguments are called
variable-length arguments
Example:
print (var)
printinfo( 10 )
www.careerin.co.in
Output:
10
70 60 50
www.careerin.co.in
THE RETURN STATEMENT
www.careerin.co.in
Output:
Sum:30
abc: 30
www.careerin.co.in
PYTHON LISTS
www.careerin.co.in
PYTHON LISTS
List is a sequential data type in python
A list is a collection of datas which is ordered and
changeable. In Python lists are written with square
brackets, a list can have string or numerical data
The list is created by using square bracket with each
elements separated by commas, each element in a list is
indexed beginning with [0] ie: the index for apple is [0],
banana is [1] and so on
Example: thislist = ["apple", "banana", "cherry"]
print(thislist)
Output: ["apple", "banana", "cherry"]
www.careerin.co.in
ACCESS ITEMS IN A LIST
Example
thislist = ["apple", "banana", "cherry"]
print(thislist[1])
Output: banana
www.careerin.co.in
NEGATIVE INDEXING
Negative indexing means beginning from the end, -1
refers to the last item, -2 refers to the second last item etc
Example:
Output: cherry
www.careerin.co.in
RANGE OF INDEXES
www.careerin.co.in
Example:
thislist = ["apple", "banana", "cherry", "orange", "kiwi",
"melon", "mango"]
print(thislist[:4])
www.careerin.co.in
thislist = ["apple", "banana", "cherry", "orange", "kiwi",
"melon", "mango"]
print(thislist[2:])
www.careerin.co.in
RANGE OF NEGATIVE INDEXES
www.careerin.co.in
This example returns the items from index -4 (included)
to index -1 (excluded)
Output:
['orange', 'kiwi', 'melon']
www.careerin.co.in
CHANGE ITEM VALUE
www.careerin.co.in
LOOP THROUGH A LIST
Output:
apple
banana
cherry
www.careerin.co.in
CHECK IF ITEM EXISTS
Example:
thislist = ["apple", "banana", "cherry"]
if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")
Output: Yes, 'apple' is in the fruits list
www.careerin.co.in
LIST LENGTH
Example
Print the number of items in the list:
www.careerin.co.in
ADD ITEMS
Example
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)
Output:
['apple', 'banana', 'cherry', 'orange']
www.careerin.co.in
INSERT() METHOD
To add an item at the specified index, use the insert()
method
Example
www.careerin.co.in
REMOVE ITEM
Output:['apple', 'cherry']
www.careerin.co.in
The pop() method removes the specified index, (or the
last item if index is not specified)
Example
www.careerin.co.in
The del keyword removes the specified index
thislist = ["apple", "banana", "cherry"]
del thislist[0]
print(thislist)
www.careerin.co.in
The clear() method empties the list:
Example
Output: [ ]
www.careerin.co.in
COPY A LIST
www.careerin.co.in
thislist = ["apple", "banana", "cherry"]
mylist = list(thislist)
print(mylist)
www.careerin.co.in
JOIN TWO LISTS
Example
www.careerin.co.in
Output: ['a', 'b', 'c', 1, 2, 3]
list1.extend(list2)
print(list1)
www.careerin.co.in
Output:
['a', 'b', 'c', 1, 2, 3]
www.careerin.co.in
THE LIST() CONSTRUCTOR
www.careerin.co.in
PYTHON SETS
www.careerin.co.in
PYTHON SETS
Create a Set:
www.careerin.co.in
ACCESS ITEMS IN SETS
Set cannot be accessed by items in a set by referring to
an index, since sets are unordered the items has no index.
But you can loop through the set items using a for loop,
or ask if a specified value is present in a set, by using the
in keyword.
Example
www.careerin.co.in
Output: cherry
banana
apple
Example
www.careerin.co.in
CHANGE ITEMS IN A SET
www.careerin.co.in
Example:
thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
print(thisset)
www.careerin.co.in
Add multiple items to a set, using the update() method:
Example:
print(thisset)
Output:{'grapes', 'mango', 'orange', 'apple', 'cherry',
'banana'}
www.careerin.co.in
To determine how many items a set has, use the len()
method.
Example
print(len(thisset))
Output: 3
www.careerin.co.in
REMOVE ITEM
To remove an item in a set, use the remove(), or the
discard() method.
Example
www.careerin.co.in
Remove the last item by using the pop() method:
Example
Output: apple
{'banana', 'cherry'}
www.careerin.co.in
The clear() method empties the set:
Example:
thisset = {"apple", "banana", "cherry"}
thisset.clear()
print(thisset)
Output: set()
www.careerin.co.in
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 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set3 = set1.union(set2)
print(set3)
www.careerin.co.in
Output:
{2, 'a', 1, 3, 'c', 'b'}
set2 = {1, 2, 3}
set1.update(set2)
print(set1
www.careerin.co.in
Output: {3, 'a', 'b', 1, 2, 'c'}
www.careerin.co.in
The set() Constructor
It is also possible to use the set() constructor to make a
set.
Example
www.careerin.co.in
PYTHON TUPLES
www.careerin.co.in
PYTHON TUPLES
Create a Tuple:
www.careerin.co.in
ACCESS TUPLE ITEMS
banana
www.careerin.co.in
NEGATIVE INDEXING
cherry
www.careerin.co.in
RANGE OF INDEXES
www.careerin.co.in
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 method to change it. You can convert the
tuple into a list, change the list, and convert the list back
into a tuple.
Example
Example
Example:
thistuple = ("apple", "banana", "cherry")
if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")
Output:
Yes, 'apple' is in the fruits tuple
www.careerin.co.in
ADD ITEMS
www.careerin.co.in
REMOVE ITEMS
Example:
The del keyword can delete the tuple completely:
www.careerin.co.in
JOIN TWO TUPLES
www.careerin.co.in
THE TUPLE() CONSTRUCTOR
Example:
thistuple = tuple(("apple", "banana", "cherry"))
print(thistuple)
www.careerin.co.in
PYTHON-
DICTIONARIES
www.careerin.co.in
PYTHON DICTIONARIES
www.careerin.co.in
Example
Create and print a dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
In the above example the key is brand and the value is
Ford , in the next pair model is the key and Mustang is
the value.
www.careerin.co.in
Ouput:
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
www.careerin.co.in
ACCESSING ITEMS IN DICTIONARY
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]
Print(x) www.careerin.co.in
Output: Mustang
There is also a method called get() that will give you the
same result
x = thisdict.get("model")
Print(x)
Output: Mustang
www.careerin.co.in
CHANGE VALUES IN A DICTIONARY
print (Capital)
www.careerin.co.in
Output:
{"Austria":"Vienna", "Switzerland":"Bern",
"Germany":"Berlin", "Netherlands":"Amsterdam"}
www.careerin.co.in
LOOP THROUGH A DICTIONARY
www.careerin.co.in
Output
Austria
Switzerland
Germany
Netherlands
www.careerin.co.in
Example : To access values
capital ={"Austria":"Vienna", "Switzerland":"Bern",
"Germany":“Berlin", "Netherlands":"Amsterdam"}
For x in capital:
Print(capital[x])
Output:
Vienna
Bern
Berlin
Amsterdam
www.careerin.co.in
You can also use the values() function to return values of
a dictionary
Example:
for x in capital.values():
print(x)
www.careerin.co.in
Loop through both keys and values, by using the items()
function:
Example:
for x, y in thisdict.items():
print(x, y)
www.careerin.co.in
CHECK IF KEY EXISTS
print(“Germany is present”)
Else:
www.careerin.co.in
Output:
Germany is present
www.careerin.co.in
ADDING NEW ITEMS TO A
DICTIONARY
Print(capital)
www.careerin.co.in
Output:
{"Austria":"Vienna", "Switzerland":"Bern",
"Germany":“Berlin", "Netherlands":"Amsterdam“
“India” : “Newdelhi”}
www.careerin.co.in
REMOVING ITEMS
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
www.careerin.co.in
thisdict.pop("model")
print(thisdict)
Output: {'brand': 'Ford', 'year': 1964}
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
www.careerin.co.in
del thisdict
print(thisdict)
www.careerin.co.in
NESTED DICTIONARIES
www.careerin.co.in
Output:
www.careerin.co.in
UPDATE: MERGING DICTIONARIES
www.careerin.co.in
knowledge.update(knowledge2)
Print(knowledge)
Output:
{'Frank': {'Python', 'Perl'}, 'Guido': {'Python'}, 'Monica':
{'C', 'C++'}}
www.careerin.co.in
LISTS FROM DICTIONARIES
items_view = pets.items()
www.careerin.co.in
items = list(items_view) >>>
Print( items)
print(keys)
www.careerin.co.in
THE DICT() CONSTRUCTOR
www.careerin.co.in
PYTHON– OBJECT
ORIENTED
PROGRAMMING
www.careerin.co.in
PYTHON - OOPS
Python Class
www.careerin.co.in
CREATE A CLASS
class MyClass:
x=5
Create Object
www.careerin.co.in
Example
Create an object named p1, and print the value of x:
p1 = MyClass()
print(p1.x)
class MyClass:
x=5
p1 = MyClass()
print(p1.x)
OUTPUT: 5
www.careerin.co.in
THE __INIT__() FUNCTION
www.careerin.co.in
THE SELF PARAMETER
www.careerin.co.in
EXAMPLE:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
www.careerin.co.in
OBJECT IN PYTHON
Object is simply a collection of data (variables) and methods
(functions) that act on those data. And, class is a blueprint for
the object.
EXAMPLE:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
www.careerin.co.in
OUTPUT:
John
36
www.careerin.co.in
OBJECT METHODS
The method in object refers to the functions in the object
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()
www.careerin.co.in
OUTPUT:
Hello my name is John
www.careerin.co.in
THE PASS STATEMENT
class Person:
pass
www.careerin.co.in
PYTHON INHERITANCE
www.careerin.co.in
CREATE A PARENT CLASS
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
x = Person("John", "Doe")
x.printname()
www.careerin.co.in
OUTPUT:
John Doe
www.careerin.co.in
CREATE A CHILD CLASS
www.careerin.co.in
Example:
class Person:
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
class Student(Person):
pass
x = Student("Mike", "Olsen")
x.printname()
www.careerin.co.in
Output : Mike olsen
www.careerin.co.in
TYPES OF INHERITANCE
Single Inheritance
Multiple Inheritance
Multilevel Inheritance
Hybrid Inheritance
Hierarchical Inheritance
www.careerin.co.in
SINGLE INHERITANCE
www.careerin.co.in
MULTIPLE INHERITANCE
MULTIPLE INHERITANCE
Multiple inheritance is possible in python A class can be
derived from more then one base classes. The syntax for
multiple inheritance is similar to single inheritance
Here is an example of multiple inheritance
www.careerin.co.in
EXAMPLE
www.careerin.co.in
OUTPUT
45
25
www.careerin.co.in
MULTILEVEL INHERITANCE
Multilevel inheritance is also possible in Python like
other Object Oriented programming languages. We can
inherit a derived class from another derived class, this
process is known as multilevel inheritance. In Python,
multilevel inheritance can be done at any depth.
www.careerin.co.in
EXAMPLE
www.careerin.co.in
OUTPUT
45
www.careerin.co.in
HYBRID INHERITANCE
www.careerin.co.in
EXAMPLE
www.careerin.co.in
OUTPUT
M( ) from class d
M( ) from class b
M( ) from class a
M( ) from class a
www.careerin.co.in
FILE HANDLING IN
PYTHON
www.careerin.co.in
FILE HANDLING IN PYTHON
File handling is an important part of any web
application.
The file handling performs three important functions
i) Read files
www.careerin.co.in
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:
f = open( “filename.txt”)
www.careerin.co.in
PYTHON READ FILES
f = open("demofile.txt", "r")
print(f.read())
Output: the above code opens the contents in the file. Let
us assume that it has the below text
Hello! Welcome to demofile.txt
This file is for testing purposes.
Good Luck!
www.careerin.co.in
READ ONLY PARTS OF THE FILE
The read() method returns the whole text, but you can
also specify how many characters you want to return
Example
f = open("demofile.txt", "r")
print(f.read(5))
Output:Hello
www.careerin.co.in
READLINE()
The readline() method returns one line from the text file.
Example
f = open("demofile.txt", "r")
print(f.readline())
www.careerin.co.in
TO READ TWO LINES
By calling readline() two times, you can read the two
first lines
Example
f = open("demofile.txt", "r")
print(f.readline())
print(f.readline())
Output:
f = open("demofile.txt", "r")
print(f.readline())
f.close()
www.careerin.co.in
PYTHON FILE WRITE
www.careerin.co.in
Example
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()
f = open("demofile2.txt", "r")
print(f.read())
Output:
www.careerin.co.in
OVERWRITE THE CONTENTS IN FILE
The overwriting in a file is done by using the keyword
‘W’, it deletes the contents present previously and
replace it with the content we give .
Example
f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()
f = open("demofile3.txt", "r")
print(f.read())
www.careerin.co.in
Output:
Woops! I have deleted the content!
www.careerin.co.in
APPEND TEXT TO A FILE
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()
f = open("demofile2.txt", "r")
print(f.read())
www.careerin.co.in
OUTPUT
www.careerin.co.in
CREATE A NEW FILE
Example
Create a file called "myfile.txt":
f = open("myfile.txt", "x")
Example
Create a new file if it does not exist:
f = open("myfile.txt", "w")
www.careerin.co.in
PYTHON DELETE FILE
Example
Remove the file "demofile.txt":
import os
os.remove("demofile.txt")
www.careerin.co.in
CHECK IF FILE EXIST:
import os
if os.path.exists("demofile.txt"):
os.remove("demofile.txt")
else:
print("The file does not exist")
www.careerin.co.in
DELETE FOLDER
import os
os.rmdir("myfolder")
www.careerin.co.in
PYTHON DATE AND
TIME
www.careerin.co.in
PYTHON DATETIME
import datetime
datetime_object = datetime.datetime.now()
print(datetime_object)
www.careerin.co.in
GET CURRENT DATE
EXAMPLE:
import datetime
date_object = datetime.date.today() print(date_object)
OUTPUT
2020-04-07
www.careerin.co.in
DATE TIME CLASS
Commonly used classes in the datetime module are:
date Class
time Class
datetime Class
timedelta Class
www.careerin.co.in
DATETIME.DATE CLASS
The date class accepts a date from the user
Example
import datetime
d = datetime.date(2020, 4, 07)
print(d)
OUTPUT
2020-04-07
www.careerin.co.in
PRINT TODAY'S YEAR, MONTH AND
DAY
EXAMPLE
from datetime import date
today = date.today( )
Current month: 04
Current DAY: 07
www.careerin.co.in
DATETIME.TIME CLASS
a = time( )
print("a =", a)
print("b =", b)
www.careerin.co.in
OUTPUT
a = 00:00:00
b = 11:34:56
c = 11:34:56
d = 11:34:56.234566
www.careerin.co.in
PRINT HOUR, MINUTE, SECOND AND MICROSECOND
EXAMPLE:
from datetime import time
www.careerin.co.in
OUTPUT
hour = 11
minute = 34
second = 56
microsecond = 0
www.careerin.co.in
DATETIME.DATETIME CLASS
EXAMPLE:
print(a)
www.careerin.co.in
OUTPUT
2020-11-28 00:00:00
2020-11-28 23:55:59.342380
www.careerin.co.in
DATETIME.TIMEDELTA
www.careerin.co.in
t5 = datetime(year = 2019, month = 6, day = 10, hour =
5, minute = 55, second = 13)
t6 = t4 - t5
OUTPUT:
t3 = 201 days, 0:00:00
www.careerin.co.in
DIFFERENCE BETWEEN TWO TIMEDELTA
OBJECTS
EXAMPLE
www.careerin.co.in
OUTPUT
t3 = 14 days, 13:55:39
www.careerin.co.in
PYTHON STRFTIME()
www.careerin.co.in
EXAMPLE
From datetime import datetime
now = datetime.now()
t = now.strftime("%H:%M:%S")
print("time:", t)
s1 = now.strftime("%m/%d/%Y, %H:%M:%S")
print("s1:", s1)
s2 = now.strftime("%d/%m/%Y, %H:%M:%S")
print("s2:", s2)
www.careerin.co.in
OUTPUT:
time: 04:34:52
s1: 04/07/2018, 04:34:52
www.careerin.co.in
PYTHON STRPTIME() - STRING TO DATETIME
www.careerin.co.in
EXAMPLE:
from datetime import datetime
www.careerin.co.in
OUTPUT:
date_string = 21 June, 2018
www.careerin.co.in
PYTHON
EXCEPTION
HANDLING
www.careerin.co.in
PYTHON EXCEPTION HANDLING
When an error occurs, or exception as we call it, Python
will normally stop and generate an error message
www.careerin.co.in
TRY BLOCK
The try block raises an error, the except block will
handle the error and the output in the except block will
be executed
Example:
try:
print(x)
except:
print("An exception occurred")
Example:
Print one message if the try block raisesNameError and
another for other errors.
try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong"
www.careerin.co.in
OUTPUT:
www.careerin.co.in
We can use the else keyword to define a block of code to
be executed if no errors were raised
Example
Nothing went wrong
www.careerin.co.in
FINALLY BLOCK
try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")
www.careerin.co.in
Output:
www.careerin.co.in
RAISE AN EXCEPTION
EXAMPLE:
Example
x = -1
if x < 0:
raise Exception("Sorry, no numbers below zero")
www.careerin.co.in
OUTPUT:
Traceback (most recent call last):
File "demo_ref_keyword_raise.py", line 4, in
<module>
raise Exception("Sorry, no numbers below zero")
Exception: Sorry, no numbers below zero
www.careerin.co.in
Example
Raise a TypeError if x is not an integer:
x = "hello"
www.careerin.co.in
OUTPUT:
Traceback (most recent call last):
File "demo_ref_keyword_raise2.py", line 4, in
<module>
raise TypeError("Only integers are allowed")
TypeError: Only integers are allowed
www.careerin.co.in
PYTHON- MY
SQL
www.careerin.co.in
PYTHON MYSQL DATABASE CONNECTION
www.careerin.co.in
The cursor.execute() to execute SQL queries from
Python
www.careerin.co.in
PYTHON EXAMPLE TO CONNECT MYSQL DATABASE
www.careerin.co.in
Host Name – is the server name or Ip address on which
MySQL is running. if you are running on localhost, then
you can use localhost, or it’s IP, i.e. 127.0.0.0
Database Name – Database name to which you want to
connect. Here we are using Database named
‘Electronics‘ because we have already created this for
our example
www.careerin.co.in
EXAMPLE TO CREATE A DATABASE
CONNECTION
Create database Electronics;
import mysql.connector from mysql.connector import
Error
try: connection = mysql.connector.connect(host='localhost',
database='Electronics', user=‘root', password=‘ ‘)
if connection.is_connected():
db_Info = connection.get_server_info() print("Connected
to MySQL Server version ", db_Info) cursor =
connection.cursor( )
cursor.execute("select database( );")
record = cursor.fetchone() www.careerin.co.in
print("You're connected to database: ", record)
except Error as e:
print("Error while connecting to MySQL", e)
finally:
if (connection.is_connected( )):
cursor.close( )
connection.close( )
print("MySQL connection is closed")
www.careerin.co.in
OUTPUT
Connected to MySQL Server version 5.7.19
www.careerin.co.in
UNDERSTAND THE PYTHON MYSQL
DATABASE CONNECTION PROGRAM
import mysql.connector
This line imports the MySQL Connector Python module
in your program so you can use this module’s API to
connect MySQL.
from mysql.connector import Error
www.careerin.co.in
mysql.connector.connect()
Using this method we can connect the MySQL Database,
this method accepts four required parameters: Host,
Database, User and Password that we already
discussed.
connect() method established a connection to the
MySQL database from Python application and returned a
MySQLConnection object. Then we can use
MySQLConnection object to perform various operations
on the MySQL Database.
www.careerin.co.in
The Connect() method can throw an exception, i.e.
Database error if one of the required parameters is
wrong. For example, if you provide a database name that
is not present in MySQL, then Python application throws
an exception. So check the arguments that you are
passing to this method.
connection.is_connected()
www.careerin.co.in
connection.cursor()
This method returns a cursor object. Using a cursor object, we
can execute SQL queries.
The MySQLCursor class instantiates objects that can execute
operations such as SQL statements.
Cursor objects interact with the MySQL server using a
MySQLConnection object.
cursor.close()
Using the cursor’s close method we can close the cursor
object. Once we close the cursor object, we can not execute
any SQL statement.
www.careerin.co.in
connection.close()
At last, we are closing the MySQL database connection
using a close() method of MySQLConnection class.
www.careerin.co.in
PYTHON MYSQL CREATE TABLE
import mysql.connector
from mysql.connector import Error
try: connection =
mysql.connector.connect(host='localhost',
database='Electronics', user='pynative',
password='pynative@#29')
www.careerin.co.in
mySql_Create_Table_Query = """CREATE TABLE
Laptop ( Id int(11) NOT NULL, Name
varchar(250) NOT NULL, Price float NOT
cursor = connection.cursor()
result = cursor.execute(mySql_Create_Table_Query)
www.careerin.co.in
except mysql.connector.Error as error: print("Failed to
create table in MySQL: {}".format(error))
finally:
if (connection.is_connected( )):
cursor.close( )
connection.close( )
print("MySQL connection is closed")
www.careerin.co.in
OUTPUT
Laptop Table created successfully
www.careerin.co.in
PYTHON INSERT INTO MYSQL TABLE
try:
connection = mysql.connector.connect(host='localhost',
database='electronics', user='root', password=‘ ‘)
www.careerin.co.in
mySql_insert_query = """INSERT INTO Laptop (Id,
Name, Price, Purchase_date) VALUES (10, 'Lenovo
ThinkPad P71', 6459, '2019-08-14') """
cursor = connection.cursor()
cursor.execute(mySql_insert_query)
connection.commit( )
www.careerin.co.in
except mysql.connector.Error as error: print("Failed to
insert record into Laptop table {}".format(error))
finally:
if (connection.is_connected( )):
connection.close( )
www.careerin.co.in
OUTPUT
Record inserted successfully into Laptop table
www.careerin.co.in
PYTHON SELECT FROM MYSQL
TABLE
www.careerin.co.in
EXAMPLE FOR MY SQL SELECT
import mysql.connector
from mysql.connector import Error
try:
connection = mysql.connector.connect(host='localhost',
database='Electronics', user=‘root', password=‘ ‘)
www.careerin.co.in
sql_select_Query = "select * from Laptop"
cursor = connection.cursor( )
cursor.execute(sql_select_Query)
records = cursor.fetchall( )
www.careerin.co.in
for row in records:
print("Id = ", row[0], )
print("Name = ", row[1])
print("Price = ", row[2])
print("Purchase date = ", row[3], "\n")
except Error as e:
print("Error reading data from MySQL table", e)
www.careerin.co.in
finally:
if (connection.is_connected()):
connection.close( )
cursor.close( )
www.careerin.co.in
OUTPUT
Total number of rows in Laptop is: 7
Printing each laptop record
Id = 1
Price = 6459.0
www.careerin.co.in
PYTHON UPDATE MYSQL TABLE
www.careerin.co.in
import mysql.connector
from mysql.connector import Error
try:
connection = mysql.connector.connect(host='localhost',
database='Electronics', user=‘root', password=‘ ‘)
www.careerin.co.in
cursor = connection.cursor( )
print("Before updating a record ") sql_select_query =
"""select * from Laptop where id = 1"""
cursor.execute(sql_select_query)
www.careerin.co.in
sql_update_query = """Update Laptop set Price = 7000
where id = 1"""
cursor.execute(sql_update_query)
connection.commit( )
cursor.execute(sql_select_query)
finally:
if (connection.is_connected()):
connection.close( )
print("MySQL connection is closed")
www.careerin.co.in
OUTPUT
Before updating a record
(1, 'Lenovo ThinkPad P71', 6459.0, datetime.date(2019,
8, 14))
Record Updated successfully
www.careerin.co.in
PYTHON DELETE DATA FROM MYSQL
TABLE
import mysql.connector
from mysql.connector import Error
try:
connection = mysql.connector.connect(host='localhost',
database='Electronics', user=‘root', password=‘ ‘)
www.careerin.co.in
cursor = connection.cursor( )
delete_table_query = """DROP TABLE Laptop"""
cursor.execute(delete_table_query)
delete_database_query = """DROP DATABASE
Electronics""" cursor.execute(delete_database_query)
connection.commit( )
print("Table and Database Deleted successfully ")
www.careerin.co.in
except mysql.connector.Error as error:
print("Failed to Delete table and database:
{}".format(error))
finally:
if (connection.is_connected( )):
cursor.close( ) connection.close( )
print("MySQL connection is closed")
www.careerin.co.in
OUTPUT
Table and Database Deleted successfully
www.careerin.co.in