0% found this document useful (0 votes)
2 views127 pages

VAC Python Notes

The document outlines a Value Added Course on Python at Geethanjali College of Engineering and Technology, detailing course objectives, outcomes, and a structured curriculum covering core programming concepts, data types, control structures, functions, and object-oriented programming. It includes practical exercises and examples for hands-on learning, along with references to textbooks and additional resources. The document also provides an introduction to Python, its syntax, variable handling, and installation instructions.

Uploaded by

shravanichanikya
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views127 pages

VAC Python Notes

The document outlines a Value Added Course on Python at Geethanjali College of Engineering and Technology, detailing course objectives, outcomes, and a structured curriculum covering core programming concepts, data types, control structures, functions, and object-oriented programming. It includes practical exercises and examples for hands-on learning, along with references to textbooks and additional resources. The document also provides an introduction to Python, its syntax, variable handling, and installation instructions.

Uploaded by

shravanichanikya
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

PYTHON PROGRAMMING

[Link]
Sr. Assistant Professor
CS Dept
Geethanjali College of Engineering and
Technology
Hyderabad
Geethanjali College of Engineering and Technology

Geethanjali College of Engineering and Technology


(UGC AUTONOMOUS INSTITUTION)
(Accredited by NBA and NAAC with ‘A+’ grade, Approved by AICTE New Delhi and Affiliated to JNTUH)
Cheeryal (V), Keesara (M), Medchal (Dist), Telangana – 501 301.
Department of Cyber Security
Value Added Course on Python (2024-25)
Course Objectives:
 To be able to introduce core programming basics and program design with
functions using Python programming language.
 To understand a range of Object-Oriented Programming
 To understand the high-performance programs designed to strengthen the practical
expertise.

Course Outcomes:
 Ability to explore python basic concepts
 Ability to create practical and contemporary applications

UNIT – I
Introduction to Python, Installing Python. How a Program Works, Using Python, Program
Development Cycle, Input, Processing, and Output, Displaying Output with the Print
Function, Comments, Variables, Reading Input from the Keyboard, Performing
Calculations, Operators. Type conversions, Expressions.
Data types and Expressions: Strings, Assignment and Comments, Numeric Data Types
and Character Sets, Expressions, Functions and Modules.
Decision Structures and Boolean Logic: if, if-else, if-elif-else Statements, Nested Decision
Structures, Comparing Strings, Logical Operators, Boolean Variables.
UNIT - II
Repetition Structures: Introduction, while loop, for loop, Calculating a Running Total,
Input Validation Loops, Nested Loops.
Control Statements: Definite Iteration, Formatting Text for Output, Selection,
Conditional Iteration.
File and Exceptions: Introduction to File Input and Output, Using Loops to Process Files,
Processing Records Exceptions.
UNIT - III
Functions: Introduction, Defining and Calling a Void Function, Designing a Program to
Use Functions, Local Variables, Passing Arguments to Functions, Global Variables and
Global Constants, Value-Returning Functions-Generating Random Numbers, The math
Module, Storing Functions in Modules.
Recursion: Introduction, Problem Solving with Recursion, Examples of Recursive
Algorithms.

D. Subhashini, Sr. Assist Prof CS dept


Geethanjali College of Engineering and Technology

Strings and Text Files: Accessing Characters and Substrings in a String, Strings and
Number System, String Methods, Basic String Operations, String Slicing, Testing,
Searching, and Manipulating Strings.
UNIT - IV
Lists, Introduction to Lists, List slicing, Finding Items in Lists with the in Operator, List
Methods and Useful Built-in Functions, Copying Lists, Processing Lists, Two-Dimensional
Lists.
Tuples Sequences, Tuples Methods and Useful Built-in Functions.
Dictionaries and Sets: Dictionaries, Sets, Methods and Useful Built-in Functions.
Serializing Objects.
UNIT - V
Design with Classes: Classes and Objects, Classes and Functions, Classes and Methods,
Working with Instances, Inheritance and Polymorphism. Object-Oriented Programming:
Procedural and Object-Oriented Programming, Classes, techniques for Designing
Classes.
Multithreaded Programming: Introduction, Threads and Processes, Python Threads,
Thread Module, Threading Module.

TEXT BOOKS:
1. Kenneth A. Lambert, The Fundamentals of Python: First Programs, 2011, Cengage
Learning.
2. Think Python First Edition, by Allen B. Downey, Orielly publishing

REFERENCE BOOKS:
1. Introduction to Computation and Programming Using Python. John V. Guttag, The MIT
Press.
2. James Payne, Beginning Python using Python 2.6 and Python 3, Wrox publishing

List of Python programs for practice:


1. Start a Python interpreter and use it as a Calculator.
2. Write a program to calculate compound interest when principal, rate and number of
periods are given.
3. Given coordinates (x1, y1), (x2, y2) find the distance between two points
4. Read name, address, email and phone number of a person through keyboard and
print the details.
5. Print the below triangle using for loop.
5
44
333
2222
11111
6. Write a program to check whether the given input is digit or lowercase character or
uppercase character or a special character (use 'if-else-if' ladder)
7. Python Program to Print the Fibonacci sequence using while loop
8. Python program to print all prime numbers in a given interval (use break)

D. Subhashini, Sr. Assist Prof CS dept


Geethanjali College of Engineering and Technology

9. Write a program to convert a list and tuple into arrays.


10. Write a program to find common values between two arrays.
11. Write a function called gcd that takes parameters a and b and returns their
greatest common divisor.
12. Write a function called palindrome that takes a string argument and returns True if
it is a palindrome and False otherwise. Remember that you can use the built-in function
len to check the length of a string.
13. Write a function called is_sorted that takes a list as a parameter and returns True if
the list is sorted in ascending order and False otherwise.
14. Write a function called has_duplicates that takes a list and returns True if there is
any element that appears more than once. It should not modify the original list.
15. Write a function called remove_duplicates that takes a list and returns a new list
with only the unique elements from the original. Hint: they don’t have to be in the same
order.
16. Write a python code to read dictionary values from the user. Construct a function
to invert its content. i.e., keys should be values and values should be keys.
17. Write a python program that defines a matrix and prints
18. Write a python program to perform addition of two square matrices
19. Write a python program to perform multiplication of two square matrices 2.
20. How do you make a module? Give an example of construction of a module using
different geometrical shapes and operations on them as its functions.

D. Subhashini, Sr. Assist Prof CS dept


Geethanjali College of Engineering and Technology

Python Introduction
What is Python?
Python is a popular programming language. It was created by Guido van
Rossum, and released in 1991.

It is used for:

 web development (server-side)


 software development
 mathematics
 system scripting

What can Python do?


 Python can be used on a server to create web applications.
 Python can be used alongside software to create workflows.
 Python can connect to database systems. It can also read and modify
files.
 Python can be used to handle big data and perform complex
mathematics.
 Python can be used for rapid prototyping, or for production-ready
software development.

Why Python?
 Python works on different platforms (Windows, Mac, Linux, Raspberry Pi,
etc).
 Python has a simple syntax similar to the English language.
 Python has syntax that allows developers to write programs with fewer
lines than some other programming languages.
 Python runs on an interpreter system, meaning that code can be
executed as soon as it is written. This means that prototyping can be very
quick.
 Python can be treated in a procedural way, an object-orientated way or a
functional way.

D. Subhashini, Sr. Assist Prof CS dept


Geethanjali College of Engineering and Technology

Good to know
 The most recent major version of Python is Python 3. However, Python 2,
although not being updated with anything other than security updates, is
still quite popular.
 It is possible to write Python in a text editor, using an Integrated
Development Environment, such as Thonny, Pycharm, Netbeans or
Eclipse which are particularly useful when managing larger collections of
Python files.

Python Syntax compared to other


programming languages
 Python was designed for readability, and has some similarities to the
English language with influence from mathematics.
 Python uses new lines to complete a command, as opposed to other
programming languages which often use semicolons or parentheses.
 Python relies on indentation, using whitespace, to define scope; such as
the scope of loops, functions and classes. Other programming languages
often use curly-brackets for this purpose.

Python Install

You can download it for free from the following


website: [Link]

Python Quickstart
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 executed.

D. Subhashini, Sr. Assist Prof CS dept


Geethanjali College of Engineering and Technology

The way to run a python file is like this on the command line:

C:\Users\Your Name>python [Link]

Where "[Link]" is the name of your python file.

Let's write our first Python file, called [Link], which can be done in any
text editor.

[Link]

print("Hello, World!")

Simple as that. Save your file. Open your command line, navigate to the
directory where you saved your file, and run:

C:\Users\Your Name>python [Link]

The output should read:

Hello, World!

The Python Command Line


To test a short amount of code in python sometimes it is quickest and easiest
not to write the code in a file. This is made possible because Python can be run
as a command line itself.

Type the following on the Windows, Mac or Linux command line:

C:\Users\Your Name>python

Or, if the "python" command did not work, you can try "py":
C:\Users\Your Name>py

From there you can write any python, including our hello world example from
earlier in the tutorial:

D. Subhashini, Sr. Assist Prof CS dept


Geethanjali College of Engineering and Technology

C:\Users\Your Name>python
Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print("Hello, World!")

Which will write "Hello, World!" in the command line:

C:\Users\Your Name>python
Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print("Hello, World!")
Hello, World!

Whenever you are done in the python command line, you can simply type the
following to quit the python command line interface:

exit()

Python Syntax
Execute Python Syntax
Python syntax can be executed by writing directly in the Command Line:

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


Hello, World!

Or by creating a python file on the server, using the .py file extension, and
running it in the Command Line:

C:\Users\Your Name>python [Link]

D. Subhashini, Sr. Assist Prof CS dept


Geethanjali College of Engineering and Technology

Indentation
Indentation refers to the spaces at the beginning of a code line.

Where in other programming languages the indentation in code is for readability


only, the indentation in Python is very important.

Python uses indentation to indicate a block of code.

Example
if 5 > 2:
print("Five is greater than two!")

Python will give you an error if you skip the indentation:

Example
Syntax Error:

if 5 > 2:
print("Five is greater than two!")

The number of spaces is up to you as a programmer, but it has to be at least


one.

Example
if 5 > 2:
print("Five is greater than two!")
if 5 > 2:
print("Five is greater than two!")

You have to use the same number of spaces in the same block of code,
otherwise Python will give you an error:

D. Subhashini, Sr. Assist Prof CS dept


Geethanjali College of Engineering and Technology

Example
Syntax Error:

if 5 > 2:
print("Five is greater than two!")
print("Five is greater than two!")

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

Example
Variables in Python:

x = 5
y = "Hello, World!"

Python has no command for declaring a variable.

Comments
Python has commenting capability for the purpose of in-code documentation.

Comments start with a #, and Python will render the rest of the line as a
comment:

Example
Comments in Python:

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

D. Subhashini, Sr. Assist Prof CS dept


Geethanjali College of Engineering and Technology

Exercise:
Insert the missing part of the code below to output "Hello World".

("Hello World")

D. Subhashini, Sr. Assist Prof CS dept


Geethanjali College of Engineering and Technology

Variables
Creating Variables
Variables are containers for storing data values.

Unlike other programming languages, Python has no command for declaring a


variable.

A variable is created the moment you first assign a value to it.

Example
x = 5
y = "John"
print(x)
print(y)

Variables do not need to be declared with any particular type and can even
change type after they have been set.

Example
x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)

String variables can be declared either by using single or double quotes:

Example
x = "John"
# is the same as
x = 'John'

D. Subhashini, Sr. Assist Prof CS dept


Geethanjali College of Engineering and Technology

Variable Names
A variable can have a short name (like x and y) or a more descriptive name
(age, carname, total_volume).

Rules for Python variables:

 A variable name must start with a letter or the underscore character


 A variable name cannot start with a number
 A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ )
 Variable names are case-sensitive (age, Age and AGE are three different
variables)

Example
#Legal variable names:
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"

#Illegal variable names:


2myvar = "John"
my-var = "John"
my var = "John"

Remember that variable names are case-sensitive

Assign Value to Multiple Variables


Python allows you to assign values to multiple variables in one line:

