Python Final Notes
Python Final Notes
Python Final Notes
DONBOSCO COLLEGE
Kottiyam,Kollam,Kerala
(Affiliated to the University of Kerala)
Name : ……………………………………………………………………………………………
Reg : ……………………………………………………………….
Python
Python is a simple, general purpose, high level, and object-oriented programming
language.
• 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
Comments in Python
Types of Comment
Python provides the facility to write comments in two ways- single line comment
and multi-line comment.
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.
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.
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"
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)
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:
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 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
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.
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".
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.
In the case of string handling, the operator + is used to concatenate two strings as
the operation "hello"+" python" returns "hello python".
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:])
# 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)
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")
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.
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:
Example:
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
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()
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()
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
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
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:
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.
text1='hello\
user'
print(text1)
Example:
str2='''''welcome
to
SSSIT'''
print str2
#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)
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)
None is used to specify to that field that is not created. It is also used for the end of
lists in Python.
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:
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
• 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.
Operator Description
/ (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
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 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
%= 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.
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.
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.
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
Identity Operators
The identity operators are used to decide whether an element certain class or type.
Operator Description
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
<= <>>= Comparison operators (less than, less than equal to, greater
than, greater then equal to).
• 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()
eg:2
# Program to check input
# type in Python
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()
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.
# 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())
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())
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)
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.
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 print() function prints the message to the screen or any other standard
output device.
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.
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.
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.
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)
def intro():
"""
This function prints Hello Joseph
"""
print("Hi Joseph")
intro()
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.
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")
Statement Description
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.
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.
Example 1
num = int(input("enter the number?"))
if num%2 == 0:
print("Number is even")
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:
print("c is largest");
If the condition is true, then the if-block is executed. Otherwise, the else-block is
executed.
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.
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.
str = "Python"
for i in str:
print(i)
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)
list = [10,30,23,43,65,12]
sum = 0
for i in list:
sum = sum+i
print("The sum is:",sum)
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)
for i in range(10):
print(i,end = ' ')
Example - 2: Program to print table of given number.
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])
Syntax
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
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.
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
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:
The break is commonly used in the cases where we need to break the loop for a
given condition.
#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:
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.
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
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
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
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))
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.
count += 1
Python String
Each character is encoded in the ASCII or Unicode character. Python strings are
also called the collection of Unicode characters.
Syntax:
str = "Hi Python !"
Here, if we check the type of the variable str using a Python script
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
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.
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
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.
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
Example
Output:
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?"''')
2. \\ Backslash print("\\")
Output:
\
Output:
Hello
World!
#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:
James,Peter,Ricky
Integer = 10;
Float = 1.290
String = "Devansh"
print("Hi I am Integer ... My value is %d\nHi I am float ... My value is %f\nHi I
am string ... My value is %s"%(Integer,Float,String))
Output:
Method Description
in backward direction.
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
[].
Characteristics of Lists
The list has the following characteristics:
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.
Lists maintain the order of the element for the lifetime. That's why it is the ordered
collection of objects.
True
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.
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.
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]
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.
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:
[1, 2, 3, 4, 5, 6]
[1, 2, 10, 4, 5, 6]
[1, 89, 78, 4, 5, 6]
[1, 89, 78, 4, 5, 25]
Repetition The repetition operator enables the list elements to L1*2 = [1, 2, 3, 4, 1,
be repeated multiple times. 2, 3, 4]
Iteration The for loop is used to iterate over the list for i in l1:
elements. print(i)
Output
1
2
3
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.
# 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.
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:
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.
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:
list1 = [3,4,5,9,10,12,24]
sum = 0
for i in list1:
sum = sum+i
print("The sum is:",sum)
Output:
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:
Python Tuple
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.
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.
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:
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:
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.
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.
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.
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.
Iteration The for loop is used to iterate over the for i in T1:
tuple elements. print(i)
Output
1
2
3
4
5
SN Function Description
SN List Tuple
1 The literal syntax of list is shown The literal syntax of the tuple is shown
by the []. by the ().
3 The List has the a variable length. The tuple has the fixed length.
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
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.
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)
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.
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.
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 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)
the values can be accessed in the dictionary by using the keys as keys are unique in
the dictionary.
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.
Note: If the key-value already present in the dictionary, the value gets updated.
Otherwise, the new keys added in the dictionary.
Example - 1:
Example - 2:
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)
# Creating a Dictionary
Dict = {1: 'python', 2: 'Peter', 3: 'Thomas'}
# Deleting a key
# using pop() method
pop_ele = Dict.pop(3)
print(Dict)
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","N
ame":"John"}
for x,y in Employee.items():
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.
SN Function Description
SN Method Description
11 len()
12 popItem()
13 pop()
14 count()
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.
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 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())
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;
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
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
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:
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
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")
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:
If we provide the different name of arguments at the time of function call, an error
will be thrown.
Example 3
# 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.
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.
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
# 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
# empty iterable
k = []
print(all(k))
The python bin() function is used to return the binary representation of a specified
integer. A result always starts with the prefix 0b.
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 bytes()
The python bytes() in Python is used for returning a bytes object. It is an
immutable version of the bytearray() function.
x=8
print(callable(x))
x=8
exec('print(x==8)')
exec('print(x+4)')
s = sum([1, 2,4 ])
print(s)
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))
# integer
print(format(123, "d"))
# float arguments
print(format(123.4567898, "f"))
# binary format
print(format(12, "b"))
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))
• 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:
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.
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.
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.
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.
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.
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.
Syntax
fileobject.close()
if fileptr:
print("file is opened successfully")
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")
Example 2
#open the file.txt in write mode.
fileptr = open("file2.txt","a")
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.
Syntax:
fileobj.read(<count>)
Example
#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)
#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
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.
#stores all the data of the file into the variable content
content = fileptr.readlines()
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.
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.
#after the read operation file pointer modifies. tell() returns the location of the
fileptr.
For this purpose, the Python provides us the seek() method which enables us to
modify the file pointer position externally.
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.
Example
# open the file file2.txt in read mode
fileptr = open("file2.txt","r")
SN Method Description
7 File.readline([size]) It reads one line from the file and places the 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.
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.
Example:
import file;
name = input("Enter the name?")
file.displayMsg(name)
calculation.py:
Main.py:
syntax.
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.
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.
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.
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.
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()
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
else:
#block of code
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.
Syntax
try:
# block of code
# this may throw an exception
finally:
# block of code
# this will always be executed
Example
try:
fileptr = open("file2.txt","r")
try:
fileptr.write("Hi I am good")
finally:
fileptr.close()
print("file closed")
except:
print("Error")