Python Final Notes

Download as pdf or txt
Download as pdf or txt
You are on page 1of 119

CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

DONBOSCO COLLEGE
Kottiyam,Kollam,Kerala
(Affiliated to the University of Kerala)

CP1442: WEB PROGRAMMING & PYTHON


S4 BCA (2018 Admission onwards)

Name : ……………………………………………………………………………………………

Reg : ……………………………………………………………….

Don Bosco College, Kottiyam 1


CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

Module III: Introduction to Python - Features of Python - Identifiers - Reserved


Keywords -Variables Comments in Python – Input , Output and Import Functions -
Operators – Data Types and Operations – int, float, complex, Strings, List, Tuple,
Set, Dictionary - Mutable and Immutable Objects – Data Type Conversion -
Illustrative programs: selection sort, insertion sort, bubble sort

Module IV: Decision Making -conditional (if), alternative (if-else), if..elif..else -


nested if - Loops for, range() while, break, continue, pass; Functions: return values,
parameters, local and global scope, function composition, recursion; Strings: string
slices, immutability, string functions and methods, string module; Lists as arrays.

Python
Python is a simple, general purpose, high level, and object-oriented programming
language.

Python is an interpreted scripting language also. Guido Van Rossum is known as


the founder of Python programming.
• Python is a general purpose, dynamic, high-leveland interpreted
programming language. It supports Object Oriented programming approach
to develop applications. It is simple and easy to learn and provides lots of
high-level data structures.
• Python is easy to learn yet powerful and versatile scripting language, which
makes it attractive for Application Development.
• Python's syntax and dynamic typing with its interpreted nature make it an
ideal language for scripting and rapid application development.
• Python supports multiple programming pattern, including object-oriented,
imperative, and functional or procedural programming styles.
• Python is not intended to work in a particular area, such as web
programming. it is known as multipurpose programming language because it
can be used with web, enterprise, 3D CAD, etc.
• No need to use data types to declare variable because it is dynamically typed
so as to write a=10 to assign an integer value in an integer variable.
• Python makes the development and debugging fast because there is no
compilation step included in Python development, and edit-test-debug cycle
is very fast.
Few-essential feature of Python.
• Easy to use and Learn
• Expressive Language
• Interpreted Language
• Object-Oriented Language

Don Bosco College, Kottiyam 2


CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

• Open Source Language


• Extensible
• Learn Standard Library
• GUI Programming Support
• Integrated
• Embeddable
• Dynamic Memory Allocation
• Wide Range of Libraries and Frameworks

Python is a general-purpose, popular programming language and it is used in


almost every technical field. The various areas of Python use are given below.

• Data Science
• Date Mining
• Desktop Applications
• Console-based Applications
• Mobile Applications
• Software Development
• Artificial Intelligence
• Web Applications
• Enterprise Applications
• 3D CAD Applications
• Machine Learning
• Computer Vision or Image Processing Applications.
• Speech Recognitions

Python provides us the two ways to run a program:

• Using Interactive interpreter prompt


• Using a script file

Interactive interpreter prompt


Python provides the feature to execute the Python statement one by one at the
interactive prompt. The interpreter prompt is best to run the single-line statements
of the code.

Using a script file (Script Mode Programming)


Using the script mode multiple lines code into a file which can be executed later.
For this purpose, open an editor like notepad, create a file named and save it with
.py extension, which stands for "Python".
Basic Syntax of Python
Don Bosco College, Kottiyam 3
CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

Indentation and Comment in Python


Indentation is the most significant concept of the Python programming language.
Improper use of indentation will end up "IndentationError" in the code.

Indentation is nothing but adding whitespaces before the statement when it is


needed. Without indentation Python doesn't know which statement to be executed
next. Indentation also defines which statements belong to which block. If there is
no indentation or improper indentation, it will display "IndentationError" and
interrupt our code.

Comments in Python

Types of Comment
Python provides the facility to write comments in two ways- single line comment
and multi-line comment.

Single-Line Comment - Single-Line comment starts with the hash # character


followed by text for further explanation.
Multi-Line Comments - Python doesn't have explicit support for multi-line
comments but can use hash # character to the multiple lines. For example –
"""
This is an example
Of multi-line comment
Using triple-quotes
"""

Python Identifiers
Python identifiers refer to a name used to identify a variable, function, module,
class, module or other objects. There are few rules to follow while naming the
Python Variable.

• A variable name must start with either an English letter or underscore (_).
• A variable name cannot start with the number.
• Special characters are not allowed in the variable name.
• The variable's name is case sensitive.

Python Variables
Variable is a name that is used to refer to memory location. Python variable is also
known as an identifier and used to hold value. In Python, no need to specify the
type of variable because Python is a infer language and smart enough to get
variable type. Variable names can be a group of both the letters and digits, but they
have to begin with a letter or an underscore.

Don Bosco College, Kottiyam 4


CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

It is recommended to use lowercase letters for the variable name. Rahul and rahul
both are two different variables.

Identifier Naming
Variables are the example of identifiers. An Identifier is used to identify the literals
used in the program. The rules to name an identifier are given below.

• The first character of the variable must be an alphabet or underscore ( _ ).


• All the characters except the first character may be an alphabet of lower-
case(a-z), upper-case (A-Z), underscore, or digit (0-9).
• Identifier name must not contain any white-space, or special character (!, @,
#, %, ^, &, *).
• Identifier name must not be similar to any keyword defined in the language.
• Identifier names are case sensitive; for example, my name, and MyName is
not the same.
• Examples of valid identifiers: a123, _n, n_9, etc.
• Examples of invalid identifiers: 1a, n%4, n 9, etc.

Declaring Variable and Assigning Values


Python does not need declare a variable before using it in the application. It allows
to create a variable at the required time.

When any value to the variable, that variable is declared automatically.

The equal (=) operator is used to assign value to a variable.

Object References
It is necessary to understand how the Python interpreter works when we declare a
variable. The process of treating variables is somewhat different from many other
programming languages.

Python is the highly object-oriented programming language; that's why every data
item belongs to a specific type of class.
In Python, every created object identifies uniquely in Python. Python provides the
guaranteed that no two objects will have the same identifier. The built-in id()
function, is used to identify the object identifier. Consider the following example.
a = 50
b=a
print(id(a))
print(id(b))
# Reassigned variable a
a = 500
Don Bosco College, Kottiyam 5
CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

print(id(a))
Variable Names
Variable names can be any length can have uppercase, lowercase (A to Z, a to z),
the digit (0-9), and underscore character(_). Consider the following example of
valid variables names.
Eg: 1
age = 20
marks = 80.50

print(name)
print(age)
print(marks)

Eg: 2

name = "A"
Name = "B"
naMe = "C"
NAME = "D"
n_a_m_e = "E"
_name = "F"
name_ = "G"
_name_ = "H"
na56me = "I"

print(name,Name,naMe,NAME,n_a_m_e, NAME, n_a_m_e, _name,


name_,_name, na56me)

Multiple Assignment
Python allows to assign a value to multiple variables in a single statement, which is
also known as multiple assignments.
1. Assigning single value to multiple variables

Eg:

x=y=z=50
print(x)
print(y)
print(z)
2. Assigning multiple values to multiple variables:

Eg:
Don Bosco College, Kottiyam 6
CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

a,b,c=5,10,15
print a
print b
print c
Python Variable Types
There are two types of variables in Python - Local variable and Global variable.
Local Variable
Local variables are the variables that declared inside the function and have scope
within the function.

Global Variables
Global variables can be used throughout the program, and its scope is in the entire
program. Global variables can be used inside or outside the function.

A variable declared outside the function is the global variable by default. Python
provides the global keyword to use global variable inside the function. If the global
keyword is not don't used, the function treats it as a local variable.

Delete a variable
To delete the variable del keyword is used. The syntax is given below.
Syntax - del <variable_name>
Print Single and Multiple Variables in Python
We can print multiple variables within the single print statement. Below are the
example of single and multiple printing values.
Example - 1 (Printing Single Variable)

# printing single value


a=5
print(a)
print((a))

Example - 2 (Printing Multiple Variables)

a=5
b=6
# printing multiple variables
print(a,b)
# separate the variables by the comma
Print(1, 2, 3, 4, 5, 6, 7, 8)
Don Bosco College, Kottiyam 7
CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

Basic Fundamentals:
The fundamentals of Python, such as:

i)Tokens and their types.


ii) Comments

a)Tokens:
• The tokens can be defined as a punctuator mark, reserved words, and each
word in a statement.
• The token is the smallest unit inside the given program.
There are following tokens in Python:
• Keywords.
• Identifiers.
• Literals.
• Operators.

Python Data Types


Variables can hold values, and every value has a data-type. Python is a
dynamically typed language; The interpreter implicitly binds the value with its
type.
The variable a holds integer value five and we did not define its type. Python
interpreter will automatically interpret variables a as an integer type.
Python enables to check the type of the variable used in the program. Python
provides the type() function, which returns the type of the variable passed.
a=10
b="Hi Python"
c = 10.5
print(type(a))
print(type(b))
print(type(c))

Standard data types


A variable can hold different types of values. For example, a person's name must
be stored as a string whereas its id must be stored as an integer.

Python provides various standard data types that define the storage method on each
of them. The data types defined in Python are given below.
1. Numbers
2. Sequence Type
3. Boolean
4. Set
5. Dictionary

Don Bosco College, Kottiyam 8


CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

Numbers
Number stores numeric values. The integer, float, and complex values belong to a
Python Numbers data-type. Python provides the type() function to know the data-
type of the variable. Similarly, the isinstance() function is used to check an object
belongs to a particular class.

Python creates Number objects when a number is assigned to a variable. For


example;
a=5
print("The type of a", type(a))
b = 40.5
print("The type of b", type(b))
c = 1+3j
print("The type of c", type(c))
print(" c is a complex number", isinstance(1+3j,complex))

1. Int - Integer value can be any length such as integers 10, 2, 29, -20, -150 etc.
Python has no restriction on the length of an integer. Its value belongs to int
2. Float - Float is used to store floating-point numbers like 1.9, 9.902, 15.2,
etc. It is accurate upto 15 decimal points.
3. complex - A complex number contains an ordered pair, i.e., x + iy where x
and y denote the real and imaginary parts, respectively. The complex
numbers like 2.14j, 2.0 + 2.3j, etc.

Sequence Type
String
The string can be defined as the sequence of characters represented in the quotation
marks. In Python, we can use single, double, or triple quotes to define a string.
String handling in Python is a straightforward task since Python provides built-in
functions and operators to perform operations in the string.
Don Bosco College, Kottiyam 9
CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

In the case of string handling, the operator + is used to concatenate two strings as
the operation "hello"+" python" returns "hello python".

The operator * is known as a repetition operator as the operation "Python" *2


returns 'Python Python'.

Sequence Type
String
The string can be defined as the sequence of characters represented in the quotation
marks. In Python, we can use single, double, or triple quotes to define a string.

String handling in Python is a straightforward task since Python provides built-in


functions and operators to perform operations in the string.

In the case of string handling, the operator + is used to concatenate two strings as
the operation "hello"+" python" returns "hello python".

The operator * is known as a repetition operator as the operation "Python" *2


returns 'Python Python'.
str1 = 'hello python' #string str1
str2 = ' how are you' #string str2
print (str1[0:2]) #printing first two character using slice operator
print (str1[4]) #printing 4th character of the string
print (str1*2) #printing the string twice
print (str1 + str2) #printing the concatenation of str1 and str2

List
Python Lists are similar to arrays in C.The list can contain data of different types.
The items stored in the list are separated with a comma (,) and enclosed within
square brackets [].

slice [:] is used with operators to access the data of the list. The concatenation
operator (+) and repetition operator (*) works with the list in the same way as they
were working with the strings.
list1 = [1, "hi", "Python", 2]
#Checking type of given list
print(type(list1))
#Printing the list1
print (list1)
# List slicing
print (list1[3:])

Don Bosco College, Kottiyam 10


CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

# List slicing
print (list1[0:2])
# List Concatenation using + operator
print (list1 + list1)
# List repetation using * operator
print (list1 * 3)

Tuple
A tuple is similar to the list in many ways. Like lists, tuples also contain the
collection of the items of different data types. The items of the tuple are separated
with a comma (,) and enclosed in parentheses ().

A tuple is a read-only data structure and can't modify the size and value of the
items of a tuple.
tup = ("hi", "Python", 2)
# Checking type of tup
print (type(tup))
#Printing the tuple
print (tup)
# Tuple slicing
print (tup[1:])
print (tup[0:1])
# Tuple concatenation using + operator
print (tup + tup)
# Tuple repatation using * operator
print (tup * 3)
# Adding value to tup. It will throw an error.
t[2] = "hi"

Dictionary
Dictionary is an unordered set of a key-value pair of items. It is like an associative
array or a hash table where each key stores a specific value. Key can hold any
primitive data type, whereas value is an arbitrary Python object.

The items in the dictionary are separated with the comma (,) and enclosed in the
curly braces {}.
d = {1:'Jimmy', 2:'Alex', 3:'john', 4:'mike'}

# Printing dictionary
print (d)

# Accesing value using keys

Don Bosco College, Kottiyam 11


CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

print("1st name is "+d[1])


print("2nd name is "+ d[4])

