Introduction to Python Programming
Introduction to Python Programming
Python is a widely used general-purpose, high level programming language. It was initially designed
by Guido van Rossum in 1991 and developed by Python Software Foundation. It was mainly
developed for emphasis on code readability, and its syntax allows programmers to express concepts
in fewer lines of code.
Python is a programming language that lets you work quickly and integrate systems more efficiently.
The chevron at the beginning of the 1st line, i.e., the symbol >>> is a prompt the python interpreter
uses to indicate that it is ready. If the programmer types 2+6, the interpreter replies 8.
3
DATA TYPES
The data stored in memory can be of many types. Python has various standard data types that are
used to define the operations possible on them and the storage method for each of them.
1) Int: Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length.
>>> print(357654+2) >>> print(20) >>> print(0b10) # To verify the type of any object in
357656 20 2 Python, use the type() function:
>>> a=10 >>> print(0X20) >>> type(10) >>> a=11
>>> print(a) 32 <class 'int'> >>> print(type(a))
10 <class 'int'>
2) Float: Float, or "floating point number" is a number, positive or negative, containing one or more
decimals. Float can also be scientific numbers with an "e" to indicate the power of 10.
>>> y=2.8 >>> y=2.8 >>> type(.4)
>>> y >>> print(type(y)) <class 'float'>
2.8 <class 'float'>
3) Boolean: Objects of Boolean type may have one of two values, True or False:
>>> type(True) >>> type(False)
<class 'bool'> <class 'bool'>
4) String: Strings in Python are identified as a contiguous set of characters represented in the
quotation marks. Python allows for either pairs of single or double quotes. Ex: 'hello' is the same as
"hello". Strings can be output to screen using the print function. For example: print("hello").
>>> print("Hello") >>> type("Hello") >>> " " >>>x = 35
Hello <class 'str'> '' >>>print(f “x = {x}”)
If you want to include either type of quote character within the string, the simplest way is to delimit
the string with the other type. If a string is to contain a single quote, delimit it with double quotes and
vice versa:
>>> print("It's good") >>> print('It"s good')
It's good It"s good
5) List: It is a general purpose most widely used in data structures. List is a collection which is
ordered and changeable and allows duplicate members. (Grow and shrink as needed, sequence
type, sortable). To use a list, you must declare it first. Do this using square brackets and separate
values with commas. We can construct / create list in many ways.
>>> list1=[1,2,3,'A','B',7,8,[10,11]] >>> x=list() >>> tuple1=(1,2,3,4)
>>> print(list1) >>> x >>> x=list(tuple1)
[1, 2, 3, 'A', 'B', 7, 8, [10, 11]] [] >>> x
[1, 2, 3, 4]
Variables
Variables are nothing but reserved memory locations to store values. This means that when you
create a variable you reserve some space in memory. Based on the data type of a variable, the
4
interpreter allocates memory and decides what can be stored in the reserved memory. Therefore, by
assigning different data types to variables, you can store integers, decimals or characters in these
variables.
Output Variables:
The Python print statement is often used to output variables.
Variables do not need to be declared with any particular type and can even change type after they
have been set.
x = 5 # x is of type int print(x)
x = "mrcet " # x is now of type str Output: mrcet
To combine both text and a variable, Python uses the “+” character:
x = "awesome" Output x = "Python is " Output:
print("Python is " + x) Python is awesome y = "awesome" Python is awesome
z=x+y
print(z)
Expressions
An expression is a combination of values, variables, and operators. An expression is evaluated using
assignment operator. Examples: Y = x + 17
>>> x=10 >>> z
>>> z=x+20 30
A value all by itself is a simple expression, and so is a variable.
>>> y=20 20
>>> y
Python also defines expressions that only contain identifiers, literals, and operators. So,
Identifiers: Any name that is used to define a class, function, variable module, or object is an
identifier.
Literals: These are language-independent terms in Python and should exist independently in any
programming language. In Python, there are the string literals, byte literals, integer literals, floating
point literals, and imaginary literals.
5
OPERATORS
In Python you can implement the following operations using the corresponding tokens.
Operator Token Operator Token Logical Operators Assigment
add + Bitwise NOT ~ and Operators
subtract - Binary left shift << or = , +=, - =
multiply * Binary right shift >> not *=, /=, %=
Integer Division / Less than < //=, **=, &=
remainder % Greater than > This is allowed |=, ^=, >>=
Exponentiation ** Less than or equal to <= E.g: 60 <= x >= 100. <<=
Bitwise AND & Greater than or equal to >= It means:
Bitwise OR | Check equality == x>=60 and x<=100 ++ and - - are
Bitwise XOR ^ Check not equal != not allowed.
Precedence of Operators:
Operator precedence affects how an expression is evaluated. For example, x = 7 + 3 * 2; here, x is
assigned 13, not 20 because operator * has higher precedence than +, so it first multiplies 3*2 and
then adds into 7. However, parentheses () overrides the precedence of the arithmetic operators. For
example, x = (7 + 3) * 2; here, x is 20 because of the parentheses.
Comments
i) Single-line comment begins with a hash (#) symbol and is useful in mentioning that the
whole line should be considered as a comment until the end of line.
ii) A Multi line comment is useful when we need to comment on many lines. In python, triple
double quote (“ “ “) and single quote(‘ ‘ ‘)are used for multi-line commenting.
Example: Output:
30
Modules
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.
A module in Python provides us the flexibility to organize the code in a logical way. To use the
functionality of one module into another, we must have to import the specific module.
Syntax:
import <module-name>
Every module has its own functions, those that can be accessed with . (dot)
Note: In python we have help (). Enter the name of any module, keyword, or topic to get help on
writing Python programs and using Python modules. To quit this help utility and return to the
interpreter, just type "quit".
Some of the modules like math, os, date, and calendar so on……
>>> import sys >>>import calendar
>>> print([Link]) or print(sys.version_info) >>> print([Link](2020))
3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, True
[Link]) [MSC v.1916 32 bit (Intel)] >>> print([Link](2021,5))
6
>>>import math
>>>[Link](9)
3.0
>>>[Link](2,5) #discuss the output
Output:
#example for flow of execution welcome
print("welcome") 0
for x in range(3): 1
print(x) 2
print("Good morning college") Good morning college
#The flow/order of execution is: 2,3,4,3,4,3,4,5
7
(c) Parameters (arguments) through which we pass values to a function. They are optional.
(d) A colon (:) to mark the end of function header.
(e) Optional documentation string (docstring) to describe what the function does.
(f) One or more valid python statements that make up the function body. Statements must have
same indentation level (usually 4 spaces).
(g) An optional return statement to return a value from the function. Any function that returns a
value is called Fruitful function. A function that does not return a value is called a Void
function.
There are three types of Python function arguments using which we can call a function.
1) Default Arguments
2) Keyword Arguments
3) Variable-length Arguments
The return statement is used to exit a function and go back to the place from where it was called.
This statement can contain expression which gets evaluated and the value is returned. If there is no
expression in the statement or the return statement itself is not present inside a function, then the
function will return the None object.
#Keyword Arguments
When we call a function with some values, these values get assigned to the arguments according to
their position. Python allows functions to be called using keyword arguments. When we call
functions in this way, the order (position) of the arguments can be changed. (Or)
If you have some functions with many parameters and you want to specify only some of them, then
you can give values for such parameters by naming them - this is called keyword arguments - we use
the name (keyword) instead of the position to specify the arguments to the function.
There are two advantages – (1) Using the function is easier since we do not need to worry about the
order of the arguments. (2) we can give values to only those parameters which we want, provided
that the other parameters have default argument values.
>>>def func(a, b=5, c=10): Output:
… print 'a is', a, 'and b is', b, 'and c is', c a is 3 and b is 7 and c is 10
>>>func(3, 7) a is 25 and b is 5 and c is 24
>>>func(25, c=24) a is 100 and b is 5 and c is 50
>>>func(c=50, a=100)
>>>def print_name(name1, name2): Output:
… """ This function prints the name """ B and A are friends
…. print (name1 + " and " + name2 + " are friends")
>>>#calling the function
>>>print_name(name2 = 'A',name1 = 'B')
#Default Arguments
Function arguments can have default values in Python. We can provide a default value to an
argument by using the assignment operator (=).
8
>>>def hello(wish,name='you'): Output:
… return '{},{}'.format(wish,name) good morning,you
>>>print(hello("good morning"))
Note: Any number of arguments in a function can have a default value. But once we have a default
argument, all the arguments to its right must also have default values. This means to say, non-default
arguments cannot follow default arguments. For example, if we had defined the function header
above as:
def hello(name='you', wish):
Syntax Error: non-default argument follows default argument
>>>def sum(a=4, b=2): #2 is supplied as default argument >>>sum(1,2) #calling with args
… """ This function will print sum of two numbers if >>>sum( ) #calling without args
… the arguments are not supplied. it will add the default Output:
… value """ 3
… print (a+b) 6
#Variable-length arguments
Sometimes you may need more arguments to process function then you mentioned in the definition.
If we don’t know in advance about the arguments needed in function, we can use variable-length
arguments also called arbitrary arguments.
For this an asterisk (*) is placed before a parameter in function definition which can hold non-
keyworded variable-length arguments and a double asterisk (**) is placed before a parameter in
function which can hold keyworded variable-length arguments. If we use one asterisk (*) like *var,
then all the positional arguments from that point till the end are collected as a tuple called ‘var’ and if
we use two asterisks (**) before a variable like **var, then all the positional arguments from that
point till the end are collected as a dictionary called ‘var’.
>>>def wish(*names): Output:
… """This function greets all Hello MRCET
… the person in the names tuple.""" Hello CSE
… # names is a tuple with arguments Hello SIR
… for name in names: Hello MADAM
… print("Hello",name)
>>>wish("MRCET","CSE","SIR","MADAM")
Conditional (if):
The if statement contains a logical expression using
which data is compared and a decision is made based on
the result of the comparison.
Syntax:
if expression:
statement(s)
If the boolean expression evaluates to TRUE, then the
block of statement(s) inside the if statement is executed.
If boolean expression evaluates to FALSE, then the first
set of code after the end of the if statement(s) is
executed.
10
Alternative if (If-Else):
An else statement can be combined with an if statement. If - else Flowchart :
An else statement contains the block of code (false
block) that executes if the conditional expression in the
if statement resolves to 0 or a FALSE value. The else
statement is an optional statement and there could be at
most only one else Statement following if.
Syntax of if - else :
if test expression:
Body of if stmts
else:
Body of else stmts
ITERATION
A loop statement allows us to execute a statement or group of statements multiple times as long as
the condition is true. Repeated execution of a set of statements with the help of loops is called
iteration. Loops statements are used when we need to run same code again and again, each time with
a different value.
In Python Iteration (Loops) statements are of three types: While Loop, For Loop and Nested For
Loops
While loop:
Loops are either infinite or conditional. Python while
loop keeps reiterating a block of code defined inside it
until the desired condition is met.
The while loop contains a boolean expression and the
code inside the loop is repeatedly executed as long as
the boolean expression is true.
The statements that are executed inside while can be a
single line of code or a block of multiple statements.
Syntax:
while(expression):
Statement(s)
i=1 Output a=1 Output
while (i < 7): 1 while (a<10): 1
print (i) 2 print (a) 2
11
i = i+1 3 a=a+1 3
4 if (a == 4): While loop
5 print ('While loop terminated') terminated
6 break
For loop:
Python for loop is used for repeated execution of a group of statements for the desired number of
times. It iterates over the items of lists, tuples, strings, the dictionaries and other iterable objects
Sample Program:
Iterating over a Output #list of items
List: 1 list = ['FSS','Sasa','Ibadan']
num = [1, 2, 4, 6] 4 i=1
seq=0 16 #Iterating over the list
for val in num: 36 for item in list:
seq=val*val print ('Item ',i,' is ',item)
print(seq) i = i+1
Output
Item 1 is FSS
Item 2 is Sasa
Item 3 is Ibadan
Iterating over a Tuple: Iterating over a Dictionary: Iterating over a String:
tuple = (2,3,5,7) #creating a dictionary #declare a string to iterate over
print ('These are the first college = x = 'MOWEMI'
four prime numbers ') {"csc":"4flat","bam":"Ykale",
#Iterating over the tuple "lib":"ccblock"} #Iterating over the string
for a in tuple: for leta in x:
#Iterating over the dictionary to print
print (a) keys… print (leta)
Output: print ('Keys are:')
These are the first four for keys in college: Output:
prime numbers print(keys) M
2 O
3 #Iterating over the dictionary to print W
5 values… E
7 print ('Values are:') M
for blocks in [Link](): I
print(blocks)
Output:
Keys are: Values are:
csc 4flat
bam Ykale
lib ccblock
Pass:
In Python programming, pass is a null statement. The difference between a comment and pass
statement in Python is that, while the interpreter ignores a comment entirely, pass is not ignored.
pass is just a placeholder for functionality to be added later.
Example:
>>>sequence = {'p', 'a', 's', 's'} Output:
>>>for val in sequence: #Nothing is printed.
… pass
Similarily we can also write,
def f(arg): pass # a function that does nothing (yet)
class C: pass # a class with no methods (yet
PRACTICE QUESTIONS:
Write python program (use function, as well) to compute the following:
1) Area of a circle
2) Absolute value of any number; don't use built-in function.
13
3) Write a Python function that takes two lists and returns True if they have at least one
common member.
MORE ON FUNCTIONS
Global Scope:
A variable which is defined in the main body of a file is called a global variable. It will be visible
throughout the file, and also inside any file which imports that file.
The variable defined inside a function can also be made global by using the global statement.
# use Global variable and Local variable with same name >>>f4()
>>>x = 5 >>>print("global x:", x)
>>>def f4(): Output:
… x = 10 local x: 10
… print("local x:", x) global x: 5
Recursion:
Recursion is the process of defining something in terms of itself. That is, function calling itself.
# Write a program to factorial using recursion print("zero factorial", fact(0))
def fact(x): print("five factorial", fact(5))
if x==0:
result = 1 Output:
else : zero factorial 1
result = x * fact(x-1) five factorial 120
return result
Strings:
A string is a group or a sequence of characters. Since Python has no provision for arrays, we simply
use strings. This is how we declare a string. We can use a pair of single or double quotes. Every
string object is of the type ‘str’.
>>> type("name") >>> a=str('mrcet') >>> a=str(mrcet) >>> fruit = 'banana'
<class 'str'> >>> a >>> a[2] >>> letter = fruit[1]
>>> name=str() 'mrcet' 'c' >>> letter
>>> name 'a'
‘’
The second statement selects character number 1 from fruit and assigns it to letter. The expression in
brackets is called an index. The index indicates which character in the sequence we want.
String slices:
A segment of a string is called a slice. Selecting a slice is similar to selecting a character: Subsets of
strings can be taken using the slice operator ([ ] and [:]) with indexes starting at 0 in the beginning of
the string and working their way from -1 at the end.
Example 1: Output:
str = 'Hello World!'
print str # Prints complete string Hello World!
print str[0] # Prints first character of the string H
print str[2:5] # Prints characters starting from 3rd to 5th llo
print str[2:] # Prints string starting from 3rd character print llo World!
str * 2 # Prints string two times Hello World!Hello World!
print str + "TEST" # Prints concatenated string Hello World!TEST
Example 2: Output
>>> x='computer'
>>> x[1:4] 'omp'
>>> x[Link] 'opt'
>>> x[3:] 'puter'
>>> x[:5] 'compu'
>>> x[-1] 'r'
>>> x[-3:] 'ter'
>>> x[:-2] 'comput'
>>> x[::-2] 'rtpo'
>>> x[::-1] 'retupmoc'
Immutability:
It is tempting to use the [] operator on the left side of an assignment, with the intention of changing a
character in a string.
For example:
>>> greeting='mrcet college!'
>>> greeting[0]='n'
TypeError: 'str' object does not support item assignment.
The reason for the error is that strings are immutable, which means we can’t change an existing
string. The best we can do is creating a new string that is a variation on the original:
>>> greeting = 'Hello, world!' >>> new_greeting
>>> new_greeting = 'J' + greeting[1:] 'Jello, world!'
Note: The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition
operator.
String module:
This module contains a number of functions to process standard Python strings. In recent versions,
most functions are available as string methods as well. It’s a built-in module and we have to import it
before using any of its constants and classes.
Syntax: import string
Note: help(string) --- gives the information about all the variables ,functions, attributes and classes to
be used in string module.
Example: Output:
import string
print(string.ascii_letters) abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLM…RSTUVWXYZ
print(string.ascii_lowercase) abcdefghijklmnopqrstuvwxyz
print(string.ascii_uppercase) ABCDEFGHIJKLMNOPQRSTUVWXYZ
print([Link]) 0123456789
print([Link]) 0123456789abcdefABCDEF
print([Link])
print([Link]) !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
PYTHON ARRAYS
Array is a container which can hold a fix number of items and these items should be of the same
type. Most of the data structures make use of arrays to implement their algorithms.
Following are the important terms to understand the concept of Array.
Element − Each item stored in an array is called an element.
Index − Each location of an element in an array has a numerical index, which is used to
identify the element.
Array Representation
Arrays can be declared in various ways in different languages. Below is an illustration.
As per the above illustration, following are the important points to be considered.
Index starts with 0.
Array length is 10 which means it can store 10 elements.
16
Each element can be accessed via its index. For example, we can fetch an element at index 6
as 70
Basic Operations
Following are the basic operations supported by an array.
i) Traverse − print all the array elements one by one.
ii) Insertion − Adds an element at the given index.
iii) Deletion − Deletes an element at the given index.
iv) Search − Searches an element using the given index or by the value.
v) Update − Updates an element at the given index.
Array is created in Python by importing array module to the python program. Then the array is
declared as shown below.
from array import *
arrayName=array(typecode, [initializers])
Typecode are the codes that are used to define the type of value the array will hold. Some common
typecodes used are:
Typecode Value
b Represents signed integer of size 1 byte
B Represents unsigned integer of size 1 byte
c Represents character of size 1 byte
i Represents signed integer of size 2 bytes
I Represents unsigned integer of size 2 bytes
f Represents floating point of size 4 bytes
d Represents floating point of size 8 bytes
Creating an array: Output:
from array import * 10
array1 = array('i', [10,20,30,40,50]) 20
for x in array1: 30
print(x) 40
50
Accessing Array Element Output:
We can access each element of an 10
array using the index of the element. 30
from array import *
array1 = array('i', [10,20,30,40,50])
print (array1[0])
print (array1[2])
Array methods:
Python has a set of built-in methods that you can use on lists/arrays.
Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the first item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list
17
Note: Python does not have built-in support for Arrays, but Python Lists can be used instead.
Example:
>>> college=["mrcet","it","cse"] >>> [Link]("eee") >>> [Link]()
>>> [Link]("auto") >>> [Link]("ece") 'ece'
>>> college >>> college
['mrcet', 'it', 'cse', 'auto'] ['mrcet', 'it', 'cse', 'auto', 'eee', 'ece']
>>> college >>> [Link](4) >>> college
['mrcet', 'it', 'cse', 'auto', 'eee'] 'eee' ['mrcet', 'it', 'cse', 'auto']
>>> [Link]("it")
>>> college
['mrcet', 'cse', 'auto'] (Practice more)
List operations:
These operations include indexing, slicing, adding, multiplying, and checking for membership.
18
>>> list1=[1,2,3,4,5,6,7,8,9,10] >>> list1[:6] >>> list1[Link]
>>> list1[1:] [1, 2, 3, 4, 5, 6] [2, 4, 6, 8]
[2, 3, 4, 5, 6, 7, 8, 9, 10]
List methods:
The list data type has some more methods. Here are all of the methods of list objects:
Del() Append() Extend() Insert()
>>> x=[5,3,8,6] >>> x=[1,5,8,4] >>> x=[1,2,3,4] >>> x=[1,3,4,6,7]
>>> del(x[1]) >>> [Link](10) >>> y=[3,6,9,1] >>> [Link](2,10)
>>> x >>> x >>> [Link](y) >>> x
[5, 8, 6] [1, 5, 8, 4, 10] >>> x [1, 3, 10, 4, 6, 7]
[1, 2, 3, 4, 3, 6, 9, 1]
Pop() Remove() Reverse() Sort()
>>> x=[1,2,10,4,6,7] >>> x=[1,33,2,10,4,6] >>> x=[1,2,3,4,5,6,7] >>> x=[10,1,5,3,8,7]
>>> [Link]() >>> [Link](33) >>> [Link]() >>> [Link]()
7 >>> x >>> x >>> x
>>> [Link](2) [1, 2, 10, 4, 6] [7, 6, 5, 4, 3, 2, 1] [1, 3, 5, 7, 8, 10]
10
More Program Examples
>>> x=[m for m in range(8)] >>>x=[z**2 for z in range(10) if z>4]
>>> print(x) >>> print(x)
[0, 1, 2, 3, 4, 5, 6, 7] [25, 36, 49, 64, 81]
>>>x=[x**2 for x in range (1,11) if x%2 == 1] >>> a=5
>>> print(x) >>> table = [[a, b, a * b] for b in range(1, 11)]
[1, 9, 25, 49, 81] >>> for i in table:
print(i) (Discuss the output)
Tuples:
A tuple is a collection which is ordered and unchangeable. In Python tuples are written with round
brackets.
Supports all operations for sequences.
Immutable, but member objects may be mutable.
If the contents of a list shouldn’t change, use a tuple to prevent items from accidently being
added, changed, or deleted.
Tuples are more efficient than list due to python’s implementation.
We can construct tuple in many ways:
X=() #no item tuple
X=(1,2,3)
X=tuple(list1)
X=1,2,3,4
Some of the operations of tuple are:
Access tuple items Change tuple items Loop through a tuple
>>> x=('a','b','c','g') Once a tuple is created, you cannot >>> x=4,5,6,7,2,'aa'
>>> print(x[2]) change its values. Tuples are >>> for i in x:
c unchangeable. print(i)
x=(2,5,7,'4',8)
x[1]=1 (Check the output)
Count() Index() Len()
>>>x=(1,2,3,4,5,6,2,10,2,11,12,2) >>>x=(1,2,3,4,5,6,2,10,2,11,12,2) >>> x=(1,2,3,4,5,6,2,10,2)
>>>[Link](2) >>> [Link](2) >>> y=len(x)
4 1 >>> print(y)
9
19
Functions can return tuples as
return values. c = 2 * 3.14159 * r
def circleInfo(r): a = 3.14159 * r * r Output:
""" Return (circumference, return (c, a)
area) of a circle of radius r """ print(circleInfo(10)) (62.8318, 314.159)
Pop Quiz
Question: Answer:
Create a list of 2-tuples like >>> z=[(x, x**2) for x in range(6)]
(number, square). >>> z
[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
Dictionaries:
A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are
written with curly brackets, and they have keys and values.
Key-value pairs
Unordered
We can construct or create dictionary like:
X= {1:’A’,2:’B’,3:’c’} OR X= dict([(‘a’,3) (‘b’,4)]) OR X= dict(‘A’=1,’B’=2)
20
>>>print(items) >>>print(i)
brand ('brand', 'mrcet')
model ('model', 'college')
year ('year', 2004)
An exception is an event, which occurs during the execution of a program that disrupts the normal
flow of the program's instructions. In general, when a Python script encounters a situation that it
cannot cope with, it raises an exception. An exception is a Python object that represents an error.
Text files:
We can create the text files by using the syntax:
Variable name=open (“[Link]”, file mode)
For ex: f= open ("[Link]","w+")
We declared the variable f to open a file named [Link]. Open takes 2 arguments, the file that we
want to open and a string that represents the kinds of permission or operation we want to do on the
file. Here we used "w" letter in our argument, which indicates write and the plus sign that means it
will create a file if it does not exist in library.
22
programming") Programming")
[Link]() print([Link]())
[Link]()
Python has many built-in exceptions which forces your program to output an error when something
in it goes wrong. In Python, users can define such exceptions by creating a new class. This exception
class has to be derived, either directly or indirectly, from Exception class.
Different types of exceptions:
ArrayIndexOutOfBoundException.
ClassNotFoundException.
FileNotFoundException.
IOException.
InterruptedException.
NoSuchFieldException.
NoSuchMethodException
Handling Exceptions:
The cause of an exception is often external to the program itself. For example, an incorrect input, a
malfunctioning IO device etc. Because the program abruptly terminates on encountering an
exception, it may cause damage to system resources, such as files. Hence, the exceptions should be
properly handled so that an abrupt termination of the program is prevented.
Python uses try and except keywords to handle exceptions. Both keywords are followed by indented
blocks.
23
Syntax:
try :
#statements in try block
except :
#executed when error in try block
Typically we see, most of the times
1. Syntactical errors (wrong spelling, colon ( : ) missing ….), At developer level and compile
level it gives errors.
2. Logical errors (2+2=4, instead if we get output as 3 i.e., wrong output …..,), As a developer
we test the application, during that time logical error may obtained.
3. Run time error (In this case, if the user doesn’t know to give input, 5/6 is ok but if the user
say 6 and 0 i.e.,6/0 (shows error a number cannot be divided by zero)). This is not easy
compared to the above two errors because it is not done by the system, it is (mistake) done by
the user.
24