Python-Programming
Python-Programming
INTRODUCTION TO PYTHON
Introduction to 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.
Features of Python:
1. Simple
Python is a simple and minimalistic language. Reading a good Python
program feelsalmost like reading English language.
2. Easy to learn
Python uses very few keywords. Python has an extraordinarily simple syntax
and simple program structure.
3. Open Source
There is no need to pay for Python software. Python is FLOSS (Free/Library
and Open Source Software). Its source can be read, modified and used in
programs as desired by the programmers.
4. High level language
When you write programs in Python, you never need to bother aboutthe low-
level details such as managing the memory used by your program, etc.
5. Dynamically typed
Python provides IntelliSense. IntelliSense to make writing your code easier
and more error-free. IntelliSense option includes statement completion, which
provides quick access to valid member function or variables, including global,
via the member list. Selecting from the list inserts the member into your code.
6. Portable
Due to its open-source nature, Python has been ported to (i.e. changed to make
it work on) many platforms. All your Python programs can work on any of
these platforms without requiring any changes at all if you are careful enough
to avoid any system-dependent features.
7. Platform independent
When a Python program is compiled using a Python compiler, it generates
byte code. Python’s byte code represents a fixed set of instructions that run on
all operating systems and hardware. Using a Python Virtual Machine (PVM),
anybody can run these byte code instructions on any computer system. Hence,
Python programs are not dependent on any specific operating system.
8. Procedure and Object Oriented
Python supports procedure-oriented programming as well as object-oriented
programming. In procedure-oriented languages, the program is built around
procedures or functions which are nothing but reusable pieces of programs. In
object- oriented languages, the program is built around objects which combine
data and functionality.
FLAVORS OF PYTHON
Flavors of Python simply refers to the different Python compilers. These
flavors are useful to integrate various programming languages into Python. Let
us look at some of these flavors:
i. C Python
C Python is the Python compiler implemented in C programming language. In
this, Python code is internally converted into the byte code using standard C
functions. Additionally, it is possible to run and execute programs written in
C/C++ using CPython compiler.
ii. J Python
Earlier known as J Python. Jython is an implementation of the Python
programming language designed to run on the Java platform. Jython is
extremely useful because it provides the productivity features of a mature
scripting language while running on a JVM.
iii. PyPy
This is the implementation using Python language. PyPy often runs faster than
C Python because PyPy is a just-in-time compiler while CPython is an
interpreter.
iv. Iron Python
Iron Python is an open-source implementation of the Python programming
language which is tightly integrated with the .NET Framework.
v. Ruby Python
Ruby Python is a bridge between the Ruby and Python interpreters. It embeds
a Python interpreter in the Ruby application’s process using FFI (Foreign
Function Interface).
vi. Python xy
Python(x,y) is a free scientific and engineering development software for
numerical computations, data analysis and data visualization based on Python.
vii. Stockless Python
Stack less Python is a Python programming language interpreter. In practice,
Stack less Python uses the C stack, but the stack is cleared between function
calls
viii. Anaconda Python
Anaconda is a free and open-source distribution of the Python and R
programming languages for scientific computing, that aims to simplify
package management and deployment. Package versions are managed by the
package management system conda.
MANAGEMENT IN PYTHON
Garbage Collector
Garbage Collection is how the memory is freed when not use and how it
can be made available for other objects. Python deletes the objects that are no
longer in use. This is what we call Garbage Collection. The garbage collector
initiates its execution with the program and is activated if the reference count
drops to zero.
Static Memory Allocation – Stack
In static memory allocation, the memory is allocated at the compile time.
The Stack data structure stores the static memory.
Static int x=2;
Dynamic Memory Allocation – Heap
In dynamic memory allocation, the memory is allocated at the run time.
The Heap stores the dynamic memory. It frees up the memory space if the object
is no longer needed.
x = [0]*2
As we discussed above, the garbage collector initiates its execution with
the program and is activated if the reference count drops to zero.
Reference Count
The Python garbage collector initiates its execution with the program and
is activated if the reference count drops to zero. Let us see when the reference
count increase or decreases.
The reference count value increase when −
When a new name is assigned or in a dictionary or tuple, the reference
count increases its value.
If we reassign the reference to an object, the reference counts decrease its
value.
The reference count value decreases when −
The value decreases when the object's reference goes out of scope.
The value decreases when an object is deleted.
Therefore, reference counting is actually how many times other objects
reference an object. With that, The de-allocation occurs when the reference count
drops to zero.
The collection objects like stack, linked listThe collection objects like lists and
orvector but not primitive data types likedictionariescan store objects of
int, any type including
float, char etc., numbers and lists.
None data type: The none data type represents an object that does not contain
any value. In java language it is called “NULL” object. But in Python it is called
as “none”. In Python maximum of only one ‘none’object is provided. If no
value is passed to the function, then the default value will be taken as ‘none’.
Numeric data type
The numeric type represents numbers. There are 3 subtypes:
int
float
complex
SEQUENCES
A sequence represents a group of items or elements. There aresix types of
sequences in Python. Important sequences as follows,
str
list
tuple
str data type : The str represents string data type. A string is a collection of
character enclosed in single or double quotes. Both are valid.
E.g. str=”kvn” # str is name of string variable
str=’vedish’ # str is name of string variable
Triple double quote or triple single quotes are used to embed a string in a another
string (Nested string).
str=”””This is ‘str data type’ example”””
print(str) # output is : This is ‘str data type’
example
The [] operator used to retrieve specified character from the string. Thestring
th
index starts from 0. Hence, str[0] indicates the 0 character in the string.
e.g str=” SSCASC Tumkur”
print(str) # it display - SSCASC Tumkur
print(str[0]) # it display - G
OPERATORS
Operators are special symbols which represents computation. They are
applied on operand(s), which can be values or variables.
Same operator can behave differentlyon different data types. Operators
when applied on operands form an expression.
Operators are categorized as Arithmetic, Relational, Logical and
Assignment. Value and variables when used with operator are known as
operands.
1. Arithmetic Operators:
Symbol Description Example-1 Example-2
+ Addition >>> 5 + 6 >>>’SSCASCT’+’B
CA’
11
SSCASCTBCA
- Subtraction >>>10-5 >>>5 – 6
5 -1
* Multiplication >>> 5*630 >>>’SSCASCT’ * 2
SSCASCTSSCASCT
/ Division >>> 10 / 5 >>>5 /2.0
2 2.5
% Remainder / Modulo >>> 5 % 2 >>>15%5
1 0
** Exponentiation >>> 2**38 >>>2**8256
// Integer Division >>> 7.0 // 2 >>>3//21
3.0
2. Relational Operators:
3. Logical Operators:
Symbol Description Example-2
or If any one of the operand is true, then >>> 7<=10 or 7 ==10
condition becomes TRUE
True
and If both the operands are true, then the >>>7<10 and 7 >20
condition becomes TRUE
False
not Reverse the state of operand / condition >>> not 7<10False
4. Assignment Operator:
Symbol Description Example-1
= Assigned values from right side >>> x=10
operands
to left variable. 10
the left operand
Bitwise Operator: a bit is the smallest unit of data storage and it can have only
one of the two values, 0 and 1. Bitwise operators works on bits and perform bit-
by-bit operation.
If Statements
One-way if statement executes the statements if the condition is
true. The syntax fora one-way if statement is:
if boolean-expression:
Statement # Note that the statement(s) must be indented
The reserved word if begins a if statement.
The condition is a Boolean expression that determines whether or
not the body will beexecuted. A colon (:) must follow the condition.
The block is a block of one or more statements to be executed if the
condition is true.
The statements within the block must all be indented the same
number of spaces from the left. The block within an Example: To
demonstrate simple if
#Get two integers from the user
Dividend = int(input('Please enter the number to divide: '))
Divisor = int(input('Please enter dividend: ')) # If possible, divide them and report
the resultif divisor != 0:
Quotient = dividend/divisor
Print(dividend, '/', divisor, "=", quotient)print('Program finished')
Output
Please enter the number to divide: 4Please enter dividend: 5
4 / 5 = 0.8
Program finished
>>>
If-else statements
A two-way if-else statement decides which statements to execute based
on whetherthe condition is true or false.
The syntax for a two-way if-else statement:
if boolean-expression:
Statement(s) #for-the-true-case ,the statement(s) must be indented
Else: statement(s) #for-the-false-case
Example: to demonstrate if else
Percent=float(input("enter percentage"))if percent >= 90.0:
Print ("congratulations, you got an a") print ("you are doing well in this class")
Else:
Print ("you did not get an a")
Print ("see you in class next week")
Nested if statements.
A series of tests can written using nested if statements.
Example: Nestedif percent=float(input("Enter Percentage")) if (percent >=
90.00):
Print ('congratuations, you got an A')else:
If (percent >= 80.0): print ('you got a B')
Else:
If (percent >= 70.0): print ('you got a C')
Else:
Print ('your grade is less than a C')
If_elif_else Statement
In Python we can define a series of conditionals (multiple
alternatives) using if for the first one, elif for the rest, up until the final
(optional) else for anything not caught by the other conditionals.
Example:If_elif_else score=int(input("Enter Score"))if score >= 90.0:
grade = 'A' elif score >= 80.0:
grade = 'B' elif score >= 70.0:
grade = 'C' elif score >= 60.0:
grade = 'D'else:
grade = 'F' print("Grade=",grade)
Using else if instead of elif will trigger a syntax error and is not
allowed.
Loops
It is one of the most basic functions in programming; loops are
an important in every programming language. Loops enable is to
execute a statement repeatedly which are referred to as iterations. (A
loop is used to tell a program to execute statements repeatedly).
The simplest type of loop is a while loop.
The syntax for the while loop is:
while loop-continuation-condition:# Loop body
Statement(s)# Note that the statement(s) must be indented
i = initialValue # Initialize loop-control
variable
while i <
endValue:#
Loop body
ARRAYS
An array is a data structure that stores values of same data type.
In Python, this is the main difference between arrays and lists.
While python lists can contain values corresponding to different
data types, arrays in python can only contain values corresponding to
same data type.
To use arrays in python language, you need to import the standard
array module. This is because array is not a fundamental data type like
strings, integer etc. Here is how you can import array module in
python:
From array import *
Once you have imported the array module, you can declare an array.
Here is how you do it:
Array Identifier Name = array(type code, [Initializers])
Multi-Dimensional Array
An array containing more than one row and column is called
multidimensional array. It is also called combination of several 1D
arrays.2D array is also considered as matrix.
A=array([1,2,3,4])# create 1D array with 1 row B=array([1,2,3,4],[5,6,7,8])
create 2D array with 2 row
Example:2D_array
from numpy import* a=array([[1,2,3],[4,5,6],[7,8,9]])
print(a)#Prints 2D array as rows print("2D Array Element wise Printing")for i in
range(len(a)):
for j in range(len(a[i])):
print(a[i][j],end=' ')#Prints array element wiseprint(end='\n')
print(end='\n' )
#2D array As matrix by using matrix funprint("Matrix printing")
a=matrix('1 2 3; 4 5 6 ; 7 8 9')print(a)
Output
[[1 2 3]
[4 5 6]
[7 8 9]]
2D Array Element wise Printing1 2 3
456
789
Matrix printing[[1 2 3]
[4 5 6]
[7 8 9]]
>>>
Matrix in Numpy
In python we can show matrices as 2D array. In numpy, a matrix is
considered as specialized 2D array. It has lot of built in operators on 2D
matrices. In numpy, matrix is created using the following syntax.
Matrix_name=matrix(2D array or string)
Eg. a=matrix('1 2 3;4 5 6;7 8 8')
Matrix addition, multiplication and division.
We can use arithmetic operators like +, -,* ,/ to perform different
operations onmatrices.
Example: Matrix_Operation
from numpy import* a=matrix('4 4 4;4 4 4;4 4 4')
b=matrix('2 2 2;2 2 2;2 2 2')print("Printing A matrix") print(a)
print("Printing B matrix")print(b)
print("Printing Addition of two matrix")c=a+b #matrix addition
print(c)
print("Printing Multplication of two matrix")c=a*b #matrix addition
print(c)
print("Printing Division of two matrix")c=a/b #matrix addition
print(c)
Output
Printing A matrix[[4 4 4]
[4 4 4]
[4 4 4]]
Printing B matrix[[2 2 2]
[2 2 2]
[2 2 2]]
Printing Addition of two matrix
[[6 6 6]
[6 6 6]
[6 6 6]]
Printing Multplication of two matrix[[24 24 24]
[24 24 24]
[24 24 24]]
Printing Division of two matrix[[2. 2. 2.]
[2. 2. 2.]
[2. 2. 2.]]
>>>
Enter rows,col: 2 2
Enter matrix elements:1 2 3 4The original matrix
[[1 2]
[3 4]]
Printing Transpose of matrix[[1 3]
[2 4]]
>>>
UNIT-III
STRING AND CHARACTERS
Slicing String
Output:
String slicing
AST
SR
GITA
Python String Functions
The Python String Functions which we are going to discuss in this article are as
follows:
Capitalize( ) function
Lower( ) function
Title( ) function
Casefold( ) function
Upper( ) function
Count( ) function
Find( ) function
Replace( ) function
Swapcase( ) function
Join( ) function
FUNCTIONS
A function is a collection of statements grouped together that
performs an operation.
A function is a way of packaging a group of statements for later
execution.
The function is given a name. The name then becomes a short-
hand to describe the process. Once defined, the user can use it by
the name, and not by the steps involved. Once again, we have separated
the “what” from the“how”, i.e. abstraction.
Functions in any programming language can fall into two broad
categories:
Built-in functions
They are predefined and customized, by programming languages and
each serves aspecific purpose.
User-defined functions
They are defined by users as per their programming requirement.
There are two sides to every Python function:
Function definition. The definition of a function contains the code
that determines the function’s behaviour.
Function call. A function is used within a program via a function
invocation.
Defining a Function
A function definition consists of the function’s name, parameters,
and body.
The syntax for defining a function is as follows:
def function Name(list of parameters):
Statements # Note that the statement(s) must be indentedreturn
A function contains a header and body. The header begins with
the def keyword, followed by the function’s name known as the
identifier of the function and parameters, and ends with a colon.
The variables in the function header are known as formal
parameters or simply parameters. When a function is invoked,
you pass a value to the parameter. This value is referred to as
an actual parameter or argument. Parameters are optional; that is,
a function may not have any parameters.
Statement(s) – also known as the function body – are a nonempty
sequence of statements executed each time the function is called.
This means a function body cannot be empty, just like any indented
block.
Some functions return a value, while other functions perform
desired operations without returning a value. If a function returns
a value, it is called a value- returning function.
Calling a Function
Calling a function executes the code in the function. In a
function’s definition, you define what it is to do. To use a function, you
have to call or invoke it. The programthat calls the function is called a
caller. There are two ways to call a function, depending on whether or
not it returns a value. If the function returns a value, a call to that
function is usually treated as a value.
For example,
larger = max(3, 4)
Calls max(3, 4) and assigns the result of the function to the variable
larger.
Another example of a call that is treated as a value is
print(max(3, 4))
This prints the return value of the function call max (3, 4).
RECURSION
A recursive function is one that invokes itself. Or A recursive
function is afunction that calls itself in its definition.
For example the mathematical function, factorial, defined by factorial
(n) = n*(n-1)*(n-2)*...*3*2*1. can be programmed as
def factorial(n):
#n here should be an integer
if n == 0:return 1 else:
return n*factorial(n-1)
Any recursive function can be divided into two parts.
First, there must be one or more base cases, to solve the simplest
case, which is referred to as the base case or the stopping condition
Next, recursive cases, here function is called with different
arguments, which are referred to as a recursive call. These are values that
are handled by “reducing” the problem to a “simpler” problem of the
same form.
Example: To find factorial using Recursion
def main():
n=int(input("Enter a nonnegative integer: ")) print("Factorial of", n,
"is",factorial(n)) print(" 0! = ", factorial(0))
print(" 1! = ", factorial(1))
print(" 5! = ", factorial(6))
# Return the factorial for the specified numberdef factorial(n):
if n == 0: # Base casereturn 1
else:
return n*factorial(n-1) # Recursive callmain()# call the main
Output:
Enter a nonnegative integer: 5
Factorial of 5 is 120
0! = 1
1! = 1
5! = 720
Python Tuples
A collection of ordered and immutable objects is known as a tuple. Tuples
and lists are similar as they both are sequences. Though, tuples and lists are
different because we cannot modify tuples, although we can modify lists after
creating them, and also because we use parentheses to create tuples while we use
square brackets to create lists.
Placing different values separated by commas and enclosed in parentheses forms
a tuple. For instance,
Example
1. tuple_1 = ("Python", "tuples", "immutable", "object")
2. tuple_2 = (23, 42, 12, 53, 64)
3. tuple_3 = "Python", "Tuples", "Ordered", "Collection"
We represent an empty tuple by two parentheses enclosing nothing. Empty
tuple = ()
We need to add a comma after the element to create a tuple of a single element
Tuple_1 = (50,)
Tuple indices begin at 0, and similar to strings, we can slice them, concatenate
them, and perform other operations.
Creating a Tuple
All the objects (elements) must be enclosed in parenthesis (), each
separated by a comma, to form a tuple. Although using parenthesis is not required,
it is recommended to do so.
Whatever the number of objects, even of various data types, can be
included in a tuple (dictionary, string, float, list, etc.).
# Python program to show how to create a tuple
# Creating an empty tuple
empty_tuple = ()
print("Empty tuple: ", empty_tuple)
# Creating tuple having integers
int_tuple = (4, 6, 8, 10, 12, 14)
print("Tuple with integers: ", int_tuple)
# Creating a tuple having objects of different data types
mixed_tuple = (4, "Python", 9.3)
print("Tuple with different data types: ", mixed_tuple)
# Creating a nested tuple
nested_tuple = ("Python", {4: 5, 6: 2, 8:2}, (5, 3, 5, 6))
print("A nested tuple: ", nested_tuple)
Output:
Empty tuple: ()
Tuple with integers: (4, 6, 8, 10, 12, 14)
Tuple with different data types: (4, 'Python', 9.3)
A nested tuple: ('Python', {4: 5, 6: 2, 8: 2}, (5, 3, 5, 6))
Parentheses are not mandated to build tuples. Tuple packing is the term for this.
Tuple Operations
Like string, tuple objects are also a sequence. Hence, the operators used with
strings are also available for the tuple.
Operator Example
The + operator returns a tuple containing all the >>> t1=(1,2,3)
elements of the first and the second tuple object. >>> t2=(4,5,6)
>>> t1+t2
(1, 2, 3, 4, 5, 6)
>>> t2+(7,)
(4, 5, 6, 7)
The * operator Concatenates multiple copies of >>> t1=(1,2,3)
the same tuple. >>> t1*4
(1, 2, 3, 1, 2, 3,
1, 2, 3, 1, 2, 3)
The [] operator Returns the item at the given >>>
t1=(1,2,3,4,5,6)
index. A negative index counts the position from
>>> t1[3]
the right side.
4
>>> t1[-2]
5
Operator Example
The [:] operator returns the items in the range >>>
t1=(1,2,3,4,5,6)
specified by two index operands separated
>>> t1[1:3]
by the : symbol. If the first operand is omitted,
(2, 3)
the range starts from zero. If the second
>>> t1[3:]
operand is omitted, the range goes up to
(4, 5, 6)
the end of the tuple.
>>> t1[:3]
(1, 2, 3)
The in operator returns true if an item exists in the given tuple. >>>
t1=(1,2,3,4,5,6)
>>> 5 in t1
True
>>> 10 in t1
False
The not in operator returns true if an item does not exist in the >>>
given tuple. t1=(1,2,3,4,5,6)
>>> 4 not in t1
False
>>> 10 not in t1
True
UNIT-IV
DICTIONARIES:
Method Description
Page 35 of 52
Return a new view of the dictionary's items(key,
value).
Items()
Keys() Return a new view of the dictionary's keys.
Remove the item with key and return its valueor d
if key is not found. If d is not provided and key is
not found, raises KeyError.
Pop(key[,d])
Remove and return an arbitary item (key, value).
Raises KeyError if the dictionary isempty.
Popitem()
If key is in the dictionary, return its value. Ifnot,
insert key with a value of d and
return d (defaults to None).
Setdefault(key[,d])
Update the dictionary with the key/value pairsfrom
other, overwriting existing keys.
Update([other])
Values() Return a new view of the dictionary's values
Copy() Return a shallow copy of the dictionary.
Page 36 of 52
Remove the item with key and return its valueor d
if key is not found. If d is not provided and key is
not found, raises KeyError.
Pop(key[,d])
Popitem()
Example:
Page 37 of 52
# Python program to demonstrate
# passing dictionary as argument #
A function that takes dictionary #
as an argument
def func(d):
for key in d:
print("key:", key, "Value:", d[key])
# Driver's code
D = {'a':1, 'b':2, 'c':3}
func(D)
Output:
key: b Value: 2
key: a Value: 1
key: c Value: 3
Page 38 of 52
def main():
# passing dictionary key-value
# pair as arguments
display(fname ="John",
mname ="F.",
lname ="Kennedy")
# Driver's code
main()
Output:
John F. Kennedy
Errors and Exceptions:
Python Errors and Built-in Exceptions: Python (interpreter) raises exceptions
when it encounters errors. When writing a program, we, more often than not,
willencounter errors. Error caused by not following the proper structure (syntax)
of the languageis called syntax error or parsing error
Zero Division Error:
Zero Division Error in Python indicates that the second argument used in a
division (or modulo) operation was zero.
Overflow Error:
Overflow Error in Python indicates that an arithmetic operation has
exceeded the limits ofthe current Python runtime. This is typically due to
excessively large float values, as integer values that are too big will opt to raise
memory errors instead.
Import Error:
It is raised when you try to import a module which does not exist. This may
happen if you made a typing mistake in the module name or the module doesn't
exist in its standard path. In the example below, a module named
"non_existing_module" is being imported but it doesn't exist, hence an import
error exception is raised.
Index Error:
Page 39 of 52
An Index Error exception is raised when you refer a sequence which is out
of range. In the example below, the list abc contains only 3 entries, but the 4th
index is being accessed,which will result an Index Error exception.
Type Error:
When two unrelated type of objects are combined, Type Error exception is
raised. In example below, an int and a string is added, which will result in Type
Error exception.
Indentation Error:
Unexpected indent. As mentioned in the "expected an indented block"
section, Python not only insists on indentation, it insists on consistent indentation.
You are free to choose the number of spaces of indentation to use, but you then
need to stick with it.
Syntax errors:
These are the most basic type of error. They arise when the Python parser
is unable to understand a line of code. Syntax errors are almost always fatal, i.e.
there is almost never a way to successfully execute a piece of code containing
syntax errors.
Run-time error:
A run-time error happens when Python understands what you are saying,
but runs into trouble when following your instructions.
Key Error:
Python raises a KeyError whenever a dict() object is requested (using the
format a = adict[key]) and the key is not in the dictionary.
Value Error:
In Python, a value is the information that is stored within a certain object.
To encounter a ValueError in Python means that is a problem with the content of
the object you tried to assign the value to.
Python has many built-in exceptions
Which forces your program to output an error when something in it goes
wrong. In Python, users can define such exceptions by creating a new class. This
exception class has to be derived, either directly or indirectly, from Exception
class.
Different types of exceptions:
Array Index Out Of Bound Exception.
Page 40 of 52
Class Not Found Exception.
File Not Found Exception.
IO Exception.
Interrupted Exception.
No Such Field Exception.
No Such Method Exception
Handling Exceptions:
The cause of an exception is often external to the program itself. For
example, an incorrect input, a malfunctioning IO device etc. Because the program
abruptly terminates on encountering an exception, it may cause damage to system
resources, such as files. Hence, the exceptions should be properly handled so that
an abrupt termination of the program is prevented.
Python uses try and except keywords to handle exceptions. Both keywords are
followed by indented blocks.
Syntax:
try:
#statements in try blockexcept :
#executed when error in try blockTypically we see, most of the times
Syntactical errors (wrong spelling, colon ( : ) missing ….), At developer
level and compile level it gives errors.
Logical errors (2+2=4, instead if we get output as 3 i.e., wrong output
…..,),
As a developer we test the application, during that time logical error may
obtained.
Run time error (In this case, if the user doesn’t know to give input, 5/6 is ok but
ifthe user say 6 and 0 i.e.,6/0 (shows error a number cannot be divided by zero))
This is not easy compared to the above two errors because it is not done by
thesystem, it is (mistake) done by the user.
The things we need to observe are:
You should be able to understand the mistakes; the error might be done by
user, DB connection or server.
Page 41 of 52
Whenever there is an error execution should not stop. Ex: Banking
Transaction
The aim is execution should not stop even though an error occur
FILES
A file is some information or data which stays in the computer storage
devices. Python givesyou easy ways to manipulate these files. Generally files
divide in two categories, text file and binary file. Text files are simple text where
as the binary files contain binarydata which is only readable by computer.
Text files: In this type of file, Each line of text is terminated with a special
character called EOL (End of Line), which is the new line character (‘\n’) in
python by default.
Binary files: In this type of file, there is no terminator for a line and the data is
stored after converting it into machine understandable binary language.
Text files:
We can create the text files by using the syntax:
Variable name=open (“file.txt”, file mode)For ex: f= open ("hello.txt","w+")
We declared the variable f to open a file named hello.txt. Open takes 2
arguments, thefile that we want to open and a string that represents the
kinds of permission or operation we want to do on the file
Here we used "w" letter in our argument, which indicates write and the plus
sign that means it will create a file if it does not exist in library
The available option beside "w" are "r" for read and "a" for append and
plus signmeans if it is not there then create it
Page 42 of 52
'r' This is the default mode. It Opens file for reading.
'w' This Mode Opens file for writing.
If file does not exist, it creates a new file.If file exists it truncates
the file.
'x' Creates a new file. If file already exists, the operation fails.
'a' Open file in append mode.
If file does not exist, it creates a new file.
't' This is the default mode. It opens in text mode.
'b' This opens in binary mode.
'+' This will open a file for reading and writing (updating)
Page 43 of 52
A Python program to unzip the contents of the files that are available in a
zip file
#to view contents of zipped files
from zipfile import *
#Open the zip file
z = ZipFile('test.zip', 'r')
#extract all the file names which are in the zip file
z.extractall()
Page 44 of 52
UNIT-V
CONSTRUCTOR
Page 45 of 52
student.show()
Output:
This is parametrized constructor
Hello John
INHERITANCE
Types of Inheritance in Python Programming
Types of inheritance: There are five types of inheritance in python programming:
Single inheritance
Multiple inheritances
Multilevel inheritance
Hierarchical inheritance
Hybrid inheritance
i. Single inheritance
When child class is derived from only one parent class. This is called single
inheritance. The example we did above is the best example for single
inheritance in python programming.
ii. Multiple Inheritance
When child class is derived or inherited from more than one parent class. This
is called multiple inheritance. In multiple inheritance, we have two parent
classes/base classes and one child class that inherits both parent classes
properties.
iii. Multilevel Inheritance:
In multilevel inheritance, we have one parent class and child class that is
derived or inherited from that parent class. We have a grand-child class that
is derived from the child class. See the below-given flow diagram to
understand more clearly.
iv. Hierarchical inheritance
When we derive or inherit more than one child class from one(same) parent
class. Then this type of inheritance is called hierarchical inheritance.
v. Hybrid Inheritance
Page 46 of 52
Hybrid inheritance satisfies more than one form of inheritance ie. It may be
consists of all types of inheritance that we have done above. It is not wrong
if we say Hybrid Inheritance is the combinations of simple, multiple,
multilevel and hierarchical inheritance. This type of inheritance is very
helpful if we want to use concepts of inheritance without any limitations
according to our requirements.
POLYMORPHISM
DUCK TYPING PHILOSOPHY OF PYTHON
Duck Typing is a type system used in dynamic languages. For example, Python,
Perl, Ruby, PHP, Javascript, etc. where the type or the class of an object is less
important than the method it defines. Using Duck Typing, we do not check types
at all. Instead, we check for the presence of a given method or attribute.
The name Duck Typing comes from the phrase:
“If it looks like a duck and quacks like a duck, it’s a duck”
Example:
# Python program to demonstrate
# duck typing
class Specialstring:
def len (self):
return 21
# Driver's code
if name == " main ":
string = Specialstring()
print(len(string))
Output:
In this case, we call method len() gives the return value from
len method. Here len method defines the property of the class Special
string The object’s type itself is not significant in this we do not declare the
argument in method prototypes. This means that compilers can not do type-
checking. Therefore, what really matters is if the object has particular attributes
at run time. Duck typing is hence implemented by dynamic languages.
Page 47 of 52
But now some of the static languages like Haskell also supports it. But, Java/C#
doesn’t have this ability yet.
Example: Now, lets look demonstrates how an object be used in any other
circumstances until it is not supported.
Output:
fly with wings
fly with fuel
Traceback (most recent call last):
File "/home/854855e5570b9ce4a9e984209b6a1c21.py", line 20, in
obj.fly()
AttributeError: 'Fish' object has no attribute 'fly'
In this example, we can see a class supports some method we can modify it or
give them new functionality. Duck-typing emphasis what the object can really
do, rather than what the object is.
Page 48 of 52
OPERATOR OVERLOADING
Operators work for user-defined types.
For example, the + operator will perform arithmetic addition on two numbers,
merge two lists, or concatenate two strings.
This feature in Python that allows the same operator to have different meaning
according to the context is called operator overloading.
obj1 = Complex(1, 2)
obj2 = Complex(3, 4)
obj3 = obj1 + obj2
print(obj3)
# Output: (4, 6)
In the above example, we have used the + operator to add
two Complex objects a and b together.
Page 49 of 52
The add () method overloads the + operator to add the real and imaginary
parts of the two complex numbers together and returns a new Complex object
with the resulting values.
The str () method returns a string representation of the complex number in
the form a + bj.
p1 = Person("Alice", 20)
p2 = Person("Bob", 30)
True
False
Page 50 of 52
Here, lt () overloads the < operator to compare the age attribute of two
objects.
The lt () method returns,
True - if the first object's age is less than the second object's age
False - if the first object's age is greater than the second object's age We
can define similar methods to overload the other comparison operators. For
example, gt () to overload > operator, eq () to
overload == operator and so on.
Function Description
Page 51 of 52
Advantages of Operator Overloading
Improves code readability by allowing the use of familiar operators.
Ensures that objects of a class behave consistently with built-in types and
other user-defined types.
Makes it simpler to write code, especially for complex data types.
Allows for code reuse by implementing one operator method and using it
for other operators.
METHOD OVERRIDING
Method Overriding in Python is an OOPs concept closely related to
inheritance. When a child class method overrides (or, provides it's own
implementation) the parent class method of the same name, parameters and return
type, it is known as method overriding.
In this case, the child class's method is called the overriding method and
the parent class's method is called the overridden method.
Method overriding is completely different from the concept of method
overloading. Method overloading occurs when there are two functions with the
same name but different parameters. And, method overloading is not directly
supported in Python.
Parent class: The class being inherited is called the Parent or Superclass.
Child class: The class that inherits the properties and methods of the parent class
is called the Child or Subclass.
Key features of Method Overriding in Python
These are some of the key features and advantages of method overriding in
Python --
Method Overriding is derived from the concept of object oriented
programming
Method Overriding allows us to change the implementation of a function
in the child class which is defined in the parent class.
Method Overriding is a part of the inheritance mechanism
Method Overriding avoids duplication of code
Page 52 of 52
Method Overriding also enhances the code adding some additional
properties.
Prerequisites for method overriding
There are certain prerequisites for method overriding in Python. They're
discussed below --
Method overriding cannot be done within a class. So,we need to derive a
child class from a parent class. Hence Inheritance is mandatory.
The method must have the same name as in the parent class
The method must have the same number of parameters as in the parent
class.
Page 53 of 52