Example
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)

D. Subhashini, Sr. Assist Prof CS dept


Geethanjali College of Engineering and Technology

And you can assign the same value to multiple variables in one line:

Example
x = y = z = "Orange"
print(x)
print(y)
print(z)

Output Variables
The Python print statement is often used to output variables.

To combine both text and a variable, Python uses the + character:

Example
x = "awesome"
print("Python is " + x)

You can also use the + character to add a variable to another variable:

Example
x = "Python is "
y = "awesome"
z = x + y
print(z)

For numbers, the + character works as a mathematical operator:

Example
x = 5
y = 10
print(x + y)

If you try to combine a string and a number, Python will give you an error:

D. Subhashini, Sr. Assist Prof CS dept


Geethanjali College of Engineering and Technology

Example
x = 5
y = "John"
print(x + y)

Global Variables
Variables that are created outside of a function (as in all of the examples above)
are known as global variables.

Global variables can be used by everyone, both inside of functions and outside.

Example Create a variable outside of a function, and use it inside the


function
x = "awesome"

def myfunc():
print("Python is " + x)

myfunc()

If you create a variable with the same name inside a function, this variable will
be local, and can only be used inside the function. The global variable with the
same name will remain as it was, global and with the original value.

Example Create a variable inside a function, with the same name as the
global variable
x = "awesome"

def myfunc():
x = "fantastic"
print("Python is " + x)

myfunc()
print("Python is " + x)

D. Subhashini, Sr. Assist Prof CS dept


Geethanjali College of Engineering and Technology

The global Keyword


Normally, when you create a variable inside a function, that variable is local,
and can only be used inside that function.

To create a global variable inside a function, you can use the global keyword.

Example If you use the global keyword, the variable belongs to the global
scope:
def myfunc():
global x
x = "fantastic"

myfunc()

print("Python is " + x)

Also, use the global keyword if you want to change a global variable inside a
function.

Example
To change the value of a global variable inside a function, refer to the variable
by using the global keyword:

x = "awesome"

def myfunc():
global x
x = "fantastic"

myfunc()

print("Python is " + x)

D. Subhashini, Sr. Assist Prof CS dept


Geethanjali College of Engineering and Technology

Data Types
Built-in Data Types
In programming, data type is an important concept.

Variables can store data of different types, and different types can do different
things.

Python has the following data types built-in by default, in these categories:

Text Type: Str

Numeric Types: int, float, complex

Sequence Types: list, tuple, range

Mapping Type: Dict

Set Types: set, frozenset

Boolean Type: Bool

Binary Types: bytes, bytearray, memoryview

Getting the Data Type


You can get the data type of any object by using the type() function:

Example
Print the data type of the variable x:

x = 5
print(type(x))

D. Subhashini, Sr. Assist Prof CS dept


Geethanjali College of Engineering and Technology

Setting the Data Type


In Python, the data type is set when you assign a value to a variable:

Example Data Type

x = "Hello World" Str

x = 20 Int

x = 20.5 Float

x = 1j Complex

x = ["apple", "banana", "cherry"] List

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

x = range(6) Range

x = {"name" : "John", "age" : 36} Dict

x = {"apple", "banana", "cherry"} Set

x = frozenset({"apple", "banana", "cherry"}) Frozenset

x = True Bool

x = b"Hello" Bytes

x = bytearray(5) Bytearray

x = memoryview(bytes(5)) Memoryview

D. Subhashini, Sr. Assist Prof CS dept


Geethanjali College of Engineering and Technology

Setting the Specific Data Type


If you want to specify the data type, you can use the following constructor
functions:

Example Data Type

x = str("Hello World") str

x = int(20) int

x = float(20.5) float

x = complex(1j) complex

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

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

x = range(6) range

x = dict(name="John", age=36) dict

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

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

x = bool(5) bool

x = bytes(5) bytes

x = bytearray(5) bytearray

x = memoryview(bytes(5)) memoryview

Exercise: print the data type of x, what data type would that be?
x = 5
print(type(x))

D. Subhashini, Sr. Assist Prof CS dept


Geethanjali College of Engineering and Technology

Numbers
There are three numeric types in Python:

 int
 float
 complex

Variables of numeric types are created when you assign a value to them:

Example
x = 1 # int
y = 2.8 # float
z = 1j # complex

To verify the type of any object in Python, use the type() function:

Example
print(type(x))
print(type(y))
print(type(z))

Int
Int, or integer, is a whole number, positive or negative, without decimals, of
unlimited length.

Example Integers:
x = 1
y = 35656222554887711
z = -3255522

print(type(x))
print(type(y))
print(type(z))

D. Subhashini, Sr. Assist Prof CS dept


Geethanjali College of Engineering and Technology

Float
Float, or "floating point number" is a number, positive or negative, containing
one or more decimals.

Example Floats:
x = 1.10
y = 1.0
z = -35.59

print(type(x))
print(type(y))
print(type(z))

Float can also be scientific numbers with an "e" to indicate the power of 10.

Example Floats:
x = 35e3
y = 12E4
z = -87.7e100

print(type(x))
print(type(y))
print(type(z))

Complex
Complex numbers are written with a "j" as the imaginary part:

Example Complex:
x = 3+5j
y = 5j
z = -5j

print(type(x))

D. Subhashini, Sr. Assist Prof CS dept


Geethanjali College of Engineering and Technology

print(type(y))
print(type(z))

Type Conversion
You can convert from one type to another with the int(), float(),
and complex() methods:

Example Convert from one type to another:


x = 1 # int
y = 2.8 # float
z = 1j # complex

#convert from int to float:


a = float(x)

#convert from float to int:


b = int(y)

#convert from int to complex:


c = complex(x)

print(a)
print(b)
print(c)

print(type(a))
print(type(b))
print(type(c))

Note: You cannot convert complex numbers into another number type.

D. Subhashini, Sr. Assist Prof CS dept


Geethanjali College of Engineering and Technology

Random Number
Python does not have a random() function to make a random number, but Python
has a built-in module called random that can be used to make random numbers:

Example Import the random module, and display a random number


between 1 and 9:
import random

print([Link](1, 10))

Exercise:
Insert the correct syntax to convert x into a decimal number.

x = 5
x = (x)

D. Subhashini, Sr. Assist Prof CS dept


Geethanjali College of Engineering and Technology

Casting
Specify a Variable Type
There may be times when you want to specify a type on to a variable. This can
be done with casting. Python is an object-orientated language, and as such it
uses classes to define data types, including its primitive types.

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

Example Integers:
x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3

Example 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

Example Strings:
x = str("s1") # x will be 's1'
y = str(2) # y will be '2'
z = str(3.0) # z will be '3.0'

D. Subhashini, Sr. Assist Prof CS dept


Geethanjali College of Engineering and Technology

Strings
String Literals
String literals in python are surrounded by either single quotation marks, or
double quotation marks.

'hello' is the same as "hello".

You can display a string literal with the print() function:

Example
print("Hello")
print('Hello')

Assign String to a Variable


Assigning a string to a variable is done with the variable name followed by an
equal sign and the string:

Example
a = "Hello"
print(a)

D. Subhashini, Sr. Assist Prof CS dept


Geethanjali College of Engineering and Technology

Multiline Strings
You can assign a multiline string to a variable by using three quotes:

Example You can use three double quotes

a = """Lorem ipsum dolor sit amet,


consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)

Example Or three single quotes:


a = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''
print(a)

in the output, the line breaks are inserted at the same position as in the code.

Strings are Arrays


Like many other popular programming languages, strings in Python are arrays
of bytes representing unicode characters.

However, Python does not have a character data type, a single character is
simply a string with a length of 1.

Square brackets can be used to access elements of the string.

Example Get the character at position 1 (remember that the first


character has the position 0):
a = "Hello, World!"
print(a[1])

Slicing
You can return a range of characters by using the slice syntax.

D. Subhashini, Sr. Assist Prof CS dept


Geethanjali College of Engineering and Technology

Specify the start index and the end index, separated by a colon, to return a part
of the string.

Example
Get the characters from position 2 to position 5 (not included):

b = "Hello, World!"
print(b[2:5])

Negative Indexing
Use negative indexes to start the slice from the end of the string:

Example Get the characters from position 5 to position 1 (not


included), starting the count from the end of the string:
b = "Hello, World!"
print(b[-5:-2])

String Length
To get the length of a string, use the len() function.

Example The len() function returns the length of a string:


a = "Hello, World!"
print(len(a))

String Methods
Python has a set of built-in methods that you can use on strings.

Example The strip() method removes any whitespace from the


beginning or the end:
a = " Hello, World! "
print([Link]()) # returns "Hello, World!"
D. Subhashini, Sr. Assist Prof CS dept
Geethanjali College of Engineering and Technology

Example The lower() method returns the string in lower case:


a = "Hello, World!"
print([Link]())

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

a = "Hello, World!"
print([Link]())

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


a = "Hello, World!"
print([Link]("H", "F"))

Example The split() method splits the string into substrings if it finds
instances of the separator:
a = "Hello, World!"
print([Link](",")) # returns ['Hello', ' World!']

Check String
To check if a certain phrase or character is present in a string, we can use the
keywords in or not in.

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


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

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

D. Subhashini, Sr. Assist Prof CS dept


Geethanjali College of Engineering and Technology

String Concatenation
To concatenate, or combine, two strings you can use the + operator.

Example Merge variable a with variable b into variable c:


a = "Hello"
b = "World"
c = a + b
print(c)

Example To add a space between them, add a " ":


a = "Hello"
b = "World"
c = a + " " + b
print(c)

String Format
As we learned in the Python Variables chapter, we cannot combine strings and
numbers like this:

Example
age = 36
txt = "My name is John, I am " + age
print(txt)

But we can combine strings and numbers by using the format() method!

The format() method takes the passed arguments, formats them, and places
them in the string where the placeholders {} are:

Example Use the format() method to insert numbers into strings:


age = 36
txt = "My name is John, and I am {}"
print([Link](age))

D. Subhashini, Sr. Assist Prof CS dept


Geethanjali College of Engineering and Technology

The format() method takes unlimited number of arguments, and are placed into
the respective placeholders:

Example
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print([Link](quantity, itemno, price))

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([Link](quantity, itemno, price))

Escape Character
To insert characters that are illegal in a string, use an escape character.

An escape character is a backslash \ followed by the character you want to


insert. An example of an illegal character is a double quote inside a string that
is surrounded by double quotes:

Example You will get an error if you use double quotes inside a
string that is surrounded by double quotes:
txt = "We are the so-called "Vikings" from the north."

To fix this problem, use the escape character \":

Example The escape character allows you to use double quotes


when you normally would not be allowed:

D. Subhashini, Sr. Assist Prof CS dept


Geethanjali College of Engineering and Technology

txt = "We are the so-called \"Vikings\" from the north."

Other escape characters used in Python:

Code Result

\' Single Quote

\\ Backslash

\n New Line

\r Carriage Return

\t Tab

\b Backspace

\f Form Feed

\ooo Octal value

\xhh Hex value

String Methods
Python has a set of built-in methods that you can use on strings.

All string methods returns new values. They do not change the original string.

Method Description

capitalize() Converts the first character to upper case

casefold() Converts string into lower case

center() Returns a centered string

count() Returns the number of times a specified value occurs in a


string

encode() Returns an encoded version of the string

D. Subhashini, Sr. Assist Prof CS dept


Geethanjali College of Engineering and Technology

endswith() Returns true if the string ends with the specified value

expandtabs() Sets the tab size of the string

find() Searches the string for a specified value and returns the
position of where it was found

format() Formats specified values in a string

format_map() Formats specified values in a string

index() Searches the string for a specified value and returns the
position of where it was found

isalnum() Returns True if all characters in the string are alphanumeric

isalpha() Returns True if all characters in the string are in the


alphabet

isdecimal() Returns True if all characters in the string are decimals

isdigit() Returns True if all characters in the string are digits

isidentifier() Returns True if the string is an identifier

islower() Returns True if all characters in the string are lower case

isnumeric() Returns True if all characters in the string are numeric

isprintable() Returns True if all characters in the string are printable

isspace() Returns True if all characters in the string are whitespaces

istitle() Returns True if the string follows the rules of a title

isupper() Returns True if all characters in the string are upper case

join() Joins the elements of an iterable to the end of the string

ljust() Returns a left justified version of the string

lower() Converts a string into lower case

lstrip() Returns a left trim version of the string

D. Subhashini, Sr. Assist Prof CS dept


Geethanjali College of Engineering and Technology

maketrans() Returns a translation table to be used in translations

partition() Returns a tuple where the string is parted into three parts

replace() Returns a string where a specified value is replaced with a


specified value

rfind() Searches the string for a specified value and returns the last
position of where it was found

rindex() Searches the string for a specified value and returns the last
position of where it was found

rjust() Returns a right justified version of the string

rpartition() Returns a tuple where the string is parted into three parts

rsplit() Splits the string at the specified separator, and returns a list

rstrip() Returns a right trim version of the string

split() Splits the string at the specified separator, and returns a list

splitlines() Splits the string at line breaks and returns a list

startswith() Returns true if the string starts with the specified value

strip() Returns a trimmed version of the string

swapcase() Swaps cases, lower case becomes upper case and vice versa

title() Converts the first character of each word to upper case

translate() Returns a translated string

upper() Converts a string into upper case

zfill() Fills the string with a specified number of 0 values at the


beginning

D. Subhashini, Sr. Assist Prof CS dept


Geethanjali College of Engineering and Technology

Booleans
Booleans represent one of two values: True or False.

Boolean Values
In programming you often need to know if an expression is True or False.

You can evaluate any expression in Python, and get one of two
answers, True or False.

When you compare two values, the expression is evaluated and Python returns
the Boolean answer:

Example
print(10 > 9)
print(10 == 9)
print(10 < 9)

When you run a condition in an if statement, Python returns True or False:

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

Evaluate Values and Variables


The bool() function allows you to evaluate any value, and give
you True or False in return,

D. Subhashini, Sr. Assist Prof CS dept


Geethanjali College of Engineering and Technology

Example Evaluate a string and a number:


print(bool("Hello"))
print(bool(15))

Example Evaluate two variables:


x = "Hello"
y = 15

print(bool(x))
print(bool(y))

Most Values are True


Almost any value is evaluated to True if it has some sort of content.

Any string is True, except empty strings.

Any number is True, except 0.

Any list, tuple, set, and dictionary are True, except empty ones.

Example The following will return True:


bool("abc")
bool(123)
bool(["apple", "cherry", "banana"])

Some Values are False


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 The following will return False:

D. Subhashini, Sr. Assist Prof CS dept


Geethanjali College of Engineering and Technology

bool(False)
bool(None)
bool(0)
bool("")
bool(())
bool([])
bool({})

Functions can Return a Boolean


You can create functions that returns a Boolean Value:

Example Print the answer of a function:


def myFunction():
return True

print(myFunction())

You can execute code based on the Boolean answer of a function:

Example Print "YES!" if the function returns True, otherwise print


"NO!":
def myFunction() :
return True

if myFunction():
print("YES!")
else:
print("NO!")

Exercise:
The statement below would print a Boolean value, which one?

print(10 > 9)

D. Subhashini, Sr. Assist Prof CS dept


Geethanjali College of Engineering and Technology

Operators
Operators are used to perform operations on variables and values.

Python divides the operators in the following groups:

 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

+ Addition x+y

- Subtraction x-y

* Multiplication x*y

/ Division x/y

% Modulus x%y

** Exponentiation x ** y

// Floor division x // y

D. Subhashini, Sr. Assist Prof CS dept


Geethanjali College of Engineering and Technology

Assignment Operators
Assignment operators are used to assign values to variables:

Operator Example Same As

= x=5 x=5

+= x += 3 x=x+3

-= x -= 3 x=x-3

*= x *= 3 x=x*3

/= x /= 3 x=x/3

%= x %= 3 x=x%3

//= x //= 3 x = x // 3

**= x **= 3 x = x ** 3

&= x &= 3 x=x&3

|= x |= 3 x=x|3

^= x ^= 3 x=x^3

>>= x >>= 3 x = x >> 3

<<= x <<= 3 x = x << 3

D. Subhashini, Sr. Assist Prof CS dept


Geethanjali College of Engineering and Technology

Comparison Operators
Comparison operators are used to compare two values:

Operator Name Example

== Equal x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y

Logical Operators
Logical operators are used to combine conditional statements:

Operator Description Example

and Returns True if both statements are true x < 5 and x < 10

Or Returns True if one of the statements is x < 5 or x < 4


true

not Reverse the result, returns False if the not(x < 5 and x < 10)
result is true

D. Subhashini, Sr. Assist Prof CS dept


Geethanjali College of Engineering and Technology

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:

Operator Description Example

is Returns True if both variables are the same object x is y

is not Returns True if both variables are not the same x is not y
object

Membership Operators
Membership operators are used to test if a sequence is presented in an object:

Operator Description Example

in Returns True if a sequence with the specified value is x in y


present in the object

not in Returns True if a sequence with the specified value is x not in y


not present in the object

D. Subhashini, Sr. Assist Prof CS dept


Geethanjali College of Engineering and Technology

Bitwise Operators
Bitwise operators are used to compare (binary) numbers:

Operator Name Description

& AND Sets each bit to 1 if both bits are 1

| OR Sets each bit to 1 if one of two bits is 1

^ XOR Sets each bit to 1 if only one of two bits is 1

~ NOT Inverts all the bits

<< Zero fill left Shift left by pushing zeros in from the right and let
shift the leftmost bits fall off

>> Signed Shift right by pushing copies of the leftmost bit in


right shift from the left, and let the rightmost bits fall off

Exercise:
Multiply 10 with 5, and print the result.

print(10 5)

D. Subhashini, Sr. Assist Prof CS dept


Geethanjali College of Engineering and Technology

User Input

Python allows for user input.

That means we are able to ask the user for input.

The method is a bit different in Python 3.6 than Python 2.7.

Python 3.6 uses the input() method.

Python 2.7 uses the raw_input() method.

Example The following example asks for the username, and when
you entered the username, it gets printed on the screen:

Python 3.6
username = input("Enter username:")
print("Username is: " + username)

Python 2.7
username = raw_input("Enter username:")
print("Username is: " + username)

Python stops executing when it comes to the input() function, and continues
when the user has given some input.

D. Subhashini, Sr. Assist Prof CS dept


Geethanjali College of Engineering and Technology

if ... else
Conditions and If statements
Python supports the usual logical conditions from mathematics:

 Equals: a == b
 Not Equals: a != b
 Less than: a < b
 Less than or equal to: a <= b
 Greater than: a > b
 Greater than or equal to: a >= b

These conditions can be used in several ways, most commonly in "if


statements" and loops.

An "if statement" is written by using the if keyword.

Example if statement:
a = 33
b = 200
if b > a:
print("b is greater than a")

Indentation
Python relies on indentation (whitespace at the beginning of a line) to define
scope in the code. Other programming languages often use curly-brackets for
this purpose.

Example if statement, without indentation (will raise an error):


a = 33
b = 200
if b > a:
print("b is greater than a") # you will get an error

D. Subhashini, Sr. Assist Prof CS dept


Geethanjali College of Engineering and Technology

elif
The elif keyword is pythons way of saying "if the previous conditions were not
true, then try this condition".

Example
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")

In this example a is equal to b, so the first condition is not true, but


the elif condition is true, so we print to screen that "a and b are equal".

else
The else keyword catches anything which isn't caught by the preceding
conditions.

Example
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")

In this example a is greater than b, so the first condition is not true, also
the elif condition is not true, so we go to the else condition and print to
screen that "a is greater than b".

You can also have an else without the elif:

D. Subhashini, Sr. Assist Prof CS dept


Geethanjali College of Engineering and Technology

Example
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")

Short Hand if
If you have only one statement to execute, you can put it on the same line as
the if statement.

Example One line if statement:


if a > b: print("a is greater than b")

Short Hand if ... else


If you have only one statement to execute, one for if, and one for else, you can
put it all on the same line:

Example One line if else statement:


a = 2
b = 330
print("A") if a > b else print("B")

This technique is known as Ternary Operators, or Conditional Expressions.

You can also have multiple else statements on the same line:

D. Subhashini, Sr. Assist Prof CS dept


Geethanjali College of Engineering and Technology

Example One line if else statement, with 3 conditions:


a = 330
b = 330
print("A") if a > b else print("=") if a == b else print("B")

and logical operator


The and keyword is a logical operator,used to combine conditional statements:

Example Test if a is greater than b, AND if c is greater than a:


a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")

or logical operator
The or keyword is a logical operator, used to combine conditional statements:

Example Test if a is greater than b, OR if a is greater than c:

a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions is True")

Nested if
if statements inside if statements, is called nested if statements.

D. Subhashini, Sr. Assist Prof CS


dept
Geethanjali College of Engineering and Technology

Example
x = 41

if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")

The pass Statement


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

Example
a = 33
b = 200

if b > a:
pass

Exercise:
Print "Hello World if a is greater than b.

a = 50
b = 10
a b
print("Hello World")

D. Subhashini,Sr. Assist Prof CS


dept
Geethanjali College of Engineering and Technology

Loops
Python has two primitive loop commands:

 while loops
 for loops

The while Loop


With the while loop we can execute a set of statements as long as a condition is
true.

Example Print i as long as i is less than 6:


i = 1
while i < 6:
print(i)
i += 1
remember to increment i, or else the loop will continue forever.

The while loop requires relevant variables to be ready, in this example we need
to define an indexing variable, i, which we set to 1.

The break Statement


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

Example Exit the loop when i is 3:

i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1

D. Subhashini,Sr. Assist Prof CS


dept
Geethanjali College of Engineering and Technology

The continue Statement


With the continue statement we can stop the current iteration, and continue
with the next:

Example Continue to the next iteration if i is 3:


i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)

The else Statement


With the else statement we can run a block of code once when the condition no
longer is true:

Example Print a message once the condition is false:


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

Exercise:
Print i as long as i is less than 6.

i = 1
i < 6
print(i)
i += 1

D. Subhashini,Sr. Assist Prof CS


dept
Geethanjali College of Engineering and Technology

The for Loop


A for loop is used for iterating over a sequence (that is either a list, a tuple, a
dictionary, a set, or a string).This is less like the for keyword in other
programming languages, and works more like an iterator method as found in
other object-orientated programming languages. for loop can execute a set of
statements, once for each item in a list, tuple, set etc.

Example Print each fruit in a fruit list:


fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)

The for loop does not require an indexing variable to set beforehand.

Looping Through a String


Even strings are iterable objects, they contain a sequence of characters:

Example Loop through the letters in the word "banana":


for x in "banana":
print(x)

The break Statement


break statement can stop the loop before it has looped through all the items:

Example Exit the loop when x is "banana":


fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break

D. Subhashini,Sr. Assist Prof CS


dept
Geethanjali College of Engineering and Technology

Example Exit the loop when x is "banana", but this time the break
comes before the print:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
break
print(x)

The continue Statement


With the continue statement we can stop the current iteration of the loop, and
continue with the next:

Example Do not print banana:


fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)

The range() Function


To loop through a set of code a specified number of times, we can use
the range() function,

The range() function returns a sequence of numbers, starting from 0 by


default, and increments by 1 (by default), and ends at a specified number.

Example Using the range() function:


for x in range(6):
print(x)

Note that range(6) is not the values of 0 to 6, but the values 0 to 5.

D. Subhashini,Sr. Assist Prof CS


dept
Geethanjali College of Engineering and Technology

The range() function defaults to 0 as a starting value, however it is possible to


specify the starting value by adding a parameter: range(2, 6), which means
values from 2 to 6 (but not including 6):

Example Using the start parameter:


for x in range(2, 6):
print(x)

The range() function defaults to increment the sequence by 1, however it is


possible to specify the increment value by adding a third parameter: range(2,
30, 3):

Example Increment the sequence with 3 (default is 1):


for x in range(2, 30, 3):
print(x)

else in For Loop


The else keyword in a for loop specifies a block of code to be executed when the
loop is finished:

Example Print all numbers from 0 to 5, and print a message when


the loop has ended:
for x in range(6):
print(x)
else:
print("Finally finished!")

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

D. Subhashini,Sr. Assist Prof CS


dept
Geethanjali College of Engineering and Technology

Example Print each adjective for every fruit:


adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]

for x in adj:
for y in fruits:
print(x, y)

The pass Statement


for loops cannot be empty, but if you for some reason have a for loop with no
content, put in the pass statement to avoid getting an error.

Example
for x in [0, 1, 2]:
pass

Exercise:
Loop through the items in the fruits list.

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


x fruits
print(x)

D. Subhashini,Sr. Assist Prof CS


dept
Geethanjali College of Engineering and Technology

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

You can pass data, known as parameters, into a function.

A function can return data as a result.

Creating a Function
In Python a function is defined using the def keyword:

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

Calling a Function
To call a function, use the function name followed by parenthesis:

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

my_function()

Arguments
Information can be passed into functions as arguments.

Arguments are specified after the function name, inside the parentheses. You
can add as many arguments as you want, just separate them with a comma.

D. Subhashini,Sr. Assist Prof CS


dept
Geethanjali College of Engineering and Technology

The following example has a function with one argument (fname). When the
function is called, we pass along a first name, which is used inside the function
to print the full name:

Example
def my_function(fname):
print(fname + " is a fruit.")

my_function("Apple")
my_function("Banana")
my_function("Mango")

Parameters or Arguments?
The terms parameter and argument can be used for the same thing:
information that are passed into a function.

Number of Arguments
By default, a function must be called with the correct number of arguments.
Meaning that if your function expects 2 arguments, you have to call the function
with 2 arguments, not more, and not less.

Example This function expects 2 arguments, and gets 2 arguments:


def my_function(name1, name2):
print(name1 + " " + name2)

my_function("Apple", "Mango")

If you try to call the function with 1 or 3 arguments, you will get an error:

Example This function expects 2 arguments, but gets only 1:


def my_function(name1, name2):
print(name1 + " " + name2)

my_function("Apple")

D. Subhashini,Sr. Assist Prof CS


dept
Geethanjali College of Engineering and Technology

Arbitrary Arguments, *args


If you do not know how many arguments that will be passed into your function,
add a * before the parameter name in the function definition.

This way the function will receive a tuple of arguments, and can access the
items accordingly:

Example If the number of arguments is unknown, add a * before the


parameter name:
def my_function(*kids):
print("The youngest child is " + kids[2])

my_function("John", "Jony", "Janardhan")

Keyword Arguments
You can also send arguments with the key = value syntax.

This way the order of the arguments does not matter.

Example
def my_function(child3, child2, child1):
print("The youngest child is " + child3)

my_function(child1 = "john", child2 = "Jony", child3 = "Janardhan")

Arbitrary Keyword Arguments, **kwargs


If you do not know how many keyword arguments that will be passed into your
function, add two asterisk: ** before the parameter name in the function
definition.

D. Subhashini,Sr. Assist Prof CS


dept
Geethanjali College of Engineering and Technology

This way the function will receive a dictionary of arguments, and can access the
items accordingly:

Example If the number of keyword arguments is unknown, add a


double ** before the parameter name:
def my_function(**kid):
print("His last name is " + kid["lname"])

my_function(fname = "Dasaradha", lname = "Rama")

Default Parameter Value


If we call the function without argument, it uses the default value:

Example
def my_function(country = "Norway"):
print("I am from " + country)

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

Passing a List as an Argument


You can send any data types of argument to a function (string, number, list,
dictionary etc.), and it will be treated as the same data type inside the function.

Example Sending a List as an argument will still be a List when it


reaches the function:
def my_function(food):
for x in food:
print(x)

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


my_function(fruits)

D. Subhashini,Sr. Assist Prof CS


dept
Geethanjali College of Engineering and Technology

Return Values
To let a function return a value, use the return statement:

Example
def my_function(x):
return 5 * x

print(my_function(3))
print(my_function(5))
print(my_function(9))

The pass Statement


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

Example
def myfunction():
pass

Recursion
Python also accepts function recursion, which means a defined function can call
itself.

Recursion is a common mathematical and programming concept. It means that


a function calls itself. This has the benefit of meaning that you can loop through
data to reach a result.

The developer should be very careful with recursion as it can be quite easy to
slip into writing a function which never terminates, or one that uses excess

D. Subhashini,Sr. Assist Prof CS


dept
Geethanjali College of Engineering and Technology

amounts of memory or processor power. However, when written correctly


recursion can be a very efficient and mathematically-elegant approach to
programming.

In this example, tri_recursion() is a function that we have defined to call


itself ("recurse"). We use the k variable as the data, which decrements (-1)
every time we recurse. The recursion ends when the condition is not greater
than 0 (i.e. when it is 0).

Example Recursion Example


def tri_recursion(k):
if(k > 0):
result = k + tri_recursion(k - 1)
print(result)
else:
result = 0
return result

print("\n\nRecursion Example Results")


tri_recursion(6)

Exercise:
Create a function named my_function.

:
print("Hello from a function")

D. Subhashini,Sr. Assist Prof CS


dept
Geethanjali College of Engineering and Technology

Modules
What is a Module?
Consider a module to be the same as a code library.

A file containing a set of functions you want to include in your application.

Create a Module
To create a module just save the code you want in a file with the file
extension .py:

Example Save this code in a file named [Link]


def greeting(name):
print("Hello, " + name)

Use a Module
Now we can use the module we just created, by using the import statement:

Example Import the module named mymodule, and call the greeting
function:
import mymodule

[Link]("students”)

When using a function from a module, use the


syntax: module_name.function_name.

D. Subhashini,Sr. Assist Prof CS


dept
Geethanjali College of Engineering and Technology

Variables in Module
The module can contain functions, as already described, but also variables of all
types (arrays, dictionaries, objects etc):

Example Save this code in the file [Link]

person1 = {
"name": "Ram",
"age": 36,
"country": "India"
}

Example Import the module named mymodule, and access the


person1 dictionary:
import mymodule

a = mymodule.person1["age"]
print(a)

Naming a Module
You can name the module file whatever you like, but it must have the file
extension .py

Re-naming a Module
You can create an alias when you import a module, by using the as keyword:

Example Create an alias for mymodule called mm:


import mymodule as mm

a = mm.person1["age"]
print(a)

D. Subhashini,Sr. Assist Prof CS


dept
Geethanjali College of Engineering and Technology

Built-in Modules
There are several built-in modules, which you can import whenever you like.

Example Import and use the platform module:


import platform

x = [Link]()
print(x)

Using the dir() Function


There is a built-in function to list all the function names (or variable names) in a
module. dir() function can be used on pre defined and user defined modules.

Example List all the defined names belonging to the platform module:
import platform

x = dir(platform)
print(x)

Import From Module


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

Example: The module named mymodule has one function and one dictionary:
def greeting(name):
print("Hello, " + name)

person1 = {
"name": "Ram",
"age": 36,
"country": "India"
}

D. Subhashini,Sr. Assist Prof CS


dept
Geethanjali College of Engineering and Technology

Example Import only the person1 dictionary from the module:


from mymodule import person1

print (person1["age"])

When importing using the from keyword, do not use the module name when
referring to elements in the module.
Example: person1["age"], not mymodule.person1["age"]

Exercise:
What is the correct syntax to import a module named "mymodule"?

mymodule

D. Subhashini,Sr. Assist Prof CS


dept
Geethanjali College of Engineering and Technology

Functions (Contd..)
Functions are the most important aspect of an application. A function can be defined
as the organized block of reusable code, which can be called whenever required.

Python allows us to divide a large program into the basic building blocks known as a
function. The function contains the set of programming statements. A function can
be called multiple times to provide reusability and modularity to the Python program.

The Function helps to programmer to break the program into the smaller part. It
organizes the code very effectively and avoids the repetition of the code. As the
program grows, function makes the program more organized.

Python provide us various inbuilt functions like range() or print(). Although, the
user can create its functions, which can be called user-defined functions.

There are mainly two types of functions.

o User-define functions - The user-defined functions are those define by


the user to perform the specific task.
o Built-in functions - The built-in functions are those functions that are pre-
defined in Python.

In this tutorial, we will discuss the user define functions.

Advantage of Functions in Python


There are the following advantages of Python functions.

o Using functions, we can avoid rewriting the same logic/code again and
again in a program.
o We can call functions multiple times in a program and anywhere in a
program.
o We can track a large Python program easily when it is divided into
multiple functions.
o However, Function calling is always overhead in a Python program.

D. Subhashini,Sr. Assist Prof CS


dept
Geethanjali College of Engineering and Technology

Creating a Function
Python provides the def keyword to define the function. The syntax for defining
the function is given below.

def my_function(parameters):
function_block
return expression

Syntax of functions definition.

o The def keyword, along with the function name is used to define the
function.
o The function name must follow identifier rules.
o A function accepts the parameter (argument), and they can be optional.
o The function block is started with the colon (:), and block statements
must be at the same indentation.
o The return statement is used to return the value. A function can have
only one return

Function Calling
After the function is created, we can call it from another function. A function
must be defined before the function call; otherwise, the Python interpreter gives
an error. To call the function, use the function name followed by the
parentheses.

Example That prints “hello World”

#function definition
def hello_world():
print("hello world")
# function calling
hello_world()

D. Subhashini,Sr. Assist Prof CS


dept
Geethanjali College of Engineering and Technology

The return statement


The return statement is used at the end of the function and returns the result of
the function. It terminates the function execution and transfers the result where
the function is called. The return statement cannot be used outside of the
function.

Syntax

return [expression_list]

It can contain the expression which gets evaluated and value is returned to the
caller function. If the return statement has no expression or does not exist itself
in the function then it returns the None object.

Example1

# Defining function
def sum():
a = 10
b = 20
c = a+b
return c
# calling sum() function in print statement
print("The sum is:",sum())

Output: The sum is: 30

In the above code, we have defined the function named sum, and it has a
statement c = a+b, which computes the given values, and the result is
returned by the return statement to the caller function.

Example Creating function without return statement

def sum():
a = 10
b = 20
c = a+b
# calling sum() function in print statement
print(sum())

D. Subhashini,Sr. Assist Prof CS


dept
Geethanjali College of Engineering and Technology

Output: None

In the above code, we have defined the same function without the return
statement as we can see that the sum() function returned the None object to
the caller function.

Arguments in function
The arguments are types of information which can be passed into the function.
The arguments are specified in the parentheses. We can pass any number of
arguments, but they must be separate them with a comma.

Example contains a function that accepts a string as the argument.

#defining the function


def func (name):
print("Hi ",name)
#calling the function
func("Students")

Output: Hi Students

Example Python function to calculate the sum of two variables

def sum (a,b):


return a+b;

a = int(input("Enter a: "))
b = int(input("Enter b: "))

#printing the sum of a and b


print("Sum = ",sum(a,b))

Output:

Enter a: 10
Enter b: 20
Sum = 30

D. Subhashini,Sr. Assist Prof CS


dept
Geethanjali College of Engineering and Technology

Call by reference in Python


In Python, call by reference means passing the actual value as an argument in
the function. All the functions are called by reference, i.e., all the changes made
to the reference inside the function revert back to the original value referred by
the reference.

Example Passing mutable Object (List)

def change_list(list1):
[Link](20)
[Link](30)
print("list inside function = ",list1)

list1 = [10,30,40,50]
change_list(list1)
print("list outside function = ",list1)

Output:

list inside function = [10, 30, 40, 50, 20, 30]


list outside function = [10, 30, 40, 50, 20, 30]

Example Passing immutable Object (String)

def change_string (str):


str = str + " How r you "
print("printing the string inside function :",str)

string1 = "Hi I am there"

change_string(string1)
print("printing the string outside function :",string1)

Output:

printing the string inside function : Hi I am there How r you


printing the string outside function : Hi I am there

D. Subhashini,Sr. Assist Prof CS


dept
Geethanjali College of Engineering and Technology

Types of arguments
There may be several types of arguments which can be passed at the time of
function call.

1. Required arguments
2. Keyword arguments
3. Default arguments
4. Variable-length arguments

Required Arguments

These are the arguments which are required to be passed at the time of function
calling with the exact match of their positions in the function call and function
definition. If either of the arguments is not provided in the function call, or the
position of the arguments is changed, the Python interpreter will show the error.

Example Consider the following example

def func(name):
message = "Hi "+name
return message
name = input("Enter the name:")
print(func(name))

Output:

Enter the name: John


Hi John

Example
The function simple_interest accepts three arguments and returns the s
imple interest accordingly

def simple_interest(p,t,r):
return (p*t*r)/100
p = float(input("Enter the principle amount? "))
r = float(input("Enter the rate of interest? "))

D. Subhashini,Sr. Assist Prof CS


dept
Geethanjali College of Engineering and Technology

t = float(input("Enter the time in years? "))


print("Simple Interest: ",simple_interest(p,r,t))

Output:

Enter the principle amount: 5000


Enter the rate of interest: 5
Enter the time in years: 3
Simple Interest: 750.0

Example Calculate returns the sum of two arguments a and b

def calculate(a,b):
return a+b
calculate(10) # this causes an error as we are missing a required arguments b.

Output:

TypeError: calculate() missing 1 required positional argument: 'b'

Default Arguments

Python allows us to initialize the arguments at the function definition. If the


value of any of the arguments is not provided at the time of function call, then
that argument can be initialized with the value given in the definition even if the
argument is not specified at the function call.
Example

def printme(name,age=22):
print("My name is",name,"and age is",age)
printme(name = "john")

Output:

My name is John and age is 22


Example

def printme(name,age=22):
print("My name is",name,"and age is",age)
D. Subhashini,Sr. Assist Prof CS
dept
Geethanjali College of Engineering and Technology

printme(name = "john")
#the variable age is not passed into the function however the default value of
age is considered in the function
printme(age = 10,name="David")
#the value of age is overwritten here, 10 will be printed as age

Output:

My name is john and age is 22


My name is David and age is 10

Variable-length Arguments (*args) or Arbitrary Arguments

In large projects, sometimes we may not know the number of arguments to be


passed in advance. In such cases, Python provides us the flexibility to offer the
comma-separated values which are internally treated as tuples at the function
call. By using the variable-length arguments, we can pass any number of
arguments. We define the variable-length argument using the *args.

Example

def printme(*names):
print("type of passed argument is ",type(names))
print("printing the passed arguments...")
for name in names:
print(name)
printme("john","David","smith","nick")

Output:

type of passed argument is <class 'tuple'>


printing the passed arguments...
john
David
smith
nick

In the above code, we passed *names as variable-length argument. We called


the function and passed values which are treated as tuple internally. The tuple
is an iterable sequence the same as the list. To print the given values, we
iterated *arg names using for loop.

D. Subhashini,Sr. Assist Prof CS


dept
Geethanjali College of Engineering and Technology

Keyword arguments

This kind of function call will enable us to pass the arguments in the random
order. The name of the arguments is treated as the keywords and matched in the
function calling and definition. If the same match is found, the values of the
arguments are copied in the function definition.

Example with name and message as the keyword arguments

def func(name,message):
print("printing the message with",name,"and ",message)

func(name = "John",message="hello")

Output: printing the message with John and hello

Example Function called with the keyword arguments… providing the


values in different order at the calling

def simple_interest(p,t,r):
return (p*t*r)/100
print("Simple Interest: ",simple_interest(t=10,r=10,p=1900))

Output:

Simple Interest: 1900.0

If we provide the different name of arguments at the time of function call, an


error will be thrown.

Example Function called with the keyword arguments, that does not
match

def simple_interest(p,t,r):
return (p*t*r)/100
print("Simple Interest: ",simple_interest(time=10,rate=10,principle=1900))

D. Subhashini,Sr. Assist Prof CS


dept
Geethanjali College of Engineering and Technology

Output:

TypeError: simple_interest() got an unexpected keyword argument 'time'

Python allows us to provide the mix of the required arguments and keyword
arguments at the time of function call. However, the required argument must not
be given after the keyword argument, i.e., once the keyword argument is
encountered in the function call, the next arguments must also be the keyword
arguments.
Example

def func(name1,message,name2):
print("printing the message with",name1,",",message,",and",name2)
#the first argument is not the keyword argument
func("John",message="hello",name2="Jhony")

Output:

printing the message with John , hello ,and Jhony

The following example will cause an error due to an improper mix of keyword
and required arguments being passed in the function call.

Example Improper mix of keyword and required arguments

def func(name1,message,name2):
print("printing the message with",name1,",",message,",and",name2)
func("John",message="hello","David")

Output:

SyntaxError: positional argument follows keyword argument

Python provides the facility to pass the multiple keyword arguments which can
be represented as **kwargs. It is similar as the *args but it stores the
argument in the dictionary format.

This type of arguments is useful when we do not know the number of


arguments in advance.

D. Subhashini,Sr. Assist Prof CS


dept
Geethanjali College of Engineering and Technology

Example Many arguments using Keyword argument

def food(**kwargs):
print(kwargs)
food(a="Apple")
food(fruits="Orange", Vegetables ="Carrot")

Output:

{'a': 'Apple'}
{'fruits': 'Orange', 'Vegetables': 'Carrot'}

Scope of variables
The scopes of the variables depend upon the location where the variable is being
declared. The variable declared in one part of the program may not be accessible
to the other parts.

In python, the variables are defined with the two types of scopes.

1. Global variables
2. Local variables

The variable defined outside any function is known to have a global scope,
whereas the variable defined inside a function is known to have a local scope.

Example Local Variable

def print_message():
message = "hello !! I am going to print a message."
# the variable message is local to the function itself
print(message)

print_message()
print(message)
# this will cause an error since a local variable cannot be accessible here.

D. Subhashini,Sr. Assist Prof CS


dept
Geethanjali College of Engineering and Technology

Output:

hello !! I am going to print a message.


File "/root/PycharmProjects/PythonTest/[Link]", line 5, in
print(message)
NameError: name 'message' is not defined

Example

def calculate(*args):
sum=0
for arg in args:
sum = sum +arg
print("The sum is",sum)

sum=0
calculate(10,20,30) #60 will be printed as the sum
print("Value of sum outside the function:",sum) # 0 will be printed Output:

Output:

The sum is 60
Value of sum outside the function: 0

Example Global variables

def calculate(*args):
global sum
for arg in args:
sum = sum +arg
print("The sum is",sum)

sum=0
calculate(10,20,30) #60 will be printed as the sum
print("Value of sum outside the function:",sum)

D. Subhashini,Sr. Assist Prof CS


dept
Geethanjali College of Engineering and Technology

Output:

The sum is 60
Value of sum outside the function: 60

Iterators
Python Iterators
An iterator is an object that contains a countable number of values.

An iterator is an object that can be iterated upon, meaning that you can
traverse through all the values.

Technically, in Python, an iterator is an object which implements the iterator


protocol, which consist of the methods iter_() and next ().

Iterator vs Iterable
Lists, tuples, dictionaries, and sets are all iterable objects. They are
iterable containers which you can get an iterator from.

All these objects have a iter() method which is used to get an iterator:

Example Return an iterator from a tuple, and print each value:

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


myit = iter(mytuple)

print(next(myit))
print(next(myit))
print(next(myit))

Even strings are iterable objects, and can return an iterator:

D. Subhashini,Sr. Assist Prof CS


dept
Geethanjali College of Engineering and Technology

Example Strings are also iterable objects, containing a sequence of


characters:

mystr = "banana"
myit = iter(mystr)

print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))

Looping Through an Iterator


We can also use a for loop to iterate through an iterable object:

Example Iterate the values of a tuple:

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

for x in mytuple:
print(x)

Example Iterate the characters of a string:


mystr = "banana"

for x in mystr:
print(x)

The for loop actually creates an iterator object and executes the next() method
for each loop.

D. Subhashini,Sr. Assist Prof CS


dept
Geethanjali College of Engineering and Technology

File Open
Python has several functions for creating, reading, updating, and deleting
files.

File Handling
The key function for working with files in Python is the open() function.

The open() function takes two parameters; filename, and mode.

There are four different methods (modes) for opening a file:

"r" - Read - Default value. Opens a file for reading, error if the file does not
exist

"a" - Append - Opens a file for appending, creates the file if it does not exist

"w" - Write - Opens a file for writing, creates the file if it does not exist

"x" - Create - Creates the specified file, returns an error if the file exists

In addition you can specify if the file should be handled as binary or text mode

"t" - Text - Default value. Text mode

"b" - Binary - Binary mode (e.g. images)

Syntax
To open a file for reading it is enough to specify the name of the file:

f = open("[Link]")

The code above is the same as:


f = open("[Link]", "rt")

D. Subhashini,Sr. Assist Prof CS


dept
Geethanjali College of Engineering and Technology

Because "r" for read, and "t" for text are the default values, you do not need to
specify them.

Open a File on the Server


Assume we have the following file, located in the same folder as Python:

[Link]

Hello! Welcome to [Link]


This file is for testing purposes.
Good Luck!

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

The open() function returns a file object, which has a read() method for reading
the content of the file:
Example
f = open("[Link]", "r")
print([Link]())

If the file is located in a different location, you will have to specify the file path,
like this:

Example Open a file on a different location:

f = open("D:\\myfiles\[Link]", "r")
print([Link]())

Read Only Parts of the File


By default the read() method returns the whole text, but you can also specify
how many characters you want to return:

Example Return the 5 first characters of the file:

f = open("[Link]", "r")
print([Link](5))
D. Subhashini,Sr. Assist Prof CS
dept
Geethanjali College of Engineering and Technology

Read Lines
You can return one line by using the readline() method:

Example Read one line of the file:

f = open("[Link]", "r")
print([Link]())

By calling readline() two times, you can read the two first lines:

Example Read two lines of the file:

f = open("[Link]", "r")
print([Link]())
print([Link]())

By looping through the lines of the file, you can read the whole file, line by line:

Example Loop through the file line by line:

f = open("[Link]", "r")
for x in f:
print(x)

Close Files
It is a good practice to always close the file when you are done with it.

Example Close the file when you are finish with it:

f = open("[Link]", "r")
print([Link]())
[Link]()

D. Subhashini,Sr. Assist Prof CS


dept
Geethanjali College of Engineering and Technology

Note: You should always close your files, in some cases, due to buffering,
changes made to a file may not show until you close the file.

Python File Write


Write to an Existing File
To write to an existing file, you must add a parameter to the open() function:

"a" - Append - will append to the end of the file

"w" - Write - will overwrite any existing content

Example Open the file "[Link]" and append content to the file:

f = open("[Link]", "a")
[Link]("Now the file has more content!")
[Link]()

#open and read the file after the appending:


f = open("[Link]", "r")
print([Link]())

Example Open the file "[Link]" and overwrite the content:


f = open("[Link]", "w")
[Link]("Woops! I have deleted the content!")
[Link]()

#open and read the file after the appending:


f = open("[Link]", "r")
print([Link]())

Note: the "w" in method will overwrite the entire file.

D. Subhashini,Sr. Assist Prof CS


dept
Geethanjali College of Engineering and Technology

File Pointer positions

Python provides the tell() method which is used to print the byte number at
which the file pointer currently exists. Consider the following example.

# open the file [Link] in read mode


fileptr = open("[Link]","r")
#initially the filepointer is at 0
print("The filepointer is at byte :",[Link]())

#reading the content of the file


content = [Link]();
#after the read operation file pointer modifies. tell() returns the location of the
fileptr
print("After reading, the filepointer is at:",[Link]())

Output:

The filepointer is at byte : 0


After reading, the filepointer is at: 117

Modifying file pointer position

In real-world applications, sometimes we need to change the file pointer


location externally since we may need to read or write the content at various
locations.

For this purpose, the Python provides us the seek() method which enables us
to modify the file pointer position externally.

The syntax to use the seek() method is given below.

Syntax:
<fileptr>.seek(offset[,from])

The seek() method accepts two parameters:

offset: It refers to the new position of the file pointer within the file.

from: It indicates the reference position from where the bytes are to be
moved. If it is set to 0, the beginning of the file is used as the reference
position. If it is set to 1, the current position of the file pointer is used as the

D. Subhashini,Sr. Assist Prof CS


dept
Geethanjali College of Engineering and Technology

reference position. If it is set to 2, the end of the file pointer is used as the
reference position.

Consider the following example.

Example

# open the file [Link] in read mode


fileptr = open("[Link]","r")
#initially the filepointer is at 0
print("The filepointer is at byte :",[Link]())
#changing the file pointer location to 10.
[Link](10);
#tell() returns the location of the fileptr.
print("After reading, the filepointer is at:",[Link]())

Output:

The filepointer is at byte : 0


After reading, the filepointer is at: 10

D. Subhashini,Sr. Assist Prof CS


dept
Geethanjali College of Engineering and Technology

Create a New File


To create a new file in Python, use the open() method, with one of the
following parameters:

"x" - Create - will create a file, returns an error if the file exist

"a" - Append - will create a file if the specified file does not exist

"w" - Write - will create a file if the specified file does not exist

Example Create a file called "[Link]":


f = open("[Link]", "x")

Result: a new empty file is created!

Example Create a new file if it does not exist:

f = open("[Link]", "w")

Delete a File
To delete a file, you must import the OS module, and run its [Link]() function:

Example Remove the file "[Link]":

import os
[Link]("[Link]")

Check if File exist:


To avoid getting an error, you might want to check if the file exists before you
try to delete it:

Example Check if file exists, then delete it:

D. Subhashini,Sr. Assist Prof CS


dept
Geethanjali College of Engineering and Technology

import os
if [Link]("[Link]"):
[Link]("[Link]")
else:
print("The file does not exist")

Delete Folder
To delete an entire folder, use the [Link]() method:

Example Remove the folder "myfolder":

import os
[Link]("myfolder")

Note: You can only remove empty folders.


The file related methods

The file object provides the following methods to manipulate the files on various operating systems.

SN Method Description

1 [Link]() It closes the opened file. The file once closed, it can't be
read or write anymore.

2 [Link]() It flushes the internal buffer.

3 [Link]()
It returns the file descriptor used by the underlying
implementation to request I/O from the OS.

4 [Link]()
It returns true if the file is connected to a TTY device,
otherwise returns false.

5 [Link]() It returns the next line from the file.

6 [Link]([size]) It reads the file for the specified size.

7 [Link]([size])
It reads one line from the file and places the file pointer to
the beginning of the new line.

D. Subhashini,Sr. Assist Prof CS


dept
Geethanjali College of Engineering and Technology

8
[Link]([sizehin It returns a list containing all the lines of the file. It reads
t]) the file until the EOF occurs using readline() function.

9 [Link](offset[,from
It modifies the position of the file pointer to a specified
)
offset with the specified reference.

10 [Link]()
It returns the current position of the file pointer within the
file.

11 [Link]([size]) It truncates the file to the optional specified size.

12 [Link](str) It writes the specified string to a file

13 [Link](seq) It writes a sequence of the strings to a file.

D. Subhashini,Sr. Assist Prof CS


dept
Geethanjali College of Engineering and Technology

Exceptions
An exception can be defined as an unusual condition in a program resulting in
the interruption in the flow of the program.

Whenever an exception occurs, the program stops the execution, and thus the
further code is not executed. Therefore, an exception is the run-time errors
that are unable to handle by Python script. An exception is a Python object that
represents an error.

Python provides a way to handle the exception so that the code can be
executed without any interruption. If we do not handle the exception, the
interpreter doesn't execute all the code that exists after the exception.

Python has many built-in exceptions that enable our program to run without
interruption and give the output. These exceptions are given below:

Common Exceptions

Python provides the number of built-in exceptions, but here we are describing
the common standard exceptions. A list of common exceptions that can be
thrown from a standard Python program is given below.

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


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

The problem without handling exceptions

As we have already discussed, the exception is an abnormal condition that


halts the execution of the program.

Suppose we have two variables a and b, which take the input from the user
and perform the division of these values. What if the user entered the zero as
the denominator? It will interrupt the program execution and through a
ZeroDivision exception. Let's see the following example.

D. Subhashini,Sr. Assist Prof CS


dept
Geethanjali College of Engineering and Technology

Example
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
print("a/b = %d" %c)
#other code:
print("Hi I am other part of the program")

Output:

Enter a:10
Enter b:0
Traceback (most recent call last):
File "[Link]", line 3, in
<module> c = a/b;
ZeroDivisionError: division by zero

The above program is syntactically correct, but it through the error because of
unusual input. That kind of programming may not be suitable or recommended
for the projects because these projects are required uninterrupted execution.
That's why an exception- handling plays an essential role in handling these
unexpected exceptions. We can handle these exceptions in the following way.

Exception handling in python

The try-expect statement


If the Python program contains suspicious code that may throw the exception,
we must place that code in the try block. The try block must be followed with
the except statement, which contains a block of code that will be executed if
there is some exception in the try block.

D. Subhashini,Sr. Assist Prof CS


dept
Geethanjali College of Engineering and Technology

try:
#block of code

except Exception1:
#block of code

except Exception2:
#block of code

#other code

Example 1

try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
except:
print("Can't divide with zero")

Output:

Enter a:10
Enter b:0
Can't divide with zero

We can also use the else statement with the try-except statement in which,
we can place the code which will be executed in the scenario if no exception
occurs in the try block. The syntax to use the else statement with the try-
except statement is given below.

try:
#block of code

except Exception1:
#block of code

else:
#this code executes if no except block is executed

D. Subhashini,Sr. Assist Prof CS


dept
Geethanjali College of Engineering and Technology

Consider the following program.

Example 2

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

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

D. Subhashini,Sr. Assist Prof CS


dept
Geethanjali College of Engineering and Technology

The except statement with no exception


Python provides the flexibility not to specify the name of exception with the
exception statement. Consider the following example.

Example

try:
a = int(input("Enter
a:"))
b = a/b;
c int(input("Enter
b:"))
print("a/b = %d"%c)
except:
print("can't divide by zero")
else:
print("Hi I am else block")

The except statement using with exception variable


We can use the exception variable with the except statement. It is used by using
the as keyword. this object will return the cause of the exception. Consider the
following example:

try:
a = int(input("Enter
a:"))
b = a/b
c int(input("Enter
b:"))
print("a/b = %d"%c)
# Using exception object with the except statement
except Exception as e:
print("can't divide by zero")
print(e)
else:
print("Hi I am else block")

Enter a:10
Enter b:0
can't divide by
zero division by
zero

D. Subhashini,Sr. Assist Prof CS


dept
Geethanjali College of Engineering and Technology

Points to remember
1. Python facilitates us to not specify the exception with the except statement.
2. We can declare multiple exceptions in the except statement since the try block may
contain the statements which throw the different type of exceptions.
3. We can also specify an else block along with the try-except statement, which will be
executed if no exception is raised in the try block.
4. The statements that don't throw the exception should be placed inside the else block.

Example

try:
#this will throw an exception if the file doesn't exist.
fileptr = open("[Link]","r")
except IOError:
print("File not found")
else:
print("The file opened successfully")
1. [Link]()

Output:

File not found

Declaring Multiple Exceptions

The Python allows us to declare the multiple exceptions with the except clause.
Declaring multiple exceptions is useful in the cases where a try block throws
multiple exceptions. The syntax is given below.

Syntax

try:
#block of code

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


#block of code

else:
#block of code

D. Subhashini,Sr. Assist Prof CS


dept
Geethanjali College of Engineering and Technology

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

Output:

Arithmetic Exception

The try...finally block

Python provides the optional finally statement, which is used with the try
statement. It is executed no matter what exception occurs and used to release
the external resource. The finally block provides a guarantee of the execution.

We can use the finally block with the try block in which we can place the
necessary code, which must be executed before the try statement throws an
exception.

The syntax to use the finally block is given below.

Syntax

try:
# block of code
# this may throw an exception
finally:
# block of code
# this will always be executed

D. Subhashini,Sr. Assist Prof CS


dept
Geethanjali College of Engineering and Technology

D. Subhashini,Sr. Assist Prof CS


dept
Geethanjali College of Engineering and Technology

try:
fileptr = open("[Link]","r")
try:
[Link]("Hi I am good")
finally:
[Link]()
print("file closed")
except:
print("Error")

Output:

file closed
Error

Raising exceptions

An exception can be raised forcefully by using the raise clause in Python. It is


useful in that scenario where we need to raise an exception to stop the
execution of the program.

For example, there is a program that requires 2GB memory for


execution, and if the program tries to occupy 2GB of memory, then we
can raise an exception to stop the execution of the program.

The syntax to use the raise statement is given below.

Syntax

raise Exception_class <(value)>

Points to remember

1. To raise an exception, the raise statement is used. The exception class name follows
it.
2. An exception can be provided with a value that can be given in the parenthesis.
3. To access the value "as" keyword is used. "e" is used as a reference variable which
stores the value of the exception.
4. We can pass the value to an exception to specify the exception type.

D. Subhashini,Sr. Assist Prof CS


dept
Geethanjali College of Engineering and Technology

try:
age = int(input("Enter the age:"))
if(age<18):
raise ValueError
else:
print("the age is valid")
except ValueError:
print("The age is not valid")

Output:

Enter the age:17


The age is not valid

Example 2 Raise the exception with message

try:
num = int(input("Enter a positive integer: "))
if(num <= 0):
# we can pass the message in the raise statement
raise ValueError("That is a negative number!")
except ValueError as e:
print(e)

Output:

Enter a positive integer: -


5 That is a negative
number!
Example 3

try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
if b is 0:
raise ArithmeticError
else:
print("a/b = ",a/b)
except ArithmeticError:

D. Subhashini,Sr. Assist Prof CS


dept
Geethanjali College of Engineering and Technology

print("The value of b can't be 0")


Output:

Enter a:10
Enter b:0
The value of b can't be 0

D. Subhashini,Sr. Assist Prof CS


dept
98

Modules
A python module can be defined as a python program file which contains a
python code including python functions, class, or variables. In other words, we
can say that our python code file saved with the extension (.py) is treated as the
module. We may have a runnable code inside the python module.

Modules in Python provides us the flexibility to organize the code in a logical way.

To use the functionality of one module into another, we must have to import the
specific module.

Example
In this example, we will create a module named as [Link] which contains a
function func that contains a code to print some message on the console.

Let's create the module named as [Link].

#displayMsg prints a message to the name being passed.


def displayMsg(name)
print("Hi "+name);

Here, we need to include this module into our main module to call the method
displayMsg() defined in the module named file.

Loading the module in our python code

We need to load the module in our python code to use its functionality. Python
provides two types of statements as defined below.

1. The import statement


2. The from-import statement

The import statement

The import statement is used to import all the functionality of one module into
another. Here, we must notice that we can use the functionality of any python
source file by importing that file as the module into another python source file.

We can import multiple modules with a single import statement, but a module is
loaded once regardless of the number of times, it has been imported into our file.

D. Subhashini,Sr. Assist Prof CS


dept
99

The syntax to use the import statement is given below.

import module1,module2, ............................. module n

Hence, if we need to call the function displayMsg() defined in the file [Link], we
have to import that file as a module into our module as shown in the example
below.

Example:

import file;
name = input("Enter the name?") [Link](name)

Output:

Enter the
name?John Hi John

The from-import statement

Instead of importing the whole module into the namespace, python provides the
flexibility to import only the specific attributes of a module. This can be done by
using from? import statement. The syntax to use the from-import statement is
given below.

from < module-name> import <name 1>, <name 2>..,<name n>

Consider the following module named as calculation which contains three


functions as summation, multiplication, and divide.

[Link]:

#place the code in the [Link]


def summation(a,b):
return a+b
def multiplication(a,b):
return a*b;
def divide(a,b):
return a/b;

D. Subhashini,Sr. Assist Prof CS


dept
100

[Link]:

from calculation import summation


#it will import only the summation() from [Link]
a = int(input("Enter the first number"))
b = int(input("Enter the second number"))
print("Sum = ",summation(a,b)) #we do not need to specify the module name while
accessing summation()

Output:

Enter the first


number10 Enter the
second number20 Sum =
30

The from...import statement is always better to use if we know the attributes to be


imported from the module in advance. It doesn't let our code to be heavier. We can also
import all the attributes from a module by using *.

Consider the following syntax.

from <module> import *

Renaming a module

Python provides us the flexibility to import some module with a specific name so that we
can use this name to use that module in our python source [Link] syntax to rename a
module is given below.

import <module-name> as <specific-name>

Example

#the module calculation of previous example is imported in this example as cal.


import calculation as cal;
a = int(input("Enter a?")); b = int(input("Enter b?"));
print("Sum = ",[Link](a,b))

D. Subhashini,Sr. Assist Prof CS


dept
101

Output:

Enter
a?10
Enter
b?20 Sum
= 30

Math Module
Python math module is defined as the most famous mathematical functions, which
includes trigonometric functions, representation functions, logarithmic functions, etc.
Furthermore, it also defines two mathematical constants, i.e., Pie and Euler number,
etc.

Pie (n): It is a well-known mathematical constant and defined as the ratio of


circumstance to the diameter of a circle. Its value is 3.141592653589793.

Euler's number(e): It is defined as the base of the natural logarithmic, and its value is
2.718281828459045.

There are different math modules which are given below:

[Link]()
This method returns the natural logarithm of a given number. It is calculated to the base
e.

Example

import math
x=
number = 2e-7 # small value of of x
print('log(fabs(x), base) is :', [Link]([Link](number), 10))

Output:

log(fabs(x), base) is : -6.698970004336019

math.log10()
This method returns base 10 logarithm of the given number and called the standard
logarithm.

D. Subhashini,Sr. Assist Prof CS


dept
102

Example

import math
x=13 # small value of of x
print('log10(x) is :', math.log10(x))

Output:

log10(x) is : 1.1139433523068367

[Link]()
This method returns a floating-point number after raising e to the given number.

Example

import math
number = 5e-2 # small value of of x
print('The given number (x) is :', number)
print('e^x (using exp() function) is :', [Link](number)-1)

Output:

The given number (x) is : 0.05


e^x (using exp() function) is : 0.05127109637602412

[Link](x,y)
This method returns the power of the x corresponding to the value of y. If value of x is
negative or y is not integer value than it raises a ValueError.

Example

import math
number = [Link](10,2)
print("The power of number:",number)

Output:

The power of number: 100.0

D. Subhashini,Sr. Assist Prof CS


dept
103

[Link](x)
This method returns the floor value of the x. It returns the less than or equal value to x.

Example:

import math
number = [Link](10.7 5201)
print("The floor value is:",number)

Output: The floor value is: 10

[Link](x)
This method returns the ceil value of the x. It returns the greater than or equal value to
x.

import math
number = [Link](10.25201)
print("The floor value is:",number)

Output:

The floor value is: 11

[Link](x)
This method returns the absolute value of x.

import math
number = [Link](10.001)
print("The floor absolute is:",number)

Output:

The absolute value is: 10.001

[Link]()
This method returns the factorial of the given number x. If x is not integral, it raises a
ValueError.

D. Subhashini,Sr. Assist Prof CS


dept
104

Example

import math
number = [Link](7)
print("The factorial of number:",number)

Output:

The factorial of number: 5040

[Link](x)
This method returns the fractional and integer parts of x. It carries the sign of x is float.

Example

import math
number = [Link](44.5)
print("The modf of number:",number)

Output:

The modf of number: (0.5, 44.0)

Python provides the several math modules which can perform the complex task in
single- line of code.

D. Subhashini,Sr. Assist Prof CS


dept
105

What is Threading?
A single process can consist of multiple threads each thread in a program performs a
particular task.

Example: In the game, a game as a whole is a single process but it consists of several threads
responsible for playing music taking input from the user and running the opponent, etc. All
these are the separate tasks that are managed by threads.

one program with multiple threads

Just like multiprocessing, multithreading is a way of achieving multitasking. Inmultithreading, the


concept of threads is used.

Thread
In computing, a process is an instance of a computer program that is being executed. Any
process has 3 basic components:
 An executable program.

 The associated data needed by the program (variables, work space, buffers, etc.)
 The execution context of the program (State of process)

A thread is an entity within a process that can be scheduled for execution. Also, it isthe smallest
unit of processing that can be performed in an OS (Operating System).

In simple words, a thread is a sequence of such instructions within a program that can be
executed independently of other code. For simplicity, you can assume that a thread is simply a
subset of a process!

D. Subhashini,Sr. Assist Prof CS


dept
106

A thread contains all this information in a Thread Control Block (TCB):

 Thread Identifier: Unique id (TID) is assigned to every new thread

 Stack pointer: Points to thread’s stack in the process. Stack contains the local
variables under thread’s scope.
 Program counter: a register which stores the address of the instruction currently
being executed by thread.
 Thread state: can be running, ready, waiting, start or done.
 Thread’s register set: registers assigned to thread for computations.

 Parent process Pointer: A pointer to the Process control block (PCB) of theprocess
that the thread lives on.

Consider the diagram below to understand the relation between process and its thread:

Multithreading

Multiple threads can exist within one process where:

 Each thread contains its own register set and local variables (stored in stack).
 All thread of a process share global variables (stored in heap) and
the program code.

Consider the diagram below to understand how multiple threads exist in memory:

D. Subhashini,Sr. Assist Prof CS


dept
107

Multithreading is defined as the ability of a processor to execute multiple threads


concurrently.
In a simple, single-core CPU, it is achieved using frequent switching between threads. This is
termed as context switching. In context switching, the state of a thread is saved and state of
another thread is loaded whenever any interrupt (due to I/O or manually set) takes place.
Context switching takes place so frequently that all the threads appear to be running parallelly
(this is termed as multitasking).

Consider the diagram below in which a process contains two active threads:

Multithreading in Python
In Python, the threading module provides a very simple and intuitive API for spawning
multiple threads in a program.

There are two different kinds of threads:

 kernel thread

 user thread

D. Subhashini,Sr. Assist Prof CS


dept
108

Kernel Threads are a part of the operating system, while the User-space threads are not
implemented in the kernel.

There are two modules which support the usage of threads in Python3:

 _thread

 threading

The thread module has been "deprecated" for quite a long time. Users are encouraged to
use the threading module instead. Hence, in Python 3, the module "thread" is not available
anymore. However, it has been renamed to "_thread" for backwards compatibilities in
Python3.

Starting a New Thread


To spawn another thread, you need to call the following method available in the thread
module:

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

This method call enables a fast and efficient way to create new threads in both Linuxand
Windows.

The method call returns immediately and the child thread starts and calls function with the
passed list of args. When the function returns, the thread terminates.

Here, args is a tuple of arguments; use an empty tuple to call function without passing
any arguments. kwargs is an optional dictionary of keyword arguments.

Example

import _thread
import time

# Define a function for the thread


def print_time( threadName, delay):
count = 0
while count < 5:
[Link](delay)
count += 1
print ("%s: %s" % ( threadName, [Link]([Link]())
))

# Create two threads as follows

D. Subhashini,Sr. Assist Prof CS


dept
109

try:

_thread.start_new_thread( print_time, ("Thread-1", 2, ) )


_thread.start_new_thread( print_time, ("Thread-2", 4, ) )

except:

print ("Error: unable to start thread")

while 1:
pass

Output
When the above code is executed, it produces the following result −

Thread-1: Fri Feb 16 09:41:39 2024


Thread-2: Fri Feb 16 09:41:41 2024
Thread-1: Fri Feb 16 09:41:41 2024
Thread-1: Fri Feb 16 09:41:43 2024
Thread-2: Fri Feb 16 09:41:45 2024
Thread-1: Fri Feb 16 09:41:45 2024
Thread-1: Fri Feb 16 09:41:47 2024
Thread-2: Fri Feb 16 09:41:49 2024
Thread-2: Fri Feb 16 09:41:53 2024
Program goes in an infinite loop. Press ctrl-c to stop

Although it is very effective for low-level threading, the thread module is very limited
compared to the newer threading module.

The Threading Module


The newer threading module included with Python 2.4 provides much more powerful,
high-level support for threads than the thread module. The threading
module exposes all the methods of the thread module and provides some additional
methods:
 [Link]() − Returns the number of thread objects that are
active.
 [Link]() − Returns the current thread objects in the
caller's thread control.
 [Link]() − Returns a list of all thread objects that are currently
active.
In addition to the methods, the threading module has the Thread class thatimplements
threading. The methods provided by the Thread class are as follows:
 run() − The run() method is the entry point for a thread.

D. Subhashini,Sr. Assist Prof CS


dept
110

 start() − The start() method starts a thread by calling the run method.
 join([time]) − The join() waits for threads to terminate.
 isAlive() − The isAlive() method checks whether a thread is still executing.
 getName() − The getName() method returns the name of a thread.
 setName() − The setName() method sets the name of a thread.

Creating Thread Using Threading Module


To implement a new thread using the threading module, you have to do thefollowing:
 Define a new subclass of the Thread class.
 Override the init (self [,args]) method to add additional arguments.
 Then, override the run(self [,args]) method to implement what the thread should do
when started.
Once you have created the new Thread subclass, you can create an instance of it and then
start a new thread by invoking the start(), which in turn calls the run() method.

Creating Multithreading in Python


import time
import threading

def calc_square(number):
print("Calculate square numbers: ")
for i in numbers:
[Link](0.2) #artificial time-delay
print('square: ', str(n*n))

def calc_cube(number):
print("Calculate cude numbers: ")
for i in numbers:
[Link](0.2)
print('cube: ', str(n*n*n))

arr = [2,3,8,9]
t = [Link]()
t1 = [Link](target = cal_square,args=(arr,))
t2 = [Link](target = cal_cube,args=(arr,))

# creating two threads here t1 & t2


[Link]()
[Link]()
# starting threads here parallelly by using start function.

[Link]()

D. Subhashini,Sr. Assist Prof CS


dept
111

# this join() will wait until the cal_square() function is finised.


[Link]()
# this join() will wait unit the cal_cube() function is
[Link]("Successed!")

Let us try to understand the above code:


 To import the threading module, we do:
import threading

 To create a new thread, we create an object of Thread class. It takes following arguments:
 target: the function to be executed by thread
 args: the arguments to be passed to the target function
 To start a thread, we use start method of Thread class.
[Link]()
[Link]()
 Once the threads start, the current program (you can think of it like a main thread) also
keeps on executing. In order to stop execution of current program until a thread is
complete, we use join method.
[Link]()
[Link]()
As a result, the current program will first wait for the completion of t1 and then t2. Once,
they are finished, the remaining statements of current program are executed.

Consider the diagram below for a better understanding of how above program works:

D. Subhashini,Sr. Assist Prof CS


dept
112

The reason to use time delay here just to demonstrate that in which scenario multi-
threading could be useful here we are calculating square and then cubes when we are using
a [Link]() here what's happening is CPU idle and is doing nothing for 0.2 sec.
Consider the python program given below in which we print thread name and corresponding
process for each task:

# Python program to illustrate the concept of threading

import threading
import os

def task1():
print("Task 1 assigned to thread: {}".format(threading.current_thread().name))
print("ID of process running task 1: {}".format([Link]()))

def task2():
print("Task 2 assigned to thread: {}".format(threading.current_thread().name))
print("ID of process running task 2: {}".format([Link]()))

if name == " main ":

# print ID of current process


print("ID of process running main program: {}".format([Link]()))

# print name of main thread


print("Main thread name: {}".format(threading.current_thread().name))

# creating threads
t1 = [Link](target=task1, name='t1')
t2 = [Link](target=task2, name='t2')

# starting threads
[Link]()
[Link]()

# wait until all threads finish


[Link]{}
[Link]()

ID of process running main program: 11758


Main thread name: MainThread
Task 1 assigned to thread: t1
ID of process running task 1: 11758
Task 2 assigned to thread: t2
ID of process running task 2: 11758

D. Subhashini,Sr. Assist Prof CS


dept
113

Let us try to understand the above code:


 We use [Link]() function to get ID of current process
As it is clear from the output, the process ID remains same for all threads.

 We use threading.main_thread() function to get the main thread


object. In normal conditions, the main thread is the thread from which
the Python interpreter was started. name attribute of thread object is
used to get the name of thread.

 We use the threading.current_thread() function to get the current


thread object.

The diagram given below clears the above concept:

D. Subhashini,Sr. Assist Prof CS


dept
114

Python Objects Classes


Python is an object-oriented programming language that offers classes, which are a potent
tool for writing reusable code. To describe objects with shared characteristics and
behaviours, classes are utilised. We shall examine Python's ideas of classes and objects in
this article.

Classes in Python:
In Python, a class is a user-defined data type that contains both the data itself and the
methods that may be used to manipulate it. In a sense, classes serve as a template to
create objects. They provide the characteristics and operations that the objects will employ.

Suppose a class is a prototype of a building. A building contains all the details about the
floor, rooms, doors, windows, etc. we can make as many buildings as we want, based on
these details. Hence, the building can be seen as a class, and we can create as many
objects of this class.

Creating Classes in Python


In Python, a class can be created by using the keyword class, followed by the class name.
The syntax to create a class is given below.

Syntax

class ClassName:
#statement_suite

In Python, we must notice that each class is associated with a documentation string which
can be accessed by using <class-name>.__doc__. A class contains a statement suite
including fields, constructor, function, etc. definition.

Example:

Code:

class Person:
def __init__(self, name, age):
# This is the constructor method that is called when creating a new
Person object
# It takes two parameters, name and age, and initializes them as a
ttributes of the object
[Link] = name
[Link] = age
def greet(self):
# This is a method of the Person class that prints a greeting messa
ge
print("Hello, my name is " + [Link])

D. Subhashini,Sr. Assist Prof CS


dept
115

Name and age are the two properties of the Person class. Additionally, it has a function
called greet that prints a greeting.

Objects in Python:
An object is a particular instance of a class with unique characteristics and functions. After a
class has been established, you may make objects based on it. By using the class
constructor, you may create an object of a class in Python. The object's attributes are
initialised in the constructor, which is a special procedure with the name __init__.

Syntax:

# Declare an object of a class


object_name = Class_Name(arguments)
Example:

Code:

class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age
def greet(self):
print("Hello, my name is " + [Link])
# Create a new instance of the Person class and assign it to the variable
person1
person1 = Person("Ayan", 25)
[Link]()

Output:

"Hello, my name is Ayan"

The self-parameter
The self-parameter refers to the current instance of the class and accesses the class
variables. We can use anything instead of self, but it must be the first parameter of any
function which belongs to the class.

_ _init_ _ method
In order to make an instance of a class in Python, a specific function called __init__ is
called. Although it is used to set the object's attributes, it is often referred to as a
constructor.

D. Subhashini,Sr. Assist Prof CS


dept
116

The self-argument is the only one required by the __init__ method. This argument refers to
the newly generated instance of the class. To initialise the values of each attribute
associated with the objects, you can declare extra arguments in the __init__ method.

Class and Instance Variables


All instances of a class exchange class variables. They function independently of any class
methods and may be accessed through the use of the class name. Here's an illustration:

Code:

class Person:
count = 0 # This is a class variable
def __init__(self, name, age):
[Link] = name # This is an instance variable
[Link] = age
[Link] += 1 # Accessing the class variable using the name
of the class
person1 = Person("Ayan", 25)
person2 = Person("Bobby", 30)
print([Link])
Output:
2

Whereas, instance variables are specific to each instance of a class. They are specified
using the self-argument in the __init__ method. Here's an illustration:

Code:

class Person:
def __init__(self, name, age):
[Link] = name # This is an instance variable
[Link] = age
person1 = Person("Ayan", 25)
person2 = Person("Bobby", 30)
print([Link])
print([Link])

Output:
Ayan
30

Class variables are created separately from any class methods and are shared by all class
copies. Every instance of a class has its own instance variables, which are specified in the
__init__ method utilising the self-argument.

D. Subhashini,Sr. Assist Prof CS


dept
117

Python Constructor
A constructor is a special type of method (function) which is used to initialize the instance
members of the class.

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.

Constructors can be of two types.

1. Parameterized Constructor
2. Non-parameterized Constructor

Constructor definition is executed when we create the object of this class. Constructors also
verify that there are enough resources for the object to perform any start-up task.

Creating the constructor in python


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.

Consider the following example to initialize the Employee class attributes.

Example
class Employee:
def __init__(self, name, id):
[Link] = id
[Link] = name
def display(self):
print("ID: %d \nName: %s" % ([Link], [Link]))

emp1 = Employee("John", 101)


emp2 = Employee("David", 102)
# accessing display() method to print employee 1 information
[Link]()
# accessing display() method to print employee 2 information
[Link]()
Output:
ID: 101
Name: John
ID: 102
Name: David

D. Subhashini,Sr. Assist Prof CS


dept
118

Counting the number of objects of a class


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):
[Link] = [Link] + 1
s1=Student()
s2=Student()
s3=Student()
print("The number of students:",[Link])
Output:
The number of students: 3

Python Non-Parameterized Constructor


The non-parameterized constructor uses when we do not want to manipulate the value or
the constructor that has only self as an argument. Consider the following example.

Example
class Student:
# Constructor - non parameterized
def __init__(self):
print("This is non parametrized constructor")
def show(self,name):
print("Hello",name)
student = Student()
[Link]("John")

Python Parameterized Constructor


The parameterized constructor has multiple parameters along with the self. Consider the
following example.

Example
class Student:
# Constructor - parameterized
def __init__(self, name):
print("This is parametrized constructor")
[Link] = name
def show(self):
print("Hello",[Link])
student = Student("John")
[Link]()

Output:
This is parametrized constructor
Hello John

D. Subhashini,Sr. Assist Prof CS


dept
119

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.
Consider the following example.

Example
class Student:
roll_num = 101
name = "Joseph"
def display(self):
print(self.roll_num,[Link])
st = Student()
[Link]()

Output:
101 Joseph

More than One Constructor in Single class


Let's have a look at another scenario, what happen if we declare the two same constructors
in the class.

Example
class Student:
def __init__(self):
print("The First Constructor")
def __init__(self):
print("The second contructor")
st = Student()

Output:
The Second Constructor

In the above code, the object st called the second constructor whereas both have the same
configuration. The first method is not accessible by the st object. Internally, the object of the
class will always call the last constructor if the class has multiple constructors.

Note: The constructor overloading is not allowed in Python.

D. Subhashini,Sr. Assist Prof CS


dept
120

Python built-in class functions


The built-in functions defined in the class are described in the following table.

SN Function Description

It is used to access
1 getattr(obj,name,default) the attribute of the
object.

It is used to set a
particular value to the
2 setattr(obj, name,value)
specific attribute of an
object.

It is used to delete a
3 delattr(obj, name)
specific attribute.

It returns true if the


4 hasattr(obj, name) object contains some
specific attribute.

Example
class Student:
def __init__(self, name, id, age):
[Link] = name
[Link] = id
[Link] = age
# creates the object of the class Student
s = Student("John", 101, 22)
# prints the attribute name of the object s
print(getattr(s, 'name'))
# reset the value of attribute age to 23
setattr(s, "age", 23)
# prints the modified value of age
print(getattr(s, 'age'))
# prints true if the student contains the attribute with name id
print(hasattr(s, 'id'))
# deletes the attribute age
delattr(s, 'age')
# this will give an error since the attribute age has been deleted
print([Link])

D. Subhashini,Sr. Assist Prof CS


dept
121

Output:
John
23
True
AttributeError: 'Student' object has no attribute 'age'

Built-in class attributes


Along with the other attributes, a Python class also contains some built-in class attributes
which provide information about the class.

The built-in class attributes are given in the below table.

SN Attribute Description

It provides the dictionary containing the information about the class


1 __dict__
namespace.

2 __doc__ It contains a string which has the class documentation

3 __name__ It is used to access the class name.

4 __module__ It is used to access the module in which, this class is defined.

5 __bases__ It contains a tuple including all base classes.

Example
class Student:
def __init__(self,name,id,age):
[Link] = name;
[Link] = id;
[Link] = age
def display_details(self):
print("Name:%s, ID:%d, age:%d"%([Link],[Link]))
s = Student("John",101,22)
print(s.__doc__)
print(s.__dict__)
print(s.__module__)

Output:
None
{'name': 'John', 'id': 101, 'age': 22}
__main__

D. Subhashini,Sr. Assist Prof CS


dept
122

Python Inheritance
Inheritance is an important aspect of the object-oriented paradigm. Inheritance provides
code reusability to the program because we can use an existing class to create a new class
instead of creating it from scratch.

In inheritance, the child class acquires the properties and can access all the data members
and functions defined in the parent class. A child class can also provide its specific
implementation to the functions of the parent class. In this section of the tutorial, we will
discuss inheritance in detail.

In python, a derived class can inherit base class by just mentioning the base in the bracket
after the derived class name. Consider the following syntax to inherit a base class into the
derived class.

Syntax
class derived-class(base class):
<class-suite>

A class can inherit multiple classes by mentioning all of them inside the bracket. Consider
the following syntax.

Syntax
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()
[Link]()
[Link]()

Output:
dog barking
Animal Speaking

D. Subhashini,Sr. Assist Prof CS


dept
123

Python Multi-Level inheritance


Multi-Level inheritance is possible in python like other object-oriented languages. 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.

The syntax of multi-level inheritance is given below.

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

Output:
dog barking
Animal Speaking
Eating bread...

D. Subhashini,Sr. Assist Prof CS


dept
124

Python Multiple inheritance


Python provides us the flexibility to inherit multiple base classes in the child class.

The syntax to perform multiple inheritance is given below.

Syntax
class Base1:
<class-suite>
class Base2:
<class-suite>
.
.
.
class BaseN:
<class-suite>
class Derived(Base1, Base2, ...... 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([Link](10,20))
print([Link](10,20))
print([Link](10,20))

Output:
30
200
0.5

D. Subhashini,Sr. Assist Prof CS


dept
125

The issubclass(sub,sup) method


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

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(issubclass(Derived,Calculation2))
print(issubclass(Calculation1,Calculation2))

Output:
True
False

The isinstance (obj, class) method


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

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(isinstance(d,Derived))

Output:
True

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

D. Subhashini,Sr. Assist Prof CS


dept
126

Example
class Animal:
def speak(self):
print("speaking")
class Dog(Animal):
def speak(self):
print("Barking")
d = Dog()
[Link]()

Output:
Barking

Real Life Example of method overriding


class Bank:
def getroi(self):
return 10;
class SBI(Bank):
def getroi(self):
return 7;
class ICICI(Bank):
def getroi(self):
return 8;
b1 = Bank()
b2 = SBI()
b3 = ICICI()
print("Bank Rate of interest:",[Link]());
print("SBI Rate of interest:",[Link]());
print("ICICI Rate of interest:",[Link]());
Output:
Bank Rate of interest: 10
SBI Rate of interest: 7
ICICI Rate of interest: 8

Data abstraction in python


Abstraction is an important aspect of object-oriented programming. In python, we can also
perform data hiding by adding the double underscore (___) as a prefix to the attribute which
is to be hidden. After this, the attribute will not be visible outside of the class through the
object.

Example
class Employee:
__count = 0;
def __init__(self):
Employee.__count = Employee.__count+1
def display(self):
print("The number of employees",Employee.__count)
emp = Employee()
emp2 = Employee()
try:
print(emp.__count)
finally:
[Link]()

D. Subhashini,Sr. Assist Prof CS


dept
127

Output:
The number of employees 2
AttributeError: 'Employee' object has no attribute '__count'

D. Subhashini,Sr. Assist Prof CS


dept

You might also like