Python
Python
what is python:-
Python is a powerful high level language. Python is clearly defined and easily
readable. The Structure of the program is very simple. It uses few keywords. It was
created by Guido van Rossum, and released in 1991.
Why Python?
Python works on cross platforms (Windows, Mac, Linux, Raspberry Pi, etc).
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.
PVM converts the python byte code into machine executable code.
* object-Oriented.
Uses of Python:-
o Data Science
o Date Mining
o Desktop Applications
o Console-based Applications
o Mobile Applications
o Software Development
o Artificial Intelligence
o Web Applications
o Enterprise Applications
o 3D CAD Applications
o Machine Learning
o Computer Vision or Image Processing Applications.
o Speech Recognitions
Advantages of Python:-
• Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
• Python has syntax that allows developers to write programs with fewer lines
than some other programming languages.
To check if you have python installed on a Windows PC, search in the start
bar for Python or run the following on the Command Line (cmd.exe)
C:\Users\python
Run the program:-
Python is an interpreted programming language, this means that as a developer you
write Python (.py) files in a text editor and then put those files into the python
interpreter to be execute.
C:\Users\python Filename.py
Variables:-
Variables are containers for storing data values. It is memory location to store
the given data. Python has no command for declaring a variable. A variable is created
the moment you first assign a value to it.
For eg:
Data types:-
Built-in-data types:
Data types are the classification or categorization of data items. It represents the
kind of value.
Python has the following data types built-in by default, in these categories:
float, y=3.5
range x=range(6)
Extensible:-
programming can embbed python within their c, c++, java script, Activex, etc,.
Interactive mode:-
Interactive mode is where you type commands and they are immediately executed.
>>>print("Csc computer education")
Script mode:-
Script mode is where you write your code in a .py file and then run it with the python
command. This is the most common way that people use Python because it lets you
write and save your code so that you can use it again later.
Interpreter Language:-
Python syntax:-
Output function:
2) x=3
y=”john”
print(x)
print(y)
Input function:-
Python uses the input() method to get the input from the users.
print(username)
print(“username is ”+username)
Z=x+y
Print(z)
Comments:-
A hash sign (#) that is not inside a string literal begins a comment. All characters
after the # are part of the comment and the Python interpreter ignores them.
For eg:
print(“welcome to python”)
Multiline comments:-
Python does not really have a syntax for multi line comments.
For eg:
#This is a comment
#written in
print(x)
print(y)
print(z)
2) x = y = z = "Orange"
print(x)
print(y)
print(z)
3) fruits = ["apple", "banana", "grapes"]
x, y, z = fruits
print(x)
print(y)
print(z)
4) x=4
y=3.6
z=7j
print(x)
print(y)
print(z)
print(type(x))
print(type(y))
print(“welcome to python”)
Type casting:-
Type Casting is the method to convert the variable data type into a certain data
type in order to the operation required to be performed by users.
Ex:- x=float(1)
y=int(3.8)
z=str(4)
print(x)
print(y)
print(z)
Operators:-
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Identity operators
• Membership operators
• Bitwise operators
Arithmetic operators:-
Arithmetic operators are used with numeric values to perform common mathematical
operations:
Operator Name Example
Assignment operators:-
“ =” “//=”
x=3 x=7
“+=” “**=”
x=7 x=7
x+=3 x**=3
“-=” “&=”
x=7 x=7
x-=3 x&=3
print(x) print(x)
“*=” “|=”
x=7 x=7
x*=3 x|=3
print(x) print(x)
“/=” “^=”
x=7 x=7
x/=3 x^=3
print(x) print(x)
Logical operators:-
“and”
Ex;-
x=5
“Or”
Ex:-
x=5
“not”
Ex:-
x=5
print (not(x>7 and x<3)) #Reverse the result, returns False if the result is true
Identity operators:-
Identity operators are used to compare the objects, not if they are equal, but if
they are actually the same object, with the same memory location:
“is”
y=”computer”
z=y
print(x is y) #returns False because x is not the same object as y, even if they have
the same content
print(z is y)
“is not”
y=”computer”
print(x is not y) #Returns True if both variables are not the same object
Membership operator:-
“in”
x=”csc computer”
print(“computer” in x) #Returns True if a sequence with the specified value
is present in the object
“not in”
x=”csc computer”
Bitwise operator:-
Ex:
a=10, b=7
c=a&b
print(c)
Ex:
a=10, b=7
c=a|b
print(c)
Ex:-
a=10, b=7
c=a^b
print(c)
Ex:-
a=7, b=~a
print(b)
<< Zero fill left shift Shift left by pushing zeros in from the right and let the
leftmost bits fall off
Ex:-
a=10
print(a<<2)
>> Signed right shift Shift right by pushing copies of the leftmost bit in from the
left, and let the rightmost bits fall off
Ex:
a=10
print(a>>2)
Escape characters:-
An escape character is a backslash \ followed by the character you want to
insert.
Ex:-
print(txt)
Code Result
\\ Backslash
\n New Line
\r Carriage Return
\t Tab
\b Backspace
\f Form Feed
Conditional
UnConditional
Conditional statement Control statements are used to control the flow of the
execution of the loop based on a condition.
Syntax: if expression:
statement
Ex:-
x=3
y=5
if x==y:
If statements:-
Ex:-
a = 33
b = 200
if b > a:
elif statements:-
The elif keyword is pythons way of saying "if the previous conditions were not
true, then try this condition".
Ex:-
a = 33
b = 33
if b > a:
elif a == b:
else statements:-
The else keyword executed anything which isn't executed by the preceding
conditions.
Syntax: if condition:
#block of statements
else:
#another block of statements (else-block)
Ex:-
a = 20
b = 33
if b > a:
elif a == b:
Nested if:-
You can have if statements inside if statements, this is called nested if statements.
num=15
if num>=0:
if num==0:
Print(“zero”)
else:
print(“Positive number”)
else:
print(“Negative number”)
Looping in python:-
Looping means repeating something over and over until a particular condition is
satisfied.
• while loops
• for loops
While loop:-
Ex:-
i=1
print(i)
i += 1 # i=i+1
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).With the for loop we can execute a set of statements, once
for each item in a list, tuple, set etc.
for x in fruits:
print(x)
2) for x in "banana":
print(x)
For else:-
The else keyword in a for loop specifies a block of code to be executed when the
loop is finished.
Ex:-
For x in range(6):
Print(x)
else:
print(“Finally finished!)
Range function:-
for x in range(6):
print(x)
print(x)
print(x)
Unconditional statement Python has various types of loop functions like for and
while. These loops are automatic and efficiently repeats the tasks. But sometimes,
where you want to exit the loop completely, skip an iteration or ignore that condition.
These can be done by unstructured loop control statements.
Break
Continue
pass
Break:-
Ex:-
for i in “python”:
if i==”h”:
break
print(“Letter: “,i)
Continue:-
The loop to skip the remainder of its body and immediately retest its condition prior
to reiterate.
Ex:-
for i in “python”:
if i==”h”:
continue
print(“letter: “,i)
Pass:-
Ex:-
for i in “python”:
pass
print(“finished”)
Array:-
Arrays are used to store multiple values in one single variable. An array is a
collection of items stored at contiguous memory locations. Python does not have built-
in support for Arrays, but Python Lists can be used instead.
An array can hold many values under a single name, and you can access the values by
referring to an index number.
String function:-
Ex:- “welcome”,”3”,”4.7”,”python”
print(a[1])
for x in "banana":
print(x)
Indexing :-
Accessing elements in string each element is accessed using indexing. The position of
each character.
Indexing
(positive) (Negative)
For Ex:-
Str = ”PYTHON”
0 1 2 3 4 5
P Y T H O N
-6 -5 -4 -3 -2 -1
Str[0]=’P’
Str[1]=’Y’
Str[2]=’T’
Str[3]=’H’
Str[4]=’O’
Str[5]=’N’
String length:
String operators:-
+ (Concatenation operation)
Basic operators
* (replication operation)
Concatenation operation:
Concatenate two strings and forms new string.
Ex:-
a = "csc"
b = "computer education"
c=a+b
print(c)
Replication Operation:
The string will be repeated the number of time which is given by the integer
value.
Ex:-
a=”python” *5
print(a)
Syntax:-
1. b = "Csc Computer Education!" #Get the character from index 2 to 4(5 not
include)
print(b[2:5])
2. b = " Csc Computer Education!" #It refers only the end index
String methods:-
Separator ‘,’,’m’,’u’
The format() method is the most flexible and useful method in formatting strings. The
curly braces {} are used as the placeholder in the string and replaced by
the format() method argument.
Ex:-
#Positional Argument
print("{1} and {0} best players ".format("Virat","Rohit"))
#Keyword Argument
print("{a},{b},{c}".format(a = "James", b = "Peter", c = "Ricky"))
Integer = 10;
Float = 1.290
String = "Devansh"
print("Hi I am Integer ... My value is %d\nHi I am float ... My value is %f\nHi I am st
ring ... My value is %s"%(Integer,Float,String))
List in python:-
Lists are used to store multiple items in a single variable. Lists are one of 4 built-in
data types in Python used to store collections of data.
Ex:-
thislist[1] = "blackcurrant"
print(thislist)
thislist.insert(1, "orange")
print(thislist)
3) The append() method used to add items in the end of the list.
thislist.append("orange")
print(thislist)
4) The extend() method is used to append elements from another list to current list.
thislist.extend(tropical)
print(thislist)
t hislist.remove("banana")
print(thislist)
The pop() method removes the specified index. The del keyword also removes
the specified index.
thislist.pop(1)
print(thislist)
If you do not specify the index, the pop() method removes the last item.
thislist.pop()
print(thislist)
del thislist
Looping in lists:
for x in thislist:
print(x)
Join list:-
list2 = [1, 2, 3]
print(list3)
The concatenation (+) and repetition (*) operators work in the same way as they were
working with the strings. The different operations of list are
1. Repetition
2. Concatenation
3. Length
4. Iteration
5. Membership
1. Repetition
The repetition operator enables the list elements to be repeated multiple times.
# repetition of list
# declaring the list
list1 = [12, 14, 16, 18, 20]
# repetition operator *
l = list1 * 2
print(l)
2. Concatenation
3. Length
4. Iteration
print(600 in list1)
print(700 in list1)
print(1040 in list1)
print(300 in list1)
print(100 in list1)
print(500 in list1)
Iterating a List
A list can be iterated by using a for - in loop. A simple list containing four strings,
which can be iterated as follows.
# iterating a list
list = ["John", "David", "James", "Jonathan"]
for i in list:
# The i variable will iterate over the elements of the List and contains each element i
n each iteration.
print(i)
Python List Built-in Functions
Python provides the following built-in functions, which can be used with the lists.
1. len()
2. max()
3. min()
len( )
Max( )
Min( )
Method Description
append()
clear()
copy()
count()
extend()
Add the elements of a list (or any iterable), to the end of the current list
index()
Returns the index of the first element with the specified value
insert()
pop()
reverse()
sort()
Tuple in python:-
Tuples are used to store multiple items in a single variable. Tuple is one of 4 built-
in data types in Python used to store collections of data.
print(thistuple)
Print(tuple1)
Tuple items are indexed, the first item has index [0], the second item has index
[1] so on.
Tuples are ordered that means the items have a defined order, and that order
will not change.
Tuples are unchangeable, meaning that we cannot change, add or remove items
after the tuple has been created.
Change in tuple:-
Once a tuple is created, you cannot change its values. Tuples are unchangeable,
or immutable as it also is called.
But tuple items can be change by convert the tuple into list.
y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)
y = list(thistuple)
y.append("orange")
thistuple = tuple(y)
y = ("orange")
print(thistuple)
Tuples are unchangeable, so you cannot remove items from it like add items remove
is also done by convert the tuple into list.
y = list(thistuple)
y.remove("apple")
thistuple = tuple(y)
del thistuple
Unpacking a tuple:
print(red)
print(yellow)
print(purple)
An asterisk in tuple:-
If the number of variables is less than the number of values, you can add an
*(asterisk) to the variable name and the values will be assigned to the variable as a list.
print(red)
print(yellow)
print(purple)
Looping in tuple:-
for x in thistuple:-
print(x)
i=0
print(thistuple[i])
i=i+1
Join tuple:-
tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2
print(tuple3)
Method Description
count()
index()
Searches the tuple for a specified value and returns the position of where it was found
Sets in python:-
Sets are used to store multiple items in a single variable.Set is one of 4 built-in
data types in Python used to store collections of data.
print(thisset)
Set items are unordered, unchangeable, and do not allow duplicate values.
Unordered means that the items in a set do not have a defined order.Set items
can appear in a different order every time you use them, and cannot be referred to by
index or key.
Set items are unchangeable, meaning that we cannot change the items after the
set has been created.
print(thisset)
You cannot access items in a set by referring to an index or a key.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.
for x in thisset:
print(x)
thisset.add("orange")
thisset.update(tropical) #to add items from another set into current set use update()
print(thisset)
print(thisset)
print(thisset)
print(thisset)
Join sets:-
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.
set2 = {1, 2, 3}
set3 = set1.union(set2)
print(set3)
set2 = {1, 2, 3}
sent3=set1.update(set2)
print(set1)
Method Description
add()
clear()
copy()
difference()
difference_update()
Removes the items in this set that are also included in another, specified set
discard()
intersection()
intersection_update()
Removes the items in this set that are not present in other, specified set(s)
isdisjoint()
issubset()
issuperset()
remove()
symmetric_difference()
symmetric_difference_update()
union()
update()
Update the set with the union of this set and others
Python Dictionaries:-
Dictionaries are used to store data values in key:value pairs. Dictionaries are
written with curly bracket and have keys and values.
"brand": "Ford",
"year": 1964
print(thisdict)
Dictionary items are ordered, changeable, and does not allow duplicates.
Dictionaries are ordered, it means that the items have a defined order, and that
order will not change.
Dictionaries are changeable, meaning that we can change, add or remove items
after the dictionary has been created.
Ex:- thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
print(thisdict)
1)You can access the items of a dictionary by referring to its key name, inside
square brackets.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
x = thisdict["model"]
1) You can change the value of a specific item by referring to its key name.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
thisdict["year"] = 2018
2) The update() method will update the dictionary with the items from the given
argument.The argument must be a dictionary, or an iterable object with key:value
pairs.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
thisdict.update({"year": 2020})
1) Adding an item to the dictionary is done by using a new index key and
assigning a value to it.
Ex:- thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
thisdict["color"] = "red"
print(thisdict)
1) thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
print(thisdict)
2) thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
print(thisdict)
3) thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
print(thisdict)
4) thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
print(thisdict)
Looping in dictionaries:-
1) thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
2) thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
print(thisdict[x])
3) thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
print(x)
4) thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
print(x)
5) thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
print(x, y)
Method Description
clear()
copy()
fromkeys()
get()
items()
keys()
popitem()
setdefault()
Returns the value of the specified key. If the key does not exist: insert the key, with
the specified value
update()
values()
Python function:-
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.
1. def my_function():
2. # Defining a function
def a_function( string ):
#This prints the value of length of string
return len(string)
Syntax:-
def <function_name>([parameters])
Ex:-
def add(a,b)
c=a+b
print(c)
add(5,6)
1.local variable
2.global variable
Local variable:
Ex:-
a=”Ravanan”
print(a)
a()
Ex:-
def msg()
Print(a)
msg()
Ex:-
def msg()
print(“inside Function”,r)
r=”Manikutty”
msg()
print(“outside Function”,r)
2. User-defined.
Buil-in(Predefine)
User-defined:-
The following are the types of arguments that we can use to call a function:
Positional argument
Default argument
Key word argument
Arbitrary argument
c=a+b
print(c)
sum(10,20)
sum(20) (so, the number a parameter in the function call should match with be
number of parameter in this function definition)
2. Default argument
Ex:-
#function definition
def msg(Id,Name,Age=21):
Print(Id)
Print(Name)
Print(Age)
return
#function call
msg(Id=100,Name=”Arun”,Age=20)
msg(Id=101,Name=”Raj”)
Ex:-
def msg(Id,Name):
Print(Id)
Print(Name)
msg(Id=1000,Name=”Mani”)
msg(Name=”veera”,Id=1001)
Ex:-
def greetings(*friends):
print("hi",friends)
greetings("mani","marish","karthika","mathika")
FUNCTION PROTOTYPES
Anonymous Functions:-
any number of arguments, but can only have one expression. Anonymous function are
Syntax:
Ex:- 1) x = lambda a : a + 10
print(x(5))
2) x = lambda a, b : a * b
print(x(5, 6))
3) x = lambda a, b, c : a + b + c
print(x(5, 6, 2))
Ex:-
# Defining a function
lambda_ = lambda argument1, argument2: argument1 + argument2;
number()
word()
As the name says, python sum() function is used to get the sum of numbers of an
iterable, i.e., list.
s = sum([1, 2,4 ])
print(s)
Recursive function:-
Def fact(n):
if n==1:
return 1
else:
return(n*fact(n-1))
num=5
2) def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
mytripler = myfunc(3)
print(mydoubler(11))
print(mytripler(11))
o Class
o Object
o Method
o Inheritance
o Polymorphism
o Data Abstraction
o Encapsulation
Class
The class can be defined as a collection of objects. It is a logical entity that has some
specific attributes and methods. For example: if you have an employee class, then it
should contain an attribute and method, i.e. an email id, name, age, salary, etc.
Syntax
class ClassName:
<statement-1>
.
.
<statement-N>
Object
The object is an entity that has state and behavior. It may be any real-world object like
the mouse, keyboard, chair, table, pen, etc.
Everything in Python is an object, and almost everything has attributes and methods.
All functions have a built-in attribute __doc__, which returns the docstring defined in
the function source code.
Example:
class car:
def __init__(self,modelname, year):
self.modelname = modelname
self.year = year
def display(self):
print(self.modelname,self.year)
c1 = car("Toyota", 2016)
c1.display()
Method
The method is a function that is associated with an object. In Python, a method is not
unique to class instances. Any object type can have methods.
Inheritance
Example:-
# are called.
# parent class
class Person(object):
self.name = name
self.idnumber = idnumber
def display(self):
print(self.name)
print(self.idnumber)
def details(self):
print("IdNumber: {}".format(self.idnumber))
# child class
class Employee(Person):
self.salary = salary
self.post = post
def details(self):
print("IdNumber: {}".format(self.idnumber))
print("Post: {}".format(self.post))
# its instance
a.display()
a.details()
Polymorphism
Polymorphism contains two words "poly" and "morphs". Poly means many, and
morph means shape. By polymorphism, we understand that one task can be performed
in different ways. For example - you have a class animal, and all animals speak. But
they speak differently. Here, the "speak" behavior is polymorphic in a sense and
depends on the animal. So, the abstract "animal" concept does not actually "speak",
but specific animals (like dogs and cats) have a concrete implementation of the action
"speak".
Example:-
class Bird:
def intro(self):
def flight(self):
print("Most of the birds can fly but some cannot.")
class sparrow(Bird):
def flight(self):
class ostrich(Bird):
def flight(self):
obj_bird = Bird()
obj_spr = sparrow()
obj_ost = ostrich()
obj_bird.intro()
obj_bird.flight()
obj_spr.intro()
obj_spr.flight()
obj_ost.intro()
obj_ost.flight()
Encapsulation
Encapsulation is also an essential aspect of object-oriented programming. It is used to
restrict access to methods and variables. In encapsulation, code and data are wrapped
together within a single unit from being modified by accident.
Example:-
# Python program to
class Base:
def __init__(self):
self.a = "GeeksforGeeks"
self.__c = "GeeksforGeeks"
class Derived(Base):
def __init__(self):
# Calling constructor of
# Base class
Base.__init__(self)
print(self.__c)
# Driver code
obj1 = Base()
print(obj1.a)
# Uncommenting print(obj1.c) will
# raise an AttributeError
Data Abstraction
Data abstraction and encapsulation both are often used as synonyms. Both are nearly
synonyms because data abstraction is achieved through encapsulation. Abstraction is
used to hide internal details and show only functionalities. Abstracting something
means to give names to things so that the name captures the core of what a function or
a whole program does.
In Python, a class can be created by using the keyword class, followed by the class
name
class Employee:
id = 10
name = "Arunraj"
def display (self):
print(self.id,self.name)
Creating Objects (instance) in Python
A class needs to be instantiated if we want to use the class attributes in another class or
method. A class can be instantiated by calling the class using the class name
<object-name> = <class-name>(<arguments>)
class Employee:
id = 10
name = "John"
def display (self):
print("ID: %d \nName: %s"%(self.id,self.name))
# Creating a emp instance of Employee class
emp = Employee()
emp.display()
We can delete the properties of the object or object itself by using the del keyword.
Example
class Employee:
id = 10
name = "John"
def display(self):
print("ID: %d \nName: %s" % (self.id, self.name))
# Creating a emp instance of Employee class
emp = Employee()
Python Constructor
In C++ or Java, the constructor has the same name as its class, but it treats constructor
differently in Python. It is used to create an object.
1. Parameterized Constructor
2. Non-parameterized Constructor
In Python, the method the __init__() simulates the constructor of the class. This
method is called when the class is instantiated. It accepts the self-keyword as a first
argument which allows accessing the attributes or method of the class.
We can pass any number of arguments at the time of creating the class object,
depending upon the __init__() definition. It is mostly used to initialize the class
attributes. Every class must have a constructor, even if it simply relies on the
default constructor.
Example
class Employee:
def __init__(self, name, id):
self.id = id
self.name = name
def display(self):
print("ID: %d \nName: %s" % (self.id, self.name))
emp1.display()
The constructor is called automatically when we create the object of the class.
Consider the following example.
Example
class Student:
count = 0
def __init__(self):
Student.count = Student.count + 1
s1=Student()
s2=Student()
s3=Student()
print("The number of students:",Student.count)
The non-parameterized constructor uses when we do not want to manipulate the value
or the constructor that has only self as an argument.
class Student:
# Constructor - non parameterized
def __init__(self):
print("This is non parametrized constructor")
def show(self,name):
print("Hello",name)
student = Student()
student.show("John")
The parameterized constructor has multiple parameters along with the self.
class Student:
# Constructor - parameterized
def __init__(self, name):
print("This is parametrized constructor")
self.name = name
def show(self):
print("Hello",self.name)
student = Student("John")
student.show()
Python Default Constructor
When we do not include the constructor in the class or forget to declare it, then that
becomes the default constructor. It does not perform any task but initializes the
objects.
class Student:
roll_num = 101
name = "Joseph"
def display(self):
print(self.roll_num,self.name)
st = Student()
st.display()
Python Inheritance
Syntax
class derived-class(base class):
<cl ass-suite>
class derive-class(<base class 1>, <base class 2>, ..... <base class n>):
<class - suite>
Example 1
class Animal:
def speak(self):
print("Animal Speaking")
#child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog barking")
d = Dog()
d.bark()
d.speak()
Multi-level inheritance is archived when a derived class inherits another derived class.
There is no limit on the number of levels up to which, the multi-level inheritance is
archived in python.
Syntax
class class1:
<class-suite>
class class2(class1):
<class suite>
class class3(class2):
<class suite>
Example
class Animal:
def speak(self):
print("Animal Speaking")
#The child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog barking")
#The child class Dogchild inherits another child class Dog
class DogChild(Dog):
def eat(self):
print("Eating bread...")
d = DogChild()
d.bark()
d.speak()
d.eat()
Python provides us the flexibility to inherit multiple base classes in the child class.
Syntax
class Base1:
<class-suite>
class Base2:
<class-suite>
.
.
.
class BaseN:
<class-suite>
Example
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(d.Summation(10,20))
print(d.Multiplication(10,20))
print(d.Divide(10,20))
Modules :-
Modules:- (collection of function)
Ex:-
1.math-mathematical function:
Type of modules:-
1. User-defined
2. Predefined
Predefined function:-
String
Math
Random
Range
User-define:-
There are different ways by which you we can import a module(the file name is the
module name with the suffix .py).
Syntax:-
</file_name1>
Example:
Save the file by name arithmetic operation.py to import this file “import” statement is
used.
import addition
addition.add(10,20)
addition.add(30,40)
FILES:-
Type of files:-
1. Text Files
2. Binary Files
Binary files are not human readable files and the data is stored as machine
understandable binary language(OS and IS).
A text file is a sequence of characters stored on a permanent medium like a hard
drive, flash memory, or CD-ROM. Text file is a human readable file.
Modes of file
1. Read mode
2. Write mode
3. Append mode
1. READ MODE ‘r’ Read mode which is used when the file is only
being
2. WRITE MODE ‘w’ Write mode which is used to edit and write new
information to the file
3. APPEND MODE ‘a’ Which is used to add new data to the end of the
file.
Syntax errors
Runtime errors
Logical Errors
Syntax error:-
Syntax errors are mistakes in the use of the python language, and are analogous to
spelling or grammar mistake in a language like English.
My function(x,y):
return x+y
else:
print(“Hello”)
if mark>=50
print(“You paased!”)
if arriving:
print(“Hi!”)
else:
print(“BYE!!!”)
Runtime Errors:-
Logical errors:-
They occur when the program runs without crashing, but produces an incorrect result
Exceptions:-
Handling Exceptions:-
fh=open(“testfile”,”w”)
exceptIOError:
else:
fh.close()
Output:-