print (d.keys())
print (d.values())

Boolean
Boolean type provides two built-in values, True and False. These values are used
to determine the given statement true or false. It denotes by the class bool. True
can be represented by any non-zero value or 'T' whereas false can be represented
by the 0 or 'F'. Consider the following example.
# Python program to check the boolean type
print(type(True))
print(type(False))
print(false)

Set
Python Set is the unordered collection of the data type. It is iterable, mutable(can
modify after creation), and has unique elements. In set, the order of the elements is
undefined; it may return the changed sequence of the element. The set is created by
using a built-in function set(), or a sequence of elements is passed in the curly
braces and separated by the comma. It can contain various types of values.
Consider the following example.
# Creating Empty set
set1 = set()
set2 = {'James', 2, 3,'Python'}
#Printing Set value
print(set2)
# Adding element to the set
set2.add(10)
print(set2)
#Removing element from the set
set2.remove(2)
print(set2)

Python Keywords
Python Keywords are special reserved words that convey a special meaning to the
compiler/interpreter. Each keyword has a special meaning and a specific operation.
These keywords can't be used as a variable.
Consider the following explanation of keywords.

True - It represents the Boolean true, if the given condition is true, then it returns
"True". Non-zero values are treated as true.
Don Bosco College, Kottiyam 12
CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

False - It represents the Boolean false; if the given condition is false, then it returns
"False". Zero value is treated as false
None - It denotes the null value or void. An empty list or Zero can't be treated as
None.
and - It is a logical operator. It is used to check the multiple conditions. It returns
true if both conditions are true.
or - It is a logical operator in Python. It returns true if one of the conditions is true
not - It is a logical operator and inverts the truth value.
assert - This keyword is used as the debugging tool in Python. It checks the
correctness of the code. It raises an AssertionError if found any error in the code
and also prints the message with an error.

a = 10
b=0
print('a is dividing by Zero')
assert b != 0
print(a / b)
def - This keyword is used to declare the function in Python.

def my_func(a,b):
c = a+b
print(c)
my_func(10,20)

class - It is used to represents the class in Python. The class is the blueprint of the
objects. It is the collection of the variable and methods.
class Myclass:
#Variables……..
def function_name(self):
#statements………
continue - It is used to stop the execution of the current iteration.
a=0
while a < 4:
a += 1
if a == 2:
continue
print(a)

break - It is used to terminate the loop execution and control transfer to the end of
the loop.
for i in range(5):
if(i==3):
Don Bosco College, Kottiyam 13
CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

break
print(i)
print("End of execution")

If - It is used to represent the conditional statement. The execution of a particular


block is decided by if statement.

i = 18
if (1 < 12):
print("I am less than 18")

else - The else statement is used with the if statement. When if statement returns
false, then else block is executed. Consider the following example.
n = 11
if(n%2 == 0):
print("Even")
else:
print("odd")

elif - This Keyword is used to check the multiple conditions. It is short for else-if.
If the previous condition is false, then check until the true condition is found.
Condition the following example.

marks = int(input("Enter the marks:"))


if(marks>=90):
print("Excellent")
elif(marks<90 and marks>=75):
print("Very Good")
elif(marks<75 and marks>=60):
print("Good")
else:
print("Average")

del - It is used to delete the reference of the object. Consider the following
example.

a=10
b=12
del a
print(b)
# a is no longer exist
print(a)
Don Bosco College, Kottiyam 14
CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

try, except - The try-except is used to handle the exceptions. The exceptions are
run-time errors. Consider the following example.

a=0
try:
b = 1/a
except Exception as e:
print(e)

raise - The raise keyword is used to through the exception forcefully. Consider the
following example.

a=5
if (a>2):
raise Exception('a should not exceed 2 ')

finally - The finally keyword is used to create a block of code that will always be
executed no matter the else block raises an error or not. Consider the following
example.

a=0
b=5
try:
c = b/a
print(c)
except Exception as e:
print(e)
finally:
print('Finally always executed')

for, while - Both keywords are used for iteration. The for keyword is used to
iterate over the sequences (list, tuple, dictionary, string). A while loop is executed
until the condition returns false. Consider the following example.

list = [1,2,3,4,5]
for i in list:
print(i)

While loop

a=0
Don Bosco College, Kottiyam 15
CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

while(a<5):
print(a)
a = a+1

import - The import keyword is used to import modules in the current Python
script. The module contains a runnable Python code.

Example:

import math
print(math.sqrt(25))

from - This keyword is used to import the specific function or attributes in the
current Python script.

Example:

from math import sqrt


print(sqrt(25))

as - It is used to create a name alias. It provides the user-define name while


importing a module.

Example:

import calendar as cal


print(cal.month_name[5])

pass - The pass keyword is used to execute nothing or create a placeholder for
future code. If we declare an empty class or function, it will through an error, so
we use the pass keyword to declare an empty class or function.

Example:

class my_class:
pass

def my_func():
pass

return - The return keyword is used to return the result value or none to called
function.
Don Bosco College, Kottiyam 16
CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

Example:

def sum(a,b):
c = a+b
return c

print("The sum is:",sum(25,15))

is - This keyword is used to check if the two-variable refers to the same object. It
returns the true if they refer to the same object otherwise false. Consider the
following example.

Example

x=5
y=5

a = []
b = []
print(x is y)
print(a is b)

global - The global keyword is used to create a global variable inside the function.
Any function can access the global. Consider the following example.

Example

def my_func():
global a
a = 10
b = 20
c = a+b
print(c)

my_func()

def func():
print(a)

func()

Don Bosco College, Kottiyam 17


CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

nonlocal - The nonlocal is similar to the global and used to work with a variable
inside the nested function(function inside a function). Consider the following
example.

Example

def outside_function():
a = 20
def inside_function():
nonlocal a
a = 30
print("Inner function: ",a)
inside_function()
print("Outer function: ",a)
outside_function()

lambda - The lambda keyword is used to create the anonymous function in


Python. It is an inline function without a name. Consider the following example.

Example

a = lambda x: x**2
for i in range(1,6):
print(a(i))

yield - The yield keyword is used with the Python generator. It stops the function's
execution and returns value to the caller. Consider the following example.

Example

def fun_Generator():
yield 1
yield 2
yield 3

# Driver code to check above generator function


for value in fun_Generator():
print(value)

Python Literals
Python Literals can be defined as data that is given in a variable or constant.
Don Bosco College, Kottiyam 18
CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

Python supports the following literals:

1. String literals:
String literals can be formed by enclosing a text in the quotes. We can use both
single as well as double quotes to create a string.
Types of Strings:

There are two types of Strings supported in Python:

a) Single-line String- Strings that are terminated within a single-line are known as
Single line Strings.

text1='hello'
b) Multi-line String - A piece of text that is written in multiple lines is known as
multiple lines string.

There are two ways to create multiline strings:

1) Adding black slash at the end of each line.

text1='hello\
user'
print(text1)

2) Using triple quotation marks:-

Example:

str2='''''welcome
to
SSSIT'''
print str2

II. Numeric literals:


Numeric Literals are immutable. Numeric literals can belong to following four
different numerical types.

x = 0b10100 #Binary Literals


y = 100 #Decimal Literal
z = 0o215 #Octal Literal
u = 0x12d #Hexadecimal Literal
Don Bosco College, Kottiyam 19
CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

#Float Literal
float_1 = 100.5
float_2 = 1.5e2

#Complex Literal
a = 5+3.14j

print(x, y, z, u)
print(float_1, float_2)
print(a, a.imag, a.real)

III. Boolean literals:


A Boolean literal can have any of the two values: True or False.

x = (1 == True)
y = (2 == False)
z = (3 == True)
a = True + 10
b = False + 10

print("x is", x)
print("y is", y)
print("z is", z)
print("a:", a)
print("b:", b)

IV. Special literals.


Python contains one special literal i.e., None.

None is used to specify to that field that is not created. It is also used for the end of
lists in Python.

Example - Special Literals

val1=10
val2=None
print(val1)
print(val2)

V. Literal Collections.
Don Bosco College, Kottiyam 20
CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

Python provides the four types of literal collection such as List literals, Tuple
literals, Dict literals, and Set literals.
List:
• List contains items of different data types. Lists are mutable i.e.,
modifiable.
• The values stored in List are separated by comma(,) and enclosed within
square brackets([]). We can store different types of data in a List.
Example - List literals

list=['John',678,20.4,'Peter']
list1=[456,'Andrew']
print(list)
print(list + list1)

Dictionary:
• Python dictionary stores the data in the key-value pair.
• It is enclosed by curly-braces {} and each pair is separated by the
commas(,).
Example
dict = {'name': 'Pater', 'Age':18,'Roll_nu':101}
print(dict)

Tuple:

Python tuple is a collection of different data-type. It is immutable which means it


cannot be modified after creation.
It is enclosed by the parentheses () and each element is separated by the comma(,).

tup = (10,20,"Dev",[2,3,4])
print(tup)

Set:
• Python set is the collection of the unordered dataset.
• It is enclosed by the {} and each element is separated by the comma(,).
Example: - Set Literals
set = {'apple','grapes','guava','papaya'}
print(set)

Python Operators
The operator can be defined as a symbol which is responsible for a particular
operation between two operands. Operators are the pillars of a program on which
Don Bosco College, Kottiyam 21
CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

the logic is built in a specific programming language. Python provides a variety of


operators, which are described as follows.

• Arithmetic operators
• Comparison operators
• Assignment Operators
• Logical Operators
• Bitwise Operators
• Membership Operators
• Identity Operators
Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations between two
operands. It includes + (addition), - (subtraction), *(multiplication), /(divide),
%(reminder), //(floor division), and exponent (**) operators.

Consider the following table for a detailed explanation of arithmetic operators.

Operator Description

+ (Addition) It is used to add two operands. For example, if a = 20, b =


10 => a+b = 30

- (Subtraction) It is used to subtract the second operand from the first


operand. If the first operand is less than the second
operand, the value results negative. For example, if a = 20,
b = 10 => a - b = 10

/ (divide) It returns the quotient after dividing the first operand by the
second operand. For example, if a = 20, b = 10 => a/b = 2.0

* It is used to multiply one operand with the other. For


(Multiplication) example, if a = 20, b = 10 => a * b = 200

% (reminder) It returns the reminder after dividing the first operand by


the second operand. For example, if a = 20, b = 10 => a%b
=0

** (Exponent) It is an exponent operator represented as it calculates the


first operand power to the second operand.

// (Floor It gives the floor value of the quotient produced by dividing


division) the two operands.

Don Bosco College, Kottiyam 22


CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

Comparison operator
Comparison operators are used to comparing the value of the two operands and
returns Boolean true or false accordingly. The comparison operators are described
in the following table.

Operator Description

== If the value of two operands is equal, then the condition becomes true.

!= If the value of two operands is not equal, then the condition becomes
true.

<= If the first operand is less than or equal to the second operand, then
the condition becomes true.

>= If the first operand is greater than or equal to the second operand, then
the condition becomes true.

> If the first operand is greater than the second operand, then the
condition becomes true.

< If the first operand is less than the second operand, then the condition
becomes true.

Assignment Operators
The assignment operators are used to assign the value of the right expression to the
left operand. The assignment operators are described in the following table.

Operator Description

= It assigns the value of the right expression to the left operand.

+= It increases the value of the left operand by the value of the right
operand and assigns the modified value back to left operand. For
example, if a = 10, b = 20 => a+ = b will be equal to a = a+ b and
therefore, a = 30.

-= It decreases the value of the left operand by the value of the right
operand and assigns the modified value back to left operand. For
example, if a = 20, b = 10 => a- = b will be equal to a = a- b and
therefore, a = 10.

*= It multiplies the value of the left operand by the value of the right
operand and assigns the modified value back to then the left

Don Bosco College, Kottiyam 23


CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

operand. For example, if a = 10, b = 20 => a* = b will be equal to a


= a* b and therefore, a = 200.

%= It divides the value of the left operand by the value of the right
operand and assigns the reminder back to the left operand. For
example, if a = 20, b = 10 => a % = b will be equal to a = a % b and
therefore, a = 0.

**= a**=b will be equal to a=a**b, for example, if a = 4, b =2, a**=b


will assign 4**2 = 16 to a.

//= A//=b will be equal to a = a// b, for example, if a = 4, b = 3, a//=b


will assign 4//3 = 1 to a.

Bitwise Operators
The bitwise operators perform bit by bit operation on the values of the two
operands. Consider the following example.

Operator Description

& (binary If both the bits at the same place in two operands are 1, then 1
and) is copied to the result. Otherwise, 0 is copied.

| (binary or) The resulting bit will be 0 if both the bits are zero; otherwise,
the resulting bit will be 1.

^ (binary The resulting bit will be 1 if both the bits are different;
xor) otherwise, the resulting bit will be 0.

~ (negation) It calculates the negation of each bit of the operand, i.e., if the
bit is 0, the resulting bit will be 1 and vice versa.

<< (left shift) The left operand value is moved left by the number of bits
present in the right operand.

>> (right The left operand is moved right by the number of bits present in
shift) the right operand.

Logical Operators
The logical operators are used primarily in the expression evaluation to make a
decision. Python supports the following logical operators.

Don Bosco College, Kottiyam 24


CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

Operator Description

and If both the expression are true, then the condition will be true. If a
and b are the two expressions, a → true, b → true => a and b →
true.

or If one of the expressions is true, then the condition will be true. If a


and b are the two expressions, a → true, b → false => a or b →
true.

not If an expression a is true, then not (a) will be false and vice versa.

Membership Operators
Python membership operators are used to check the membership of value inside a
Python data structure. If the value is present in the data structure, then the resulting
value is true otherwise it returns false.

Operator Description

in It is evaluated to be true if the first operand is found in the second


operand (list, tuple, or dictionary).

not in It is evaluated to be true if the first operand is not found in the


second operand (list, tuple, or dictionary).

Identity Operators
The identity operators are used to decide whether an element certain class or type.

Operator Description

is It is evaluated to be true if the reference present at both sides point


to the same object.

is not It is evaluated to be true if the reference present at both sides do not


point to the same object.

Operator Precedence
The precedence of the operators is essential to find out since it enables us to know
which operator should be evaluated first. The precedence table of the operators in
Python is given below.
Don Bosco College, Kottiyam 25
CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

Operator Description

** The exponent operator is given priority over all the others


used in the expression.

~+- The negation, unary plus, and minus.

* / % // The multiplication, divide, modules, reminder, and floor


division.

+- Binary plus, and minus

>><< Left shift. and right shift

& Binary and.

^| Binary xor, and or

<= <>>= Comparison operators (less than, less than equal to, greater
than, greater then equal to).

<> == != Equality operators.

= %= /= //= -= += Assignment operators


*= **=

is is not Identity operators

in not in Membership operators

not or and Logical operators

Taking input in Python


Python provides two inbuilt functions to read the input from the keyboard.

• input ( prompt )
• raw_input ( prompt )
input ( ) : This function first takes the input from the user and convert it into string.
Type of the returned object always will be <type ‘str’>. It does not evaluate the
expression it just return the complete statement as String. For example –
eg:1
# Python program showing
# a use of input()

Don Bosco College, Kottiyam 26


CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

val = input("Enter your value: ")


print(val)

eg:2
# Program to check input
# type in Python

num = input ("Enter number :")


print(num)
name1 = input("Enter name : ")
print(name1)

# Printing type of input value


print ("type of number", type(num))
print ("type of name", type(name1))

raw_input ( ) : This function works in older version (like Python 2.x). This
function takes exactly what is typed from the keyboard, convert it to string and
then return it to the variable in which we want to store. For example –
# Python program showing
# a use of raw_input()

g = raw_input("Enter your name : ")


print g

Here, g is a variable which will get the string value, typed by user during the
execution of program. Typing of data for the raw_input() function is terminated by
enter key. We can use raw_input() to enter numeric data also.

Taking input from console in Python


Console (also called Shell) is basically a command line interpreter that takes input
from the user i.e one command at a time and interprets it. If it is error free then it
runs the command and gives required output otherwise shows the error message.
Accepting Input from Console
User enters the values in the Console and that value is then used in the program as
it was required.
To take input from the user we make use of a built-in function input().

# input
input1 = input()

# output
Don Bosco College, Kottiyam 27
CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

print(input1)

1. Typecasting the input to Integer: There might be conditions when you might
require integer input from user/Console, the following code takes two
input(integer/float) from console and typecasts them to integer then prints the sum.

# input
num1 = int(input())
num2 = int(input())

# printing the sum in integer


print(num1 + num2)

2. Typecasting the input to Float: To convert the input to float the following code
will work out.

# input
num1 = float(input())
num2 = float(input())

# printing the sum in float


print(num1 + num2)

3. Typecasting the input to String: All kind of input can be converted to string
type whether they are float or integer. We make use of keyword str for typecasting.

# input
string = str(input())

# output
print(string)

Taking multiple inputs from user in Python

The developer often wants a user to enter multiple values or inputs in one line. In
C++/C user can take multiple inputs in one line using scanf but in Python user can
take multiple values or inputs in one line by two methods.

• Using split() method


• Using List comprehension
Using split() method :

Don Bosco College, Kottiyam 28


CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

This function helps in getting multiple inputs from users. It breaks the given input
by the specified separator. If a separator is not provided then any white space is a
separator. Generally, users use a split() method to split a Python string but one can
use it in taking multiple inputs.

# Python program showing how to


# multiple input using split

# taking two inputs at a time


x, y = input("Enter two values: ").split()
print("Number of boys: ", x)
print("Number of girls: ", y)
print()

# taking three inputs at a time


x, y, z = input("Enter three values: ").split()
print("Total number of students: ", x)
print("Number of boys is : ", y)
print("Number of girls is : ", z)
print()

# taking two inputs at a time


a, b = input("Enter two values: ").split()
print("First number is {} and second number is {}".format(a, b))
print()

# taking multiple inputs at a time


# and type casting using list() function
x = list(map(int, input("Enter multiple values: ").split()))
print("List of students: ", x)

Using List comprehension :


List comprehension is an elegant way to define and create list in Python. We can
create lists just like mathematical statements in one line only. It is also used in
getting multiple inputs from a user.

# Python program showing


# how to take multiple input
# using List comprehension

Don Bosco College, Kottiyam 29


CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

# taking two input at a time


x, y = [int(x) for x in input("Enter two values: ").split()]
print("First Number is: ", x)
print("Second Number is: ", y)
print()

# taking three input at a time


x, y, z = [int(x) for x in input("Enter three values: ").split()]
print("First Number is: ", x)
print("Second Number is: ", y)
print("Third Number is: ", z)
print()

# taking two inputs at a time


x, y = [int(x) for x in input("Enter two values: ").split()]
print("First number is {} and second number is {}".format(x, y))
print()

# taking multiple inputs at a time


x = [int(x) for x in input("Enter multiple values: ").split()]
print("Number of list is: ", x)

Python | Output using print() function

Python print() function prints the message to the screen or any other standard
output device.

Syntax: print(value(s), sep= ‘ ‘, end = ‘\n’, file=file, flush=flush)

Parameters:

• value(s) : Any value, and as many as you like. Will be converted to string
before printed
• sep=’separator’ : (Optional) Specify how to separate the objects, if there is
more than one.Default :’ ‘
• end=’end’: (Optional) Specify what to print at the end.Default : ‘\n’
• file : (Optional) An object with a write method. Default :sys.stdout
• flush : (Optional) A Boolean, specifying if the output is flushed (True) or
buffered (False). Default: False
• Returns: It returns output to the screen.

Don Bosco College, Kottiyam 30


CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

Though it is not necessary to pass arguments in the print() function, it requires an


empty parenthesis at the end that tells python to execute the function rather calling
it by name.

String Literals

String literals in python’s print statement are primarily used to format or design
how a specific string appears when printed using the print() function.

• \n : This string literal is used to add a new blank line while printing a
statement.

• “” : An empty quote (“”) is used to print an empty line.

end= ” ” statement

The end keyword is used to specify the content that is to be printed at the end of
the execution of the print() function. By default, it is set to “\n”, which leads to the
change of line after the execution of print() statement.

Separator

The print() function can accept any number of positional arguments. These
arguments can be separated from each other using a “,” separator. These are
primarily used for formatting multiple statements in a single print() function.

b = "for"
print("Geeks", b , "Geeks")

Python Comments

Python Comment is an essential tool for the programmers. Comments are generally
used to explain the code. We can easily understand the code if it has a proper
explanation. A good programmer must use the comments because in the future
anyone wants to modify the code as well as implement the new module; then, it
can be done easily.

In the other programming language such as C++, It provides the // for single-lined
comment and /*.... */ for multiple-lined comment, but Python provides the single-
lined Python comment. To apply the comment in the code we use the hash(#) at the
beginning of the statement or code.

Don Bosco College, Kottiyam 31


CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

Multiline Python Comment

We must use the hash(#) at the beginning of every line of code to apply the
multiline Python comment. Consider the following example.
# Variable a holds value 5
# Variable b holds value 10
# Variable c holds sum of a and b
# Print the result
a=5
b = 10
c = a+b
print("The sum is:", c)

Docstrings Python Comment


The docstring comment is mostly used in the module, function, class or method. It
is a documentation Python string. We will explain the class/method in further
tutorials.

def intro():
"""
This function prints Hello Joseph
"""
print("Hi Joseph")
intro()

a function's docstring by using the __doc__ attribute.

Generally, four whitespaces are used as the indentation. The amount of indentation
depends on user, but it must be consistent throughout that block.
def intro():
"""
This function prints Hello Joseph
"""
print("Hello Joseph")
intro.__doc__

Python indentation
Python indentation uses to define the block of the code. The other programming
languages such as C, C++, and Java use curly braces {}, whereas Python uses an
indentation. Whitespaces are used as indentation in Python.

Don Bosco College, Kottiyam 32


CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

Indentation uses at the beginning of the code and ends with the unintended line.
That same line indentation defines the block of the code (body of a function, loop,
etc.)

Generally, four whitespaces are used as the indentation. The amount of indentation
depends on user, but it must be consistent throughout that block.
for i in range(5):
print(i)
if(i == 3):
break

To indicate a block of code we indented each line of the block by the same
whitespaces.
dn = int(input("Enter the number:"))
if(n%2 == 0):
print("Even Number")
else:
print("Odd Number")

print("Task Complete")

Python If-else statements


Decision making is the most important aspect of almost all the programming
languages. As the name implies, decision making allows us to run a particular
block of code for a particular decision. Here, the decisions are made on the validity
of the particular conditions. Condition checking is the backbone of decision
making.

Statement Description

If Statement The if statement is used to test a specific condition. If the


condition is true, a block of code (if-block) will be executed.

If - else Statement The if-else statement is similar to if statement except the fact
that, it also provides the block of the code for the false case of
the condition to be checked. If the condition provided in the if
statement is false, then the else statement will be executed.

Nested if Nested if statements enable us to use if ? else statement inside


Statement an outer if statement.

Indentation in Python
Don Bosco College, Kottiyam 33
CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

For the ease of programming and to achieve simplicity, python doesn't allow the
use of parentheses for the block level code. In Python, indentation is used to
declare a block. If two statements are at the same indentation level, then they are
the part of the same block.Indentation is the most used part of the python language
since it declares the block of code. All the statements of one block are intended at
the same level indentation.

Generally, four spaces are given to indent the statements which are a typical
amount of indentation in python.
The if statement
The if statement is used to test a particular condition and if the condition is true, it
executes a block of code known as if-block. The condition of if statement can be
any valid logical expression which can be either evaluated to true or false.

The syntax of the if-statement is given below.


if expression:
statement

Example 1
num = int(input("enter the number?"))
if num%2 == 0:
print("Number is even")

Example 2 : Program to print the largest of the three numbers.

a = int(input("Enter a? "));
b = int(input("Enter b? "));
c = int(input("Enter c? "));
if a>b and a>c:
print("a is largest");
if b>a and b>c:
print("b is largest");
if c>a and c>b:

Don Bosco College, Kottiyam 34


CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

print("c is largest");

The if-else statement


The if-else statement provides an else block combined with the if statement which
is executed in the false case of the condition.

If the condition is true, then the if-block is executed. Otherwise, the else-block is
executed.

The syntax of the if-else statement is given below.


if condition:
#block of statements
else:
#another block of statements (else-block)

Example 1 : Program to check whether a person is eligible to vote or not.


age = int (input("Enter your age? "))
if age>=18:
print("You are eligible to vote !!");
else:
print("Sorry! you have to wait !!");

Example 2: Program to check whether a number is even or not.


num = int(input("enter the number?"))
if num%2 == 0:
print("Number is even...")
else:
print("Number is odd...")

The elif statement


The elif statement enables us to check multiple conditions and execute the specific
block of statements depending upon the true condition among them. Any number
of elif statements can be used in the our program depending upon the need.
However, using elif is optional.
Don Bosco College, Kottiyam 35
CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

The elif statement works like an if-else-if ladder statement in C. It must be


succeeded by an if statement.

The syntax of the elif statement is given below.

if expression 1:
# block of statements

elif expression 2:
# block of statements

elif expression 3:
# block of statements

else:
# block of statements

Example 1
number = int(input("Enter the number?"))
if number==10:
print("number is equals to 10")
elif number==50:
print("number is equal to 50");
elif number==100:
print("number is equal to 100");
else:
print("number is not equal to 10, 50 or 100");
Don Bosco College, Kottiyam 36
CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

Example 2
marks = int(input("Enter the marks? "))
f marks > 85 and marks <= 100:
print("Congrats ! you scored grade A ...")
lif marks > 60 and marks <= 85:
print("You scored grade B + ...")
lif marks > 40 and marks <= 60:
print("You scored grade B ...")
lif (marks > 30 and marks <= 40):
print("You scored grade C ...")
lse:
print("Sorry you are fail ?")

Python Loops
The flow of the programs written in any programming language is sequential by
default. Sometimes the flow of the programneed to altered. The execution of a
specific code may need to be repeated several numbers of times.

The looping simplifies the complex problems into the easy ones. It enables us to
alter the flow of the program so that instead of writing the same code again and
again, we can repeat the same code for a finite number of times.

Advantages of loops
There are the following advantages of loops in Python.

1. It provides code re-usability.


2. Using loops, we do not need to write the same code again and again.

Don Bosco College, Kottiyam 37


CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

3. Using loops, we can traverse over the elements of data structures (array or
linked lists).
There are the following loop statements in Python.

Loop Description
Statement

for loop The for loop is used in the case where we need to execute some
part of the code until the given condition is satisfied. The for loop
is also called as a per-tested loop. It is better to use for loop if the
number of iteration is known in advance.

while loop The while loop is to be used in the scenario where we don't know
the number of iterations in advance. The block of statements is
executed in the while loop until the condition specified in the
while loop is satisfied. It is also called a pre-tested loop.

do-while The do-while loop continues until a given condition satisfies. It is


loop also called post tested loop. It is used when it is necessary to
execute the loop at least once (mostly menu driven programs).

Python for loop


The for loop in Python is used to iterate the statements or a part of the program
several times. It is frequently used to traverse the data structures like list, tuple, or
dictionary.
The syntax of for loop in python is given below.

for iterating_var in sequence:


statement(s)

The for loop flowchart

Don Bosco College, Kottiyam 38


CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

Example-1: Iterating string using for loop

str = "Python"
for i in str:
print(i)

Example- 2: Program to print the table of the given number .

list = [1,2,3,4,5,6,7,8,9,10]
n=5
for i in list:
c = n*i
print(c)
Example- 2: Program to print the table of the given number .

list = [1,2,3,4,5,6,7,8,9,10]
n=5
for i in list:
c = n*i
print(c)

Example-4: Program to print the sum of the given list.

list = [10,30,23,43,65,12]
sum = 0
for i in list:
sum = sum+i
print("The sum is:",sum)

For loop Using range() function


The range() function
Don Bosco College, Kottiyam 39
CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

The range() function is used to generate the sequence of the numbers. If we pass
the range(10), it will generate the numbers from 0 to 9. The syntax of the range()
function is given below.

Syntax:range(start,stop,step size)

o The start represents the beginning of the iteration.


o The stop represents that the loop will iterate till stop-1. The range(1,5) will
generate numbers 1 to 4 iterations. It is optional.
o The step size is used to skip the specific numbers from the iteration. It is
optional to use. By default, the step size is 1. It is optional.

Example-1: Program to print numbers in sequence.

for i in range(10):
print(i,end = ' ')
Example - 2: Program to print table of given number.

n = int(input("Enter the number "))


for i in range(1,11):
c = n*i
print(n,"*",i,"=",c)

Example-3: Program to print even number using step size in range().

n = int(input("Enter the number "))


for i in range(2,n,2):
print(i)

the range() function with sequence of numbers. The len() function is combined
with range() function which iterate through a sequence using indexing. Consider
the following example.

list = ['Peter','Joseph','Ricky','Devansh']
for i in range(len(list)):
print("Hello",list[i])

Nested for loop in python


Python allows to nest any number of for loops inside a for loop. The inner loop is
executed n number of times for every iteration of the outer loop. The syntax is
given below.
Don Bosco College, Kottiyam 40
CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

Syntax

for iterating_var1 in sequence: #outer loop


for iterating_var2 in sequence: #inner loop
#block of inner loop statements
#block of outer loop statements

Example- 1: Nested for loop


# User input for number of rows
rows = int(input("Enter the rows:"))
# Outer loop will print number of rows
for i in range(0,rows+1):
# Inner loop will print number of Astrisk
for j in range(i):
print("*",end = '')
print()

Example-2: Program to number pyramid.


rows = int(input("Enter the rows"))
for i in range(0,rows+1):
for j in range(i):
print(i,end = '')
print()

Using else statement with for loop


Unlike other languages like C, C++, or Java, Python allows to use the else
statement with the for loop which can be executed only when all the iterations are
exhausted. Here, we must notice that if the loop contains any of the break
statement then the else statement will not be executed.

Example 1
for i in range(0,5):
print(i)
else:
print("for loop completely exhausted, since there is no break.")

Example 2
for i in range(0,5):
print(i)
break;
else:print("for loop is exhausted");
Don Bosco College, Kottiyam 41
CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

print("The loop is broken due to break statement...came out of the loop")


In the above example, the loop is broken due to the break statement; therefore, the
else statement will not be executed. The statement present immediate next to else
block will be executed.

Python While loop


The Python while loop allows a part of the code to be executed until the given
condition returns false. It is also known as a pre-tested loop.

It can be viewed as a repeating if statement. When the number of iterations are not
know then the while loop is most effective to use.

The syntax is given below.

while expression:
statements
Here, the statements can be a single statement or a group of statements. The
expression should be any valid Python expression resulting in true or false. The
true is any non-zero value and false is 0.
While loop Flowchart

Loop Control Statements


the normal sequence of while loop's execution can be changed using the loop
control statement. When the while loop's execution is completed, all automatic
objects defined in that scope are demolished. Python offers the following control
statement to use within the while loop.

1. Continue Statement - When the continue statement is encountered, the control


transfer to the beginning of the loop.The continue statement skips the remaining
Don Bosco College, Kottiyam 42
CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

lines of code inside the loop and start with the next iteration. It is mainly used for a
particular condition inside the loop so that we can skip some specific code for a
particular condition.The continue statement in Python is used to bring the program
control to the beginning of the loop. The continue statement skips the remaining
lines of code inside the loop and start with the next iteration. It is mainly used for a
particular condition inside the loop so that we can skip some specific code for a
particular condition.

Syntax
#loop statements
continue
#the code to be skipped

Example 1
i=0
while(i < 10):
i = i+1
if(i == 5):
continue
print(i)

In above code, the value 5 is skipped because we have provided the if condition
using with continue statement in while loop. When it matched with the given
condition then control transferred to the beginning of the while loop and it skipped
the value 5 from the code.

Example:

# prints all letters except 'a' and 't'


i=0
str1 = 'pythonlang'

while i < len(str1):


if str1[i] == 'y' or str1[i] == 't':
i += 1
continue
print('Current Letter :', a[i])
i += 1

Don Bosco College, Kottiyam 43


CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

2. Break Statement - When the break statement is encountered, it brings control


out of the loop.The break statement breaks the loops one by one, i.e., in the case of
nested loops, it breaks the inner loop first and then proceeds to outer loops. In other
words, we can say that break is used to abort the current execution of the program
and the control goes to the next line after the loop.

The break is commonly used in the cases where we need to break the loop for a
given condition.

The syntax of the break is given below.

#loop statements
break;

Example 1
list =[1,2,3,4]
count = 1;
for i in list:
if i == 4:
print("item matched")
count = count + 1;
break
print("found at",count,"location");

Example:

# The control transfer is transfered


# when break statement soon it sees t
i=0
str1 = 'python'

while i < len(str1):


if str1[i] == 't':
i += 1
break
print('Current Letter :', str1[i])
i += 1

4. Pass Statement - The pass statement is used to declare the empty loop. It is
also used to define empty class, function, and control statement.

Don Bosco College, Kottiyam 44


CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

The pass statement is a null operation since nothing happens when it is executed. It
is used in the cases where a statement is syntactically needed but don't want to use
any executable statement at its place.

For example, it can be used while overriding a parent class method in the subclass
but don't want to give its specific implementation in the subclass.

Pass is also used where the code will be written somewhere but not yet written in
the program file

Example
list = [1,2,3,4,5]
flag = 0
for i in list:
print("Current element:",i,end=" ");
if i==3:
pass
print("\nWe are inside pass block\n");
flag = 1
if flag==1:
print("\nCame out of pass\n");
flag=0
Example -

# An empty loop
str1 = 'python'
i=0

while i < len(str1):


i += 1
pass
print('Value of i :', i)

Example-1: Program to print 1 to 10 using while loop


i=1
#The while loop will iterate until condition becomes false.
While(i<=10):
print(i)
i=i+1

Example -2: Program to print table of given numbers.


i=1
Don Bosco College, Kottiyam 45
CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

number=0
b=9
number = int(input("Enter the number:"))
while i<=10:
print("%d X %d = %d \n"%(number,i,number*i))
i = i+1

Example 1
list =[1,2,3,4]
count = 1;
for i in list:
if i == 4:
print("item matched")
count = count + 1;
break
print("found at",count,"location");

Example 2
str = "python"
for i in str:
if i == 'o':
break
print(i);

Example 3: break statement with while loop


i = 0;
while 1:
print(i," ",end=""),
i=i+1;
if i == 10:
break;
print("came out of while loop");

Example 3
n=2
while 1:
i=1;
while i<=10:
print("%d X %d = %d\n"%(n,i,n*i));
i = i+1;
choice = int(input("Do you want to continue printing the table, press 0 for no?"))
Don Bosco College, Kottiyam 46
CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

if choice == 0:
break;
n=n+1

Infinite while loop


If the condition is given in the while loop never becomes false, then the while loop
will never terminate, and it turns into the infinite while loop.

Any non-zero value in the while loop indicates an always-true condition, whereas
zero indicates the always-false condition. This type of approach is useful if we
want our program to run continuously in the loop without any disturbance.

Example 1
while (1):
print("Hi! we are inside the infinite while loop")

Example 2
var = 1
while(var != 2):
i = int(input("Enter the number:"))
print("Entered value is %d"%(i))

Using else with while loop


Python allows to use the else statement with the while loop also. The else block is
executed when the condition given in the while statement becomes false. Like for
loop, if the while loop is broken using break statement, then the else block will not
be executed, and the statement present after else block will be executed. The else
statement is optional to use with the while loop. Consider the following example.

Example 1
i=1
while(i<=5):
print(i)
i=i+1
else:
print("The while loop exhausted")

Example 2
i=1
Don Bosco College, Kottiyam 47
CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

while(i<=5):
print(i)
i=i+1
if(i==3):
break
else:
print("The while loop exhausted")

In the above code, when the break statement encountered, then while loop stopped
its execution and skipped the else statement.

Example-3 Program to print Fibonacci numbers to given limit


terms = int(input("Enter the terms "))
# first two intial terms
a=0
b=1
count = 0

# check if the number of terms is Zero or negative


if (terms <= 0):
print("Please enter a valid integer")
elif (terms == 1):
print("Fibonacci sequence upto",limit,":")
print(a)
else:
print("Fibonacci sequence:")
while (count < terms) :
print(a, end = ' ')
c=a+b
# updateing values
a=b
b=c

count += 1

Python String

Python string is the collection of the characters surrounded by single quotes,


double quotes, or triple quotes. The computer does not understand the characters;
internally, it stores manipulated character as the combination of the 0's and 1's.

Don Bosco College, Kottiyam 48


CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

Each character is encoded in the ASCII or Unicode character. Python strings are
also called the collection of Unicode characters.

In Python, strings can be created by enclosing the character or the sequence of


characters in the quotes. Python allows us to use single quotes, double quotes, or
triple quotes to create the string.

Python to create a string.

Syntax:
str = "Hi Python !"
Here, if we check the type of the variable str using a Python script

print(type(str)), then it will print a string (str).


In Python, strings are treated as the sequence of characters, which means that
Python doesn't support the character data-type; instead, a single character written
as 'p' is treated as the string of length 1.

Creating String in Python


a string by enclosing the characters in single-quotes or double- quotes. Python also
provides triple-quotes to represent the string, but it is generally used for multiline
string or docstrings.

#Using single quotes


str1 = 'Hello Python'
print(str1)
#Using double quotes
str2 = "Hello Python"
print(str2)

#Using triple quotes


str3 = '''''Triple quotes are generally used for
represent the multiline or
docstring'''
print(str3)
Output:

Hello Python
Hello Python
Triple quotes are generally used for
represent the multiline or
docstring
Don Bosco College, Kottiyam 49
CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

Strings indexing and splitting

example:

str = "HELLO"
print(str[0])
print(str[1])
print(str[2])
print(str[3])
print(str[4])
# It returns the IndexError because 6th index doesn't exist
print(str[6])

the slice operator [] is used to access the individual characters of the string.
However, we can use the : (colon) operator in Python to access the substring from
the given string. Consider the following example.

Don Bosco College, Kottiyam 50


CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

the negative slicing in the string; it starts from the rightmost character, which is
indicated as -1. The second rightmost index indicates -2, and so on. Consider the
following image.

Reassigning Strings
Updating the content of the strings is as easy as assigning it to a new string. The
string object doesn't support item assignment i.e., A string can only be replaced
with new string since its content cannot be partially replaced. Strings are
immutable in Python.
Example
str = "HELLO"
print(str)
str = "hello"
print(str)
Don Bosco College, Kottiyam 51
CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

Output:

HELLO
hello

String Operators
Operator Description

+ It is known as concatenation operator used to join the strings given


either side of the operator.

* It is known as repetition operator. It concatenates the multiple copies


of the same string.

[] It is known as slice operator. It is used to access the sub-strings of a


particular string.

[:] It is known as range slice operator. It is used to access the characters


from the specified range.

in It is known as membership operator. It returns if a particular sub-


string is present in the specified string.

not in It is also a membership operator and does the exact reverse of in. It
returns true if a particular substring is not present in the specified
string.

r/R It is used to specify the raw string. Raw strings are used in the cases
where we need to print the actual meaning of escape characters such
as "C://python". To define any string as a raw string, the character r
or R is followed by the string.

% It is used to perform string formatting. It makes use of the format


specifiers used in C programming like %d or %f to map their values
in python. We will discuss how formatting is done in python.

Example
str = "Hello"
str1 = " world"
print(str*3) # prints HelloHelloHello
print(str+str1)# prints Hello world
print(str[4]) # prints o
Don Bosco College, Kottiyam 52
CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

print(str[2:4]); # prints ll
print('w' in str) # prints false as w is not present in str
print('wo' not in str1) # prints false as wo is present in str1.
print(r'C://python37') # prints C://python37 as it is written
print("The string str : %s"%(str)) # prints The string str : Hello
Output:

HelloHelloHello
Hello world
o
ll
False
False
C://python37
The string str : Hello

Python String Formatting


Escape Sequence
Let's suppose we need to write the text as - They said, "Hello what's going on?"-
the given statement can be written in single quotes or double quotes but it will raise
the SyntaxError as it contains both single and double-quotes.

Example

str = "They said, "Hello what's going on?""


print(str)

Output:

SyntaxError: invalid syntax

escape sequence.

The backslash(/) symbol denotes the escape sequence. The backslash can be
followed by a special character and it interpreted differently. The single quotes
inside the string must be escaped. We can apply the same as in the double quotes.

Example -
# using triple quotes
print('''''They said, "What's there?"''')

# escaping single quotes


Don Bosco College, Kottiyam 53
CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

print('They said, "What\'s going on?"')

# escaping double quotes


print("They said, \"What's going on?\"")
Output:

They said, "What's there?"


They said, "What's going on?"
They said, "What's going on?"

The list of an escape sequence is given below:


Sr. Escape Description Example
Sequence

1. \newline It ignores the new line. print("Python1 \


Python2 \
Python3")
Output:
Python1 Python2 Python3

2. \\ Backslash print("\\")
Output:
\

3. \' Single Quotes print('\'')


Output:
'

4. \\'' Double Quotes print("\"")


Output:
"

5. \a ASCII Bell print("\a")

6. \b ASCII Backspace(BS) print("Hello \b World")


Output:
Hello World

7. \f ASCII Formfeed print("Hello \f World!")


Hello World!

8. \n ASCII Linefeed print("Hello \n World!")


Don Bosco College, Kottiyam 54
CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

Output:
Hello
World!

9. \r ASCII Carriege print("Hello \r World!")


Return(CR) Output:
World!

10. \t ASCII Horizontal Tab print("Hello \t World!")


Output:
Hello World!

11. \v ASCII Vertical Tab print("Hello \v World!")


Output:
Hello
World!

12. \ooo Character with octal print("\110\145\154\154\157")


value Output:
Hello

13 \xHH Character with hex print("\x48\x65\x6c\x6c\x6f")


value. Output:
Hello

The format() method


The format() method is the most flexible and useful method in formatting strings.
The curly braces {} are used as the placeholder in the string and replaced by the
format() method argument. Let's have a look at the given an example:

# Using Curly braces


print("{} and {} both are the best friend".format("Devansh","Abhishek"))

#Positional Argument
print("{1} and {0} best players ".format("Virat","Rohit"))

#Keyword Argument
print("{a},{b},{c}".format(a = "James", b = "Peter", c = "Ricky"))
Output:

Devansh and Abhishek both are the best friend


Rohit and Virat best players

Don Bosco College, Kottiyam 55


CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

James,Peter,Ricky

Python String Formatting Using % Operator


Python allows us to use the format specifiers used in C's printf statement. The
format specifiers in Python are treated in the same way as they are treated in C.
However, Python provides an additional operator %, which is used as an interface
between the format specifiers and their values. In other words, we can say that it
binds the format specifiers to the values.

Consider the following example.

Integer = 10;
Float = 1.290
String = "Devansh"
print("Hi I am Integer ... My value is %d\nHi I am float ... My value is %f\nHi I
am string ... My value is %s"%(Integer,Float,String))
Output:

Hi I am Integer ... My value is 10


Hi I am float ... My value is 1.290000
Hi I am string ... My value is Devansh

Python String functions


Python provides various in-built functions that are used for string handling. Many
String fun

Method Description

capitalize() It capitalizes the first character of the String.


This function is deprecated in python3

casefold() It returns a version of s suitable for case-less


comparisons.

center(width ,fillchar) It returns a space padded string with the


original string centred with equal number of
left and right spaces.

count(string,begin,end) It counts the number of occurrences of a


substring in a String between begin and end
index.

Don Bosco College, Kottiyam 56


CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

decode(encoding = 'UTF8', errors Decodes the string using codec registered


= 'strict') for encoding.

encode() Encode S using the codec registered for


encoding. Default encoding is 'utf-8'.

endswith(suffix It returns a Boolean value if the string


,begin=0,end=len(string)) terminates with given suffix between begin
and end.

expandtabs(tabsize = 8) It defines tabs in string to multiple spaces.


The default space value is 8.

find(substring ,beginIndex, It returns the index value of the string where


endIndex) substring is found between begin index and
end index.

format(value) It returns a formatted version of S, using the


passed value.

index(subsring, beginIndex, It throws an exception if string is not found.


endIndex) It works same as find() method.

isalnum() It returns true if the characters in the string


are alphanumeric i.e., alphabets or numbers
and there is at least 1 character. Otherwise, it
returns false.

isalpha() It returns true if all the characters are


alphabets and there is at least one character,
otherwise False.

isdecimal() It returns true if all the characters of the


string are decimals.

isdigit() It returns true if all the characters are digits


and there is at least one character, otherwise
False.

isidentifier() It returns true if the string is the valid


identifier.

islower() It returns true if the characters of a string are


in lower case, otherwise false.

isnumeric() It returns true if the string contains only


numeric characters.

Don Bosco College, Kottiyam 57


CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

isprintable() It returns true if all the characters of s are


printable or s is empty, false otherwise.

isupper() It returns false if characters of a string are in


Upper case, otherwise False.

isspace() It returns true if the characters of a string are


white-space, otherwise false.

istitle() It returns true if the string is titled properly


and false otherwise. A title string is the one
in which the first character is upper-case
whereas the other characters are lower-case.

isupper() It returns true if all the characters of the


string(if exists) is true otherwise it returns
false.

join(seq) It merges the strings representation of the


given sequence.

len(string) It returns the length of a string.

ljust(width[,fillchar]) It returns the space padded strings with the


original string left justified to the given
width.

lower() It converts all the characters of a string to


Lower case.

lstrip() It removes all leading whitespaces of a


string and can also be used to remove
particular character from leading.

partition() It searches for the separator sep in S, and


returns the part before it, the separator itself,
and the part after it. If the separator is not
found, return S and two empty strings.

maketrans() It returns a translation table to be used in


translate function.

replace(old,new[,count]) It replaces the old sequence of characters


with the new sequence. The max characters
are replaced if max is given.

rfind(str,beg=0,end=len(str)) It is similar to find but it traverses the string

Don Bosco College, Kottiyam 58


CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

in backward direction.

rindex(str,beg=0,end=len(str)) It is same as index but it traverses the string


in backward direction.

rjust(width,[,fillchar]) Returns a space padded string having


original string right justified to the number
of characters specified.

rstrip() It removes all trailing whitespace of a string


and can also be used to remove particular
character from trailing.

rsplit(sep=None, maxsplit = -1) It is same as split() but it processes the string


from the backward direction. It returns the
list of words in the string. If Separator is not
specified then the string splits according to
the white-space.

split(str,num=string.count(str)) Splits the string according to the delimiter


str. The string splits according to the space if
the delimiter is not provided. It returns the
list of substring concatenated with the
delimiter.

splitlines(num=string.count('\n')) It returns the list of strings at each line with


newline removed.

startswith(str,beg=0,end=len(str)) It returns a Boolean value if the string starts


with given str between begin and end.

strip([chars]) It is used to perform lstrip() and rstrip() on


the string.

swapcase() It inverts case of all characters in a string.

title() It is used to convert the string into the title-


case i.e., The string meEruT will be
converted to Meerut.

translate(table,deletechars = '') It translates the string according to the


translation table passed in the function .

upper() It converts all the characters of a string to


Upper Case.

zfill(width) Returns original string leftpadded with zeros

Don Bosco College, Kottiyam 59


CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

to a total of width characters; intended for


numbers, zfill() retains any sign given (less
one zero).

rpartition()

Python List
A list in Python is used to store the sequence of various types of data. Python lists
are mutable type its mean we can modify its element after it created. However,
Python consists of six data-types that are capable to store the sequences, but the
most common and reliable type is the list.

A list can be defined as a collection of values or items of different types. The items
in the list are separated with the comma (,) and enclosed with the square brackets
[].

A list can be define as below

L1 = ["John", 102, "USA"]


L2 = [1, 2, 3, 4, 5, 6]

Characteristics of Lists
The list has the following characteristics:

1. The lists are ordered.


2. The element of the list can access by index.
3. The lists are the mutable type.
4. The lists are mutable types.
5. A list can store the number of various elements.

a = [1,2,"Peter",4.50,"Ricky",5,6]
b = [1,2,5,"Peter",4.50,"Ricky",6]
a ==b

False
Both lists have consisted of the same elements, but the second list changed the
index position of the 5th element that violates the order of lists. When compare
both lists it returns the false.

Don Bosco College, Kottiyam 60


CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

Lists maintain the order of the element for the lifetime. That's why it is the ordered
collection of objects.

a = [1, 2,"Peter", 4.50,"Ricky",5, 6]


b = [1, 2,"Peter", 4.50,"Ricky",5, 6]
a == b
Output:

True

emp = ["John", 102, "USA"]


Dep1 = ["CS",10]
Dep2 = ["IT",11]
HOD_CS = [10,"Mr. Holding"]
HOD_IT = [11, "Mr. Bewon"]
print("printing employee data...")
print("Name : %s, ID: %d, Country: %s"%(emp[0],emp[1],emp[2]))
print("printing departments...")
print("Department 1:\nName: %s, ID: %d\nDepartment 2:\nName: %s, ID:
%s"%(Dep1[0],Dep2[1],Dep2[0],Dep2[1]))
print("HOD Details ....")
print("CS HOD Name: %s, Id: %d"%(HOD_CS[1],HOD_CS[0]))
print("IT HOD Name: %s, Id: %d"%(HOD_IT[1],HOD_IT[0]))
print(type(emp),type(Dep1),type(Dep2),type(HOD_CS),type(HOD_IT))
Output:

printing employee data...


Name : John, ID: 102, Country: USA
printing departments...
Department 1:
Name: CS, ID: 11
Department 2:
Name: IT, ID: 11
HOD Details ....
CS HOD Name: Mr. Holding, Id: 10
IT HOD Name: Mr. Bewon, Id: 11
<class 'list'><class 'list'><class 'list'><class 'list'><class 'list'>

In the above example, we have created the lists which consist of the employee and
department details and printed the corresponding details. Observe the above code
to understand the concept of the list better.

Don Bosco College, Kottiyam 61


CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

List indexing and splitting


The indexing is processed in the same way as it happens with the strings. The
elements of the list can be accessed by using the slice operator [].

The index starts from 0 and goes to length - 1. The first element of the list is stored
at the 0th index, the second element of the list is stored at the 1st index, and so on.

list_varible(start:stop:step)
1. The start denotes the starting index position of the list.
2. The stop denotes the last index position of the list.
3. The step is used to skip the nth element within a start:stop

example:

list = [1,2,3,4,5,6,7]
print(list[0])
print(list[1])
print(list[2])
print(list[3])
# Slicing the elements
print(list[0:6])
# By default the index value is 0 so its starts from the 0th element and go for index
-1.
print(list[:])
print(list[2:5])
print(list[1:6:2])
Don Bosco College, Kottiyam 62
CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

Output:

1
2
3
4
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 7]
[3, 4, 5]
[2, 4, 6]

Unlike other languages, Python provides the flexibility to use the negative
indexing also. The negative indices are counted from the right. The last element
(rightmost) of the list has the index -1; its adjacent left element is present at the
index -2 and so on until the left-most elements are encountered.

elements of the list.

list = [1,2,3,4,5]
print(list[-1])
print(list[-3:])
print(list[:-1])
print(list[-3:-1])
Output:

5
[3, 4, 5]
[1, 2, 3, 4]
[3, 4]

Updating List values


Lists are the most versatile data structures in Python since they are mutable, and
their values can be updated by using the slice and assignment operator.

Don Bosco College, Kottiyam 63


CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

Python also provides append() and insert() methods, which can be used to add
values to the list.

Consider the following example to update the values inside the list.

list = [1, 2, 3, 4, 5, 6]
print(list)
# It will assign value to the value to the second index
list[2] = 10
print(list)
# Adding multiple-element
list[1:3] = [89, 78]
print(list)
# It will add value at the end of the list
list[-1] = 25
print(list)
Output:

[1, 2, 3, 4, 5, 6]
[1, 2, 10, 4, 5, 6]
[1, 89, 78, 4, 5, 6]
[1, 89, 78, 4, 5, 25]

The list elements can also be deleted by using the del keyword. Python also
provides us the remove() method if we do not know which element is to be deleted
from the list.

Consider the following example to delete the list elements.

list = [1, 2, 3, 4, 5, 6]
print(list)
# It will assign value to the value to second index
list[2] = 10
print(list)
# Adding multiple element
list[1:3] = [89, 78]
print(list)
# It will add value at the end of the list
list[-1] = 25
print(list)
Output:

Don Bosco College, Kottiyam 64


CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

[1, 2, 3, 4, 5, 6]
[1, 2, 10, 4, 5, 6]
[1, 89, 78, 4, 5, 6]
[1, 89, 78, 4, 5, 25]

Python List Operations


The concatenation (+) and repetition (*) operators work in the same way as they
were working with the strings.

Let's see how the list responds to various operators.

Consider a Lists l1 = [1, 2, 3, 4], and l2 = [5, 6, 7, 8] to perform operation.

Operator Description Example

Repetition The repetition operator enables the list elements to L1*2 = [1, 2, 3, 4, 1,
be repeated multiple times. 2, 3, 4]

Concatenation It concatenates the list mentioned on either side of l1+l2 = [1, 2, 3, 4, 5,


the operator. 6, 7, 8]

Membership It returns true if a particular item exists in a print(2 in l1) prints


particular list otherwise false. True.

Iteration The for loop is used to iterate over the list for i in l1:
elements. print(i)
Output
1
2
3
4

Length It is used to get the length of the list len(l1) = 4

Iterating a List
A list can be iterated by using a for - in loop. A simple list containing four strings,
which can be iterated as follows.

list = ["John", "David", "James", "Jonathan"]


for i in list:

Don Bosco College, Kottiyam 65


CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

# The i variable will iterate over the elements of the List and contains each
element in each iteration.
print(i)
Output:

John
David
James
Jonathan
Adding elements to the list
Python provides append() function which is used to add an element to the list.
However, the append() function can only add value to the end of the list.

Consider the following example in which, we are taking the elements of the list
from the user and printing the list on the console.

#Declaring the empty list


l =[]
#Number of elements will be entered by the user
n = int(input("Enter the number of elements in the list:"))
# for loop to take the input
for i in range(0,n):
# The input is taken from the user and added to the list as the item
l.append(input("Enter the item:"))
print("printing the list items..")
# traversal loop to print the list items
for i in l:
print(i, end = " ")
Output:

Enter the number of elements in the list:5


Enter the item:25
Enter the item:46
Enter the item:12
Enter the item:75
Enter the item:42
printing the list items
25 46 12 75 42

Removing elements from the list


Python provides the remove() function which is used to remove the element from
the list. Consider the following example to understand this concept.
Don Bosco College, Kottiyam 66
CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

Example -

list = [0,1,2,3,4]
print("printing original list: ");
for i in list:
print(i,end=" ")
list.remove(2)
print("\nprinting the list after the removal of first element...")
for i in list:
print(i,end=" ")
Output:

printing original list:


01234
printing the list after the removal of first element...
0134

Python List Built-in functions


Python provides the following built-in functions, which can be used with the lists.

SN Function Description Example

1 cmp(list1, It compares the elements This method is not used in the Python
list2) of both the lists. 3 and the above versions.

2 len(list) It is used to calculate the L1 = [1,2,3,4,5,6,7,8]


length of the list. print(len(L1))
8

3 max(list) It returns the maximum L1 = [12,34,26,48,72]


element of the list. print(max(L1))
72

4 min(list) It returns the minimum L1 = [12,34,26,48,72]


element of the list. print(min(L1))
12

5 list(seq) It converts any sequence to str = "Johnson"


the list. s = list(str)

Don Bosco College, Kottiyam 67


CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

print(type(s))
<class list>

Example: 1- Write the program to remove the duplicate element of the list.

list1 = [1,2,2,3,55,98,65,65,13,29]
# Declare an empty list that will store unique values
list2 = []
for i in list1:
if i not in list2:
list2.append(i)
print(list2)
Output:

[1, 2, 3, 55, 98, 65, 13, 29]


Example:2- Write a program to find the sum of the element in the list.

list1 = [3,4,5,9,10,12,24]
sum = 0
for i in list1:
sum = sum+i
print("The sum is:",sum)
Output:

The sum is: 67


Example: 3- Write the program to find the lists consist of at least one common
element.

list1 = [1,2,3,4,5,6]
list2 = [7,8,9,2,10]
for x in list1:
for y in list2:
if x == y:
print("The common element is:",x)
Output:

The common element is: 2

Python Tuple

Don Bosco College, Kottiyam 68


CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

Python Tuple is used to store the sequence of immutable Python objects. The tuple
is similar to lists since the value of the items stored in the list can be changed,
whereas the tuple is immutable, and the value of the items stored in the tuple
cannot be changed.

Creating a tuple
A tuple can be written as the collection of comma-separated (,) values enclosed
with the small () brackets. The parentheses are optional but it is good practice to
use. A tuple can be defined as follows.

T1 = (101, "Peter", 22)


T2 = ("Apple", "Banana", "Orange")
T3 = 10,20,30,40,50

print(type(T1))
print(type(T2))
print(type(T3))
Creating a tuple with single element is slightly different, put comma after the
element to declare the tuple.

tup1 = ("pythontuple")
print(type(tup1))
#Creating a tuple with single element
tup2 = ("pyhtontuple",)
print(type(tup2))

A tuple is indexed in the same way as the lists. The items in the tuple can be
accessed by using their specific index value.

Consider the following example of tuple:

Example - 1
tuple1 = (10, 20, 30, 40, 50, 60)
print(tuple1)
count = 0
for i in tuple1:
print("tuple1[%d] = %d"%(count, i))
count = count+1
Output:

(10, 20, 30, 40, 50, 60)


tuple1[0] = 10
Don Bosco College, Kottiyam 69
CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

tuple1[1] = 20
tuple1[2] = 30
tuple1[3] = 40
tuple1[4] = 50
tuple1[5] = 60

Example - 2
tuple1 = tuple(input("Enter the tuple elements ..."))
print(tuple1)
count = 0
for i in tuple1:
print("tuple1[%d] = %s"%(count, i))
count = count+1
Output:

Enter the tuple elements ...123456


('1', '2', '3', '4', '5', '6')
tuple1[0] = 1
tuple1[1] = 2
tuple1[2] = 3
tuple1[3] = 4
tuple1[4] = 5
tuple1[5] = 6

A tuple is indexed in the same way as the lists. The items in the tuple can be
accessed by using their specific index value.

Tuple indexing and slicing


The indexing and slicing in the tuple are similar to lists. The indexing in the tuple
starts from 0 and goes to length(tuple) - 1.

The items in the tuple can be accessed by using the index [] operator. Python also
allows us to use the colon operator to access multiple items in the tuple.

Consider the following image to understand the indexing and slicing in detail.

Don Bosco College, Kottiyam 70


CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

Consider the following example:

tup = (1,2,3,4,5,6,7)
print(tup[0])
print(tup[1])
print(tup[2])
# It will give the IndexError
print(tup[8])

In the above code, the tuple has 7 elements which denote 0 to 6. We tried to access
an element outside of tuple that raised an IndexError.

tuple = (1,2,3,4,5,6,7)
#element 1 to end
print(tuple[1:])
#element 0 to 3 element
print(tuple[:4])
#element 1 to 4 element
print(tuple[1:5])
# element 0 to 6 and take step of 2
print(tuple[0:6:2])

Negative Indexing
Don Bosco College, Kottiyam 71
CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

The tuple element can also access by using negative indexing. The index of -1
denotes the rightmost element and -2 to the second last item and so on.

The elements from left to right are traversed using the negative indexing. Consider
the following example:

tuple1 = (1, 2, 3, 4, 5)
print(tuple1[-1])
print(tuple1[-4])
print(tuple1[-3:-1])
print(tuple1[:-1])
print(tuple1[-2:])

Deleting Tuple
Unlike lists, the tuple items cannot be deleted by using the del keyword as tuples
are immutable. To delete an entire tuple, we can use the del keyword with the tuple
name.

Consider the following example.

tuple1 = (1, 2, 3, 4, 5, 6)
print(tuple1)
del tuple1[0]
print(tuple1)
del tuple1
print(tuple1)
Basic Tuple operations
The operators like concatenation (+), repetition (*), Membership (in) works in the
same way as they work with the list. Consider the following table for more detail.

Tuple t = (1, 2, 3, 4, 5) and Tuple t1 = (6, 7, 8, 9) are declared.

Operator Description Example

Repetition The repetition operator enables the tuple T1*2 = (1, 2, 3, 4,


elements to be repeated multiple times. 5, 1, 2, 3, 4, 5)

Concatenation It concatenates the tuple mentioned on T1+T2 = (1, 2, 3, 4,


either side of the operator. 5, 6, 7, 8, 9)

Membership It returns true if a particular item exists in print (2 in T1) prints


the tuple otherwise false True.
Don Bosco College, Kottiyam 72
CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

Iteration The for loop is used to iterate over the for i in T1:
tuple elements. print(i)
Output
1
2
3
4
5

Length It is used to get the length of the tuple. len(T1) = 5

Python Tuple inbuilt functions

SN Function Description

1 cmp(tuple1, It compares two tuples and returns true if tuple1 is


tuple2) greater than tuple2 otherwise false.

2 len(tuple) It calculates the length of the tuple.

3 max(tuple) It returns the maximum element of the tuple

4 min(tuple) It returns the minimum element of the tuple.

5 tuple(seq) It converts the specified sequence to the tuple.

List vs. Tuple

SN List Tuple

1 The literal syntax of list is shown The literal syntax of the tuple is shown
by the []. by the ().

2 The List is mutable. The tuple is immutable.

3 The List has the a variable length. The tuple has the fixed length.

4 The list provides more The tuple provides less functionality


functionality than a tuple. than the list.

5 The list is used in the scenario in The tuple is used in the cases where
Don Bosco College, Kottiyam 73
CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

which we need to store the simple we need to store the read-only


collections with no constraints collections i.e., the value of the items
where the value of the items can cannot be changed. It can be used as
be changed. the key inside the dictionary.

6 The lists are less memory The tuples are more memory efficient
efficient than a tuple. because of its immutability.

Python Set
A Python set is the collection of the unordered items. Each element in the set must
be unique, immutable, and the sets remove the duplicate elements. Sets are mutable
which means we can modify it after its creation.

Unlike other collections in Python, there is no index attached to the elements of the
set, i.e., we cannot directly access any element of the set by the index. However,
we can print them all together, or we can get the list of elements by looping
through the set.

Creating a set
The set can be created by enclosing the comma-separated immutable items with
the curly braces {}. Python also provides the set() method, which can be used to
create the set by the passed sequence.

Example 1: Using curly braces


Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday",
"Sunday"}
print(Days)
print(type(Days))
print("looping through the set elements ... ")
for i in Days:
print(i)

Example 2: Using set() method


Days = set(["Monday", "Tuesday", "Wednesday", "Thursday", "Friday",
"Saturday", "Sunday"])
print(Days)
print(type(Days))
print("looping through the set elements ... ")
for i in Days:
print(i)
Don Bosco College, Kottiyam 74
CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

Adding items to the set


Python provides the add() method and update() method which can be used to add
some particular item to the set. The add() method is used to add a single element
whereas the update() method is used to add multiple elements to the set. Consider
the following example.

Example: 1 - Using add() method


Months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(months)
print("\nAdding other months to the set...");
Months.add("July");
Months.add ("August");
print("\nPrinting the modified set...");
print(Months)
print("\nlooping through the set elements ... ")
for i in Months:
print(i)
To add more than one item in the set, Python provides the update() method. It
accepts iterable as an argument.

Example - 2 Using update() function


Months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(Months)
print("\nupdating the original set ... ")
Months.update(["July","August","September","October"]);
print("\nprinting the modified set ... ")
print(Months);

Removing items from the set


Python provides the discard() method and remove() method which can be used to
remove the items from the set. The difference between these function, using
discard() function if the item does not exist in the set then the set remain
unchanged whereas remove() method will through an error.
Example-1 Using discard() method
months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(months)
print("\nRemoving some months from the set...");
Don Bosco College, Kottiyam 75
CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

months.discard("January");
months.discard("May");
print("\nPrinting the modified set...");
print(months)
print("\nlooping through the set elements ... ")
for i in months:
print(i)

Example-2 Using remove() function


months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(months)
print("\nRemoving some months from the set...");
months.remove("January");
months.remove("May");
print("\nPrinting the modified set...");
print(months)

the pop() method is used to remove the item. Generally, the pop() method will
always remove the last item but the set is unordered, we can't determine which
element will be popped from set.

Consider the following example to remove the item from the set using pop()
method.

Months = set(["January","February", "March", "April", "May", "June"])


print("\nprinting the original set ... ")
print(Months)
print("\nRemoving some months from the set...");
Months.pop();
Months.pop();
print("\nPrinting the modified set...");
print(Months)

Difference between discard() and remove()


Despite the fact that discard() and remove() method both perform the same task,
There is one main difference between discard() and remove().

If the key to be deleted from the set using discard() doesn't exist in the set, the
Python will not give the error. The program maintains its control flow.
Don Bosco College, Kottiyam 76
CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

On the other hand, if the item to be deleted from the set using remove() doesn't
exist in the set, the Python will raise an error.

Example-
Months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(Months)
print("\nRemoving items through discard() method...");
Months.discard("Feb"); #will not give an error although the key feb is not available
in the set
print("\nprinting the modified set...")
print(Months)
print("\nRemoving items through remove() method...");
Months.remove("Jan") #will give an error as the key jan is not available in the set.
print("\nPrinting the modified set...")
print(Months)

Python Dictionary
Python Dictionary is used to store the data in a key-value pair format. The
dictionary is the data type in Python, which can simulate the real-life data
arrangement where some specific value exists for some particular key. It is the
mutable data-structure. The dictionary is defined into element Keys and values.

Keys must be a single element


Value can be any type such as list, tuple, integer, etc.
In other words, we can say that a dictionary is the collection of key-value pairs
where the value can be any Python object. In contrast, the keys are the immutable
Python object, i.e., Numbers, string, or tuple.

Creating the dictionary


The dictionary can be created by using multiple key-value pairs enclosed with the
curly brackets {}, and each key is separated from its value by the colon (:).The
syntax to define the dictionary is given below.

Dict = {"Name": "Tom", "Age": 22}


In the above dictionary Dict, The keys Name and Age are the string that is an
immutable object.

example to create a dictionary and print its content.

Employee= {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}


Don Bosco College, Kottiyam 77
CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

print(type(Employee))
print("printing Employee data .... ")
print(Employee)

Python provides the built-in function dict() method which is also used to create
dictionary. The empty curly braces {} is used to create empty dictionary.

# Creating an empty Dictionary


Dict = {}
print("Empty Dictionary: ")
print(Dict)

# Creating a Dictionary
# with dict() method
Dict = dict({1: 'Python', 2: 'Program', 3:'Language'})
print("\nCreate Dictionary by using dict(): ")
print(Dict)

# Creating a Dictionary
# with each item as a Pair
Dict = dict([(1, 'Devansh'), (2, 'Sharma')])
print("\nDictionary with each item as a pair: ")
print(Dict)

Accessing the dictionary values

the values can be accessed in the dictionary by using the keys as keys are unique in
the dictionary.

The dictionary values can be accessed in the following way.

Employee= {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}


print(type(Employee))
print("printing Employee data .... ")
print("Name : %s" %Employee["Name"])
print("Age : %d" %Employee["Age"])
print("Salary : %d" %Employee["salary"])
print("Company : %s" %Employee["Company"])

Don Bosco College, Kottiyam 78


CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

Python provides an alternative to use the get() method to access the dictionary
values. It would give the same result as given by the indexing.

Adding dictionary values


The dictionary is a mutable data type, and its values can be updated by using the
specific keys. The value can be updated along with key Dict[key] = value. The
update() method is also used to update an existing value.

Note: If the key-value already present in the dictionary, the value gets updated.
Otherwise, the new keys added in the dictionary.

Example - 1:

# Creating an empty Dictionary


Dict = {}
print("Empty Dictionary: ")
print(Dict)

# Adding elements to dictionary one at a time


Dict[0] = 'Peter'
Dict[2] = 'Joseph'
Dict[3] = 'Ricky'
print("\nDictionary after adding 3 elements: ")
print(Dict)

# Adding set of values


# with a single Key
# The Emp_ages doesn't exist to dictionary
Dict['Emp_ages'] = 20, 33, 24
print("\nDictionary after adding 3 elements: ")
print(Dict)

# Updating existing Key's Value


Dict[3] = 'python'
print("\nUpdated key value: ")
print(Dict)

Example - 2:

Employee= {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}


print(type(Employee))
print("printing Employee data .... ")
Don Bosco College, Kottiyam 79
CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

print(Employee)
print("Enter the details of the new employee....");
Employee["Name"] = input("Name: ");
Employee["Age"] = int(input("Age: "));
Employee["salary"] = int(input("Salary: "));
Employee["Company"] = input("Company:");
print("printing the new data");
print(Employee)

Deleting elements using del keyword


The items of the dictionary can be deleted by using the del keyword as given
below.

Employee = {"Name": "John", "Age": 29,


"salary":25000,"Company":"GOOGLE"}
print(type(Employee))
print("printing Employee data .... ")
print(Employee)
print("Deleting some of the employee data")
del Employee["Name"]
del Employee["Company"]
print("printing the modified information ")
print(Employee)
print("Deleting the dictionary: Employee");
del Employee
print("Lets try to print it again ");
print(Employee)

Using pop() method


The pop() method accepts the key as an argument and remove the associated value.
Consider the following example.

# Creating a Dictionary
Dict = {1: 'python', 2: 'Peter', 3: 'Thomas'}
# Deleting a key
# using pop() method
pop_ele = Dict.pop(3)
print(Dict)

Don Bosco College, Kottiyam 80


CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

Python also provides a built-in methods popitem() and clear() method for remove
elements from the dictionary. The popitem() removes the arbitrary element from a
dictionary, whereas the clear() method removes all elements to the whole
dictionary.

Iterating Dictionary
A dictionary can be iterated using for loop as given below.

Example 1
Employee = {"Name": "John", "Age": 29,
"salary":25000,"Company":"GOOGLE"}
for x in Employee:
print(x)
Example 2
#for loop to print all the values of the dictionary

Employee = {"Name": "John", "Age": 29,


"salary":25000,"Company":"GOOGLE"}
for x in Employee:
print(Employee[x])

Properties of Dictionary keys


1. In the dictionary, we cannot store multiple values for the same keys. If we pass
more than one value for a single key, then the value which is last assigned is
considered as the value of the key.

Consider the following example.

Employee={"Name":"John","Age":29,"Salary":25000,"Company":"GOOGLE","N
ame":"John"}
for x,y in Employee.items():

Don Bosco College, Kottiyam 81


CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

print(x,y)

2. In python, the key cannot be any mutable object. We can use numbers, strings,
or tuples as the key, but we cannot use any mutable object like the list as the key in
the dictionary.

Consider the following example.

Employee = {"Name": "John", "Age": 29,


"salary":25000,"Company":"GOOGLE",[100,201,301]:"Department ID"}
for x,y in Employee.items():
print(x,y)

Built-in Dictionary functions


The built-in python dictionary methods along with the description are given below.

SN Function Description

1 cmp(dict1, It compares the items of both the dictionary and returns


dict2) true if the first dictionary values are greater than the
second dictionary, otherwise it returns false.

2 len(dict) It is used to calculate the length of the dictionary.

3 str(dict) It converts the dictionary into the printable string


representation.

4 type(variable) It is used to print the type of the passed variable.

Built-in Dictionary methods


The built-in python dictionary methods along with the description are given below.

Don Bosco College, Kottiyam 82


CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

SN Method Description

1 dic.clear() It is used to delete all the items of the


dictionary.

2 dict.copy() It returns a shallow copy of the


dictionary.

3 dict.fromkeys(iterable, value = Create a new dictionary from the iterable


None, /) with the values equal to value.

4 dict.get(key, default = "None") It is used to get the value specified for


the passed key.

5 dict.has_key(key) It returns true if the dictionary contains


the specified key.

6 dict.items() It returns all the key-value pairs as a


tuple.

7 dict.keys() It returns all the keys of the dictionary.

8 dict.setdefault(key,default= It is used to set the key to the default


"None") value if the key is not specified in the
dictionary

9 dict.update(dict2) It updates the dictionary by adding the


key-value pair of dict2 to this dictionary.

10 dict.values() It returns all the values of the dictionary.

11 len()

12 popItem()

13 pop()

14 count()

Don Bosco College, Kottiyam 83


CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

15 index()

Python Function
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 enclosed by
{}. 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.

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 Python 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 Reusability is the main achievement of Python functions.
o However, Function calling is always overhead in a Python program.
Creating a Function

Don Bosco College, Kottiyam 84


CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

Python provides the def keyword to define the function. The syntax of the define
function is given below.

Syntax:

def my_function(parameters):
function_block
return expression
understand the syntax of functions definition.
o The def keyword, along with the function name is used to define the
function.
o The identifier rule must follow the function name.
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
In Python, 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.
#function definition
def hello_world():
print("hello world")
# function calling
hello_world()

The return statement

Don Bosco College, Kottiyam 85


CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

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.
Example 1
# Defining function
def sum():
a = 10
b = 20
c = a+b
return c
# calling sum() function in print statement
print("The sum is:",sum())
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 2 Creating function without return statement
# Defining function
def sum():
a = 10
b = 20
c = a+b
# calling sum() function in print statement
print(sum())

Don Bosco College, Kottiyam 86


CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

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.

Consider the following example, which contains a function that accepts a string as
the argument.
Example 1
#defining the function
def func (name):
print("Hi ",name)
#calling the function
func("Devansh")
Example 2
#Python function to calculate the sum of two variables
#defining the function
def sum (a,b):
return a+b;

#taking values from the user


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

#printing the sum of a and b


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

Don Bosco College, Kottiyam 87


CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

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 1 Passing Immutable Object (List)


#defining the function
def change_list(list1):
list1.append(20)
list1.append(30)
print("list inside function = ",list1)

#defining the list


list1 = [10,30,40,50]

#calling the function


change_list(list1)
print("list outside function = ",list1)

Example 2 Passing Mutable Object (String)


#defining the function
def change_string (str):
str = str + " Hows you "
print("printing the string inside function :",str)

string1 = "Hi I am there"

#calling the function


change_string(string1)
Don Bosco College, Kottiyam 88
CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

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

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
Till now, we have learned about function calling in Python. However, we can
provide the arguments at the time of the function call. As far as the required
arguments are concerned, 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 1

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

Example 2

#the function simple_interest accepts three arguments and returns the simple
interest accordingly

Don Bosco College, Kottiyam 89


CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

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? "))
t = float(input("Enter the time in years? "))
print("Simple Interest: ",simple_interest(p,r,t))

Example 3

#the function 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.

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 1

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 2

Don Bosco College, Kottiyam 90


CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

def printme(name,age=22):
print("My name is",name,"and age is",age)
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

Variable-length Arguments (*args)


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.

However, at the function definition, we define the variable-length argument using


the *args (star) as *<variable - name >.

Consider the following example.

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

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.

Don Bosco College, Kottiyam 91


CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

Keyword arguments(**kwargs)
Python allows us to call the function with the 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 1

#function func is called with the name and message as the keyword arguments
def func(name,message):
print("printing the message with",name,"and ",message)

#name and message is copied with the values John and hello respectively
func(name = "John",message="hello")
Output:

printing the message with John and hello


Example 2 providing the values in different order at the calling

#The function simple_interest(p, t, r) is called with the keyword arguments the


order of arguments doesn't matter in this case
def simple_interest(p,t,r):
return (p*t*r)/100
print("Simple Interest: ",simple_interest(t=10,r=10,p=1900))

If we provide the different name of arguments at the time of function call, an error
will be thrown.

Don Bosco College, Kottiyam 92


CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

Consider the following example.

Example 3

#The function simple_interest(p, t, r) is called with the keyword arguments.


def simple_interest(p,t,r):
return (p*t*r)/100

# doesn't find the exact match of the name of the arguments (keywords)
print("Simple Interest: ",simple_interest(time=10,rate=10,principle=1900))
The 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 following arguments must also be the keyword arguments.

Consider the following example.

Example 4

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="David")
The following example will cause an error due to an in-proper mix of keyword and
required arguments being passed in the function call.

Example 5

def func(name1,message,name2):
print("printing the message with",name1,",",message,",and",name2)
Don Bosco College, Kottiyam 93
CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

func("John",message="hello","David")
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.

Consider the following example:

Example 6: Many arguments using Keyword argument

def food(**kwargs):
print(kwargs)
food(a="Apple")
food(fruits="Orange", Vagitables="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 1 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)
Don Bosco College, Kottiyam 94
CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

print_message()
print(message) # this will cause an error since a local variable cannot be accessible
here.
Example 2 Global Variable
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

Python Built-in Functions


The Python built-in functions are defined as the functions whose functionality is
pre-defined in Python. The python interpreter has several functions that are always
present for use. These functions are known as Built-in Functions. There are several
built-in functions in Python which are listed below:

Python abs() Function


The python abs() function is used to return the absolute value of a number. It takes
only one argument, a number whose absolute value is to be returned. The argument
can be an integer and floating-point number. If the argument is a complex number,
then, abs() returns its magnitude.
Python abs() Function Example

# integer number
integer = -20
print('Absolute value of -40 is:', abs(integer))

# floating number
Don Bosco College, Kottiyam 95
CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

floating = -20.83
print('Absolute value of -40.83 is:', abs(floating))
Python all() Function
The python all() function accepts an iterable object (such as list, dictionary, etc.). It
returns true if all items in passed iterable are true. Otherwise, it returns False. If the
iterable object is empty, the all() function returns True.
Python all() Function Example

# all values true


k = [1, 3, 4, 6]
print(all(k))

# all values false


k = [0, False]
print(all(k))

# one false value


k = [1, 3, 7, 0]
print(all(k))

# one true value


k = [0, False, 5]
print(all(k))

# empty iterable
k = []
print(all(k))

Python bin() Function

Don Bosco College, Kottiyam 96


CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

The python bin() function is used to return the binary representation of a specified
integer. A result always starts with the prefix 0b.

Python bin() Function Example

x = 10
y = bin(x)
print (y)
Python bool()
The python bool() converts a value to boolean(True or False) using the standard
truth testing procedure.

Python bool() Example


test1 = []
print(test1,'is',bool(test1))
test1 = [0]
print(test1,'is',bool(test1))
test1 = 0.0
print(test1,'is',bool(test1))
test1 = None
print(test1,'is',bool(test1))
test1 = True
print(test1,'is',bool(test1))
test1 = 'Easy string'
print(test1,'is',bool(test1))

Python bytes()
The python bytes() in Python is used for returning a bytes object. It is an
immutable version of the bytearray() function.

Don Bosco College, Kottiyam 97


CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

It can create empty bytes object of the specified size.

Python bytes() Example

string = "Hello World."


array = bytes(string, 'utf-8')
print(array)

Python callable() Function


A python callable() function in Python is something that can be called. This built-
in function checks and returns true if the object passed appears to be callable,
otherwise false.

Python callable() Function Example

x=8
print(callable(x))

Python compile() Function


The python compile() function takes source code as input and returns a code object
which can later be executed by exec() function.

Python compile() Function Example


# compile string source to code
code_str = 'x=5\ny=10\nprint("sum =",x+y)'
code = compile(code_str, 'sum.py', 'exec')
print(type(code))
exec(code)
exec(x)

Don Bosco College, Kottiyam 98


CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

Python exec() Function


The python exec() function is used for the dynamic execution of Python program
which can either be a string or object code and it accepts large blocks of code,
unlike the eval() function which only accepts a single expression.

Python exec() Function Example

x=8
exec('print(x==8)')
exec('print(x+4)')

Python sum() Function


As the name says, python sum() function is used to get the sum of numbers of an
iterable, i.e., list.

Python sum() Function Example

s = sum([1, 2,4 ])
print(s)

s = sum([1, 2, 4], 10)


print(s)

Python any() Function


The python any() function returns true if any item in an iterable is true. Otherwise,
it returns False.

Python any() Function Example

l = [4, 3, 2, 0]
Don Bosco College, Kottiyam 99
CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

print(any(l))

l = [0, False]
print(any(l))

l = [0, False, 5]
print(any(l))

l = []
print(any(l))

Python format() Function


The python format() function returns a formatted representation of the given value.

Python format() Function Example

# d, f and b are a type

# integer
print(format(123, "d"))

# float arguments
print(format(123.4567898, "f"))

# binary format
print(format(12, "b"))

Python Lambda Functions

Don Bosco College, Kottiyam 100


CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

Python Lambda function is known as the anonymous function that is defined


without a name. Python allows us to not declare the function in the standard
manner, i.e., by using the def keyword. Rather, the anonymous functions are
declared by using the lambda keyword. However, Lambda functions can accept
any number of arguments, but they can return only one value in the form of
expression.

The anonymous function contains a small piece of code. It simulates inline


functions of C and C++, but it is not exactly an inline function.

The syntax to define an anonymous function is given below.

Syntax
lambda arguments: expression
Example 1
# a is an argument and a+10 is an expression which got evaluated and returned.
x = lambda a:a+10
# Here we are printing the function object
print(x)
print("sum = ",x(20))

Python File Handling


The file handling plays an important role when the data needs to be stored
permanently into the file. A file is a named location on disk to store related
information. We can access the stored information (non-volatile) after the program
termination.

The file-handling implementation is slightly lengthy or complicated in the other


programming language, but it is easier and shorter in Python.
In Python, files are treated in two modes as text or binary. The file may be in the
text or binary format, and each line of a file is ended with the special character.

Don Bosco College, Kottiyam 101


CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

Hence, a file operation can be done in the following order.

• Open a file
• Read or write - Performing operation
• Close the file

Opening a file
Python provides an open() function that accepts two arguments, file name and
access mode in which the file is accessed. The function returns a file object which
can be used to perform various operations like reading, writing, etc.

Syntax:

file object = open(<file-name>, <access-mode>, <buffering>)


The files can be accessed using various modes like read, write, or append. The
following are the details about the access mode to open a file.

SN Access Description
mode

1 r It opens the file to read-only mode. The file pointer exists at the
beginning. The file is by default open in this mode if no access
mode is passed.

2 rb It opens the file to read-only in binary format. The file pointer


exists at the beginning of the file.

3 r+ It opens the file to read and write both. The file pointer exists at
the beginning of the file.

4 rb+ It opens the file to read and write both in binary format. The file
pointer exists at the beginning of the file.

5 w It opens the file to write only. It overwrites the file if previously


exists or creates a new one if no file exists with the same name.
The file pointer exists at the beginning of the file.

6 wb It opens the file to write only in binary format. It overwrites the


Don Bosco College, Kottiyam 102
CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

file if it exists previously or creates a new one if no file exists.


The file pointer exists at the beginning of the file.

7 w+ It opens the file to write and read both. It is different from r+ in


the sense that it overwrites the previous file if one exists
whereas r+ doesn't overwrite the previously written file. It
creates a new file if no file exists. The file pointer exists at the
beginning of the file.

8 wb+ It opens the file to write and read both in binary format. The file
pointer exists at the beginning of the file.

9 a It opens the file in the append mode. The file pointer exists at
the end of the previously written file if exists any. It creates a
new file if no file exists with the same name.

10 ab It opens the file in the append mode in binary format. The


pointer exists at the end of the previously written file. It creates
a new file in binary format if no file exists with the same name.

11 a+ It opens a file to append and read both. The file pointer remains
at the end of the file if a file exists. It creates a new file if no
file exists with the same name.

12 ab+ It opens a file to append and read both in binary format. The
file pointer remains at the end of the file.

#opens the file file.txt in read mode


fileptr = open("file.txt","r")

if fileptr:
print("file is opened successfully")
In the above code, filename is a first argument and opened file in read mode as it is
mentioned r as the second argument. The fileptr holds the file object and if the file
is opened successfully, it will execute the print statement
The close() method
Once all the operations are done on the file, we must close it through our Python
script using the close() method. Any unwritten information gets destroyed once the
close() method is called on a file object.

Don Bosco College, Kottiyam 103


CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

We can perform any operation on the file externally using the file system which is
the currently opened in Python; hence it is good practice to close the file once all
the operations are done.

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

Syntax

fileobject.close()

# opens the file file.txt in read mode


fileptr = open("file.txt","r")

if fileptr:
print("file is opened successfully")

#closes the opened file


fileptr.close()
Writing the file
To write some text to a file, we need to open the file using the open method with
one of the following access modes.

w: It will overwrite the file if any file exists. The file pointer is at the beginning of
the file.

a: It will append the existing file. The file pointer is at the end of the file. It creates
a new file if no file exists.
Example
# open the file.txt in append mode. Create a new file if no such file exists.
fileptr = open("file2.txt", "w")

Don Bosco College, Kottiyam 104


CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

# appending the content to the file


fileptr.write('''''Python is the modern day language. It makes things so simple.
It is the fastest-growing programing language''')

# closing the opened the file


fileptr.close()

Example 2
#open the file.txt in write mode.
fileptr = open("file2.txt","a")

#overwriting the content of the file


fileptr.write(" Python has an easy syntax and user-friendly interaction.")

#closing the opened file


fileptr.close()

To read a file using the Python script, the Python provides the read() method. The
read() method reads a string from the file. It can read the data in the text as well as
a binary format.

The syntax of the read() method is given below.

Syntax:

fileobj.read(<count>)

Example

Don Bosco College, Kottiyam 105


CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

#open the file.txt in read mode. causes error if no such file exists.
fileptr = open("file2.txt","r")
#stores all the data of the file into the variable content
content = fileptr.read(10)
# prints the type of the data stored in the file
print(type(content))
#prints the content of the file
print(content)
#closes the opened file
fileptr.close()

In the above code, we have read the content of file2.txt by using the read()
function. We have passed count value as ten which means it will read the first ten
characters from the file.

If we use the following line, then it will print all content of the file.

content = fileptr.read()
print(content)

Read file through for loop


We can read the file using for loop. Consider the following example.

#open the file.txt in read mode. causes an error if no such file exists.
fileptr = open("file2.txt","r");
#running a for loop
for i in fileptr:
print(i) # i contains each line of the file

Don Bosco College, Kottiyam 106


CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

Read Lines of the file


Python facilitates to read the file line by line by using a function readline() method.
The readline() method reads the lines of the file from the beginning, i.e., if we use
the readline() method two times, then we can get the first two lines of the file.

Consider the following example which contains a function readline() that reads the
first line of our file "file2.txt" containing three lines. Consider the following
example.

Example 1: Reading lines using readline() function


#open the file.txt in read mode. causes error if no such file exists.
fileptr = open("file2.txt","r");
#stores all the data of the file into the variable content
content = fileptr.readline()
content1 = fileptr.readline()
#prints the content of the file
print(content)
print(content1)
#closes the opened file
fileptr.close()
Example 2: Reading Lines Using readlines() function
#open the file.txt in read mode. causes error if no such file exists.
fileptr = open("file2.txt","r");

#stores all the data of the file into the variable content
content = fileptr.readlines()

#prints the content of the file


print(content)

Don Bosco College, Kottiyam 107


CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

#closes the opened file


fileptr.close()
Creating a new file
The new file can be created by using one of the following access modes with the
function open().

x: it creates a new file with the specified name. It causes an error a file exists with
the same name.

a: It creates a new file with the specified name if no such file exists. It appends the
content to the file if the file already exists with the specified name.

w: It creates a new file with the specified name if no such file exists. It overwrites
the existing file.

Consider the following example.

Example 1
#open the file.txt in read mode. causes error if no such file exists.
fileptr = open("file2.txt","x")
print(fileptr)
if fileptr:
print("File created successfully")
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 file2.txt in read mode


fileptr = open("file2.txt","r")

Don Bosco College, Kottiyam 108


CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

#initially the filepointer is at 0


print("The filepointer is at byte :",fileptr.tell())

#reading the content of the file


content = fileptr.read();

#after the read operation file pointer modifies. tell() returns the location of the
fileptr.

print("After reading, the filepointer is at:",fileptr.tell())


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:

<file-ptr>.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 reference position. If it is set to
2, the end of the file pointer is used as the reference position.

Don Bosco College, Kottiyam 109


CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

Consider the following example.

Example
# open the file file2.txt in read mode
fileptr = open("file2.txt","r")

#initially the filepointer is at 0


print("The filepointer is at byte :",fileptr.tell())

#changing the file pointer location to 10.


fileptr.seek(10);

#tell() returns the location of the fileptr.


print("After reading, the filepointer is at:",fileptr.tell())
The file related methods
The file object provides the following methods to manipulate the files on various
operating systems.

SN Method Description

1 file.close() It closes the opened file. The file once closed, it


can't be read or write anymore.

2 File.fush() It flushes the internal buffer.

3 File.fileno() It returns the file descriptor used by the


underlying implementation to request I/O from
the OS.

4 File.isatty() It returns true if the file is connected to a TTY


device, otherwise returns false.

5 File.next() It returns the next line from the file.

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

7 File.readline([size]) It reads one line from the file and places the file

Don Bosco College, Kottiyam 110


CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

pointer to the beginning of the new line.

8 File.readlines([sizehint]) It returns a list containing all the lines of the file.


It reads the file until the EOF occurs using
readline() function.

9 File.seek(offset[,from) It modifies the position of the file pointer to a


specified offset with the specified reference.

10 File.tell() It returns the current position of the file pointer


within the file.

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

12 File.write(str) It writes the specified string to a file

13 File.writelines(seq) It writes a sequence of the strings to a file.

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

The functionality of one module into another, can be used by importing the
specific module.

#displayMsg prints a message to the name being passed.


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

Loading the module in our python code


Python provides two types of statements as defined below.

The import statement


The from-import statement
The import statement

Don Bosco College, Kottiyam 111


CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

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.

The syntax to use the import statement is given below.

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

Example:
import file;
name = input("Enter the name?")
file.displayMsg(name)

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.

calculation.py:

#place the code in the calculation.py


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

Main.py:

from calculation import summation


#it will import only the summation() from calculation.py
a = int(input("Enter the first number"))
Don Bosco College, Kottiyam 112
CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

b = int(input("Enter the second number"))


print("Sum = ",summation(a,b)) #we do not need to specify the module name
while accessing summation()

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

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 file.
The 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 = ",cal.summation(a,b))

Using dir() function


The dir() function returns a sorted list of names defined in the passed module. This
list contains all the sub-modules, variables and functions defined in this module.

Consider the following example.

Example
import json

List = dir(json)

print(List)

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

Don Bosco College, Kottiyam 113


CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

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

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

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

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

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.

Don Bosco College, Kottiyam 114


CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

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.

Syntax

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

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.

Don Bosco College, Kottiyam 115


CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

try:
#block of code

except Exception1:
#block of code

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

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")
The except statement with no exception
Python provides the flexibility not to specify the name of exception with the
exception statement.
Example

try:
Don Bosco College, Kottiyam 116
CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

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

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("file.txt","r")
except IOError:
print("File not found")
Don Bosco College, Kottiyam 117
CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

else:
print("The file opened successfully")
fileptr.close()

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

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

Don Bosco College, Kottiyam 118


CP1442: WEB PROGRAMMING & PYTHON COMPUTER APPLICATION (BCA)Semester 4

Example

try:
fileptr = open("file2.txt","r")
try:
fileptr.write("Hi I am good")
finally:
fileptr.close()
print("file closed")
except:
print("Error")

Don Bosco College, Kottiyam 119

You might also like