Unit 2 Exception in python-1
Unit 2 Exception in python-1
Unit-2
Unit 2
Exception Handling
Exception Handling
Exceptions are raised when the program is syntactically correct, but the
code resulted in an error. This error does not stop the execution of the
program, however, it changes the normal flow of the program.
Example
# initialize the amount variable
marks = 10000
# perform division with 0
a = marks / 0
print(a)
Output:
Exception Description
IndexError When the wrong index of a list is retrieved.
AssertionError It occurs when the assert statement fails
AttributeError It occurs when an attribute assignment is failed.
ImportError It occurs when an imported module is not found.
KeyError It occurs when the key of the dictionary is not found.
NameError It occurs when the variable is not defined.
MemoryError It occurs when a program runs out of memory.
It occurs when a function and operation are applied in
TypeError
an incorrect type.
Errors in Python
Errors are the problems in a program due to which the program will stop
the execution. On the other hand, exceptions are raised when some
internal events occur which changes the normal flow of the program.
1) Syntax errors
When the proper syntax of the language is not followed then a syntax
error is thrown.
Example
# initialize the amount variable
amount = 10000
# check that You are eligible to
# purchase Python Software or not
if(amount>2999)
print("You are eligible to purchase Python Software ")
Output:
2) logical errors(Exception)
When in the runtime an error that occurs after passing the syntax test is
called exception or logical type.
For example, when we divide any number by zero then the
“ZeroDivisionError” exception is raised, or when we import a module
that does not exist then “ImportError” is raised.
Example
# initialize the amount variable
marks = 10000
# perform division with 0
a = marks / 0
print(a)
Output:
Exception Handling
When an error and an exception are raised then we handle that with the
help of the Handling method.
To handle the exception, we have put the code,
result = numerator/denominator inside the try block.
Now when an exception occurs, the rest of the code inside the try block is
skipped. The except block catches the exception and statements inside
the except block are executed.
Example: Let us try to access the array element whose index is out of
bound and handle the corresponding exception.
a = [1, 2, 3]
try:
print ("Second element = %d" %(a[1]))
# Throws error since there are only 3 elements in array
print ("Fourth element = %d" %(a[3]))
except:
print ("An error occurred")
Output:
Second element = 2
An error occurred
In the above example, the statements that can cause the error are
placed inside the try statement (second print statement in our
case).
The second print statement tries to access the fourth element of the
list which is not there and this throws an exception.
This exception is then caught by the except statement.
try:
# statement(s)
except IndexError:
# statement(s)
except ValueError:
# statement(s)
Example:
#Program for multiple catch statement
# Program to handle multiple errors with one
# except statement
def fun(a):
if a < 4:
# throws ZeroDivisionError for a = 3
b = a/(a-3)
# throws NameError if a >= 4
print("Value of b = ", b)
try:
fun(3)
fun(5)
Output
ZeroDivisionError Occurred and Handled
If you comment on the line fun(3), the output will be
NameError Occurred and Handled
Example:
# Python program to demonstrate finally
# No exception Exception raised in try block
try:
k = 5//0 # raises divide by zero exception.
print(k)
# handles zerodivision exception
except ZeroDivisionError:
print("Can't divide by zero")
finally:
# this block is always executed
# regardless of exception generation.
print('This is always executed')
Output:
Can't divide by zero
This is always executed
Python Functions
Python Functions is a block of statements that return the specific task.
The idea is to put some commonly or repeatedly done tasks together
and make a function so that instead of writing the same code again and
again for different inputs, we can do the function calls to reuse code
contained in it over and over again.
General syntax is
def function_name(arguments):
# function body
return
Example
def greet():
print('Hello World!')
Here, we have created a function named greet(). It simply prints the text
Hello World!.
Example
# A simple Python function
def fun():
print("Welcome to AESNC")
calling a Function
After creating a function we can call it by using the name of the function
followed by parenthesis containing parameters of that particular function.
Example:
# A simple Python function
def fun():
print("Welcome to AESNC")
# Driver code to call a function
fun()
Output:
Welcome to AESNC
example,
def add_numbers():
....................
return sum
Here, we are returning the variable sum to the function call.
Example
# function definition
def find_square(num):
result = num * num
return result
# function call
square = find_square(3)
print('Square:',square)
Output: Square: 9
Output
Emil ABC
Tobias ABC
Linus ABC
Example
# function with two arguments
def add_num(num1, num2):
sum = num1 + num2
print('Sum: ',sum)
# function with no argument
def add_num():
Example
# function call with two values
add_num(5, 4)
# function call with no value
add_num()
Output:
Sum: 9
Python parameters
Parameters in python are variables — placeholders for the actual
values the function needs. When the function is called, these values
are passed in as arguments.
For example, the arguments passed into the function
"""Docstring"""
# body of the function
return expression
These library functions are defined inside the module. And, to use them
we must include the module inside our program.
Types of Function
There are two types of function in Python programming:
Standard library functions - These are built-in functions in
Python that are available to use.
User-defined functions - We can create our own functions based
on our requirements.
Default arguments
In Python, we can provide default values to function arguments. We use
the ” = “ Assignment operator to provide default values.
In other words, Default values indicate that the function argument will
take that value if no argument value is passed during the function call.
The default value is assigned by using the assignment(=) operator of the
form ”keywordname=value“.
Example
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function() #It will take default values i.e Norway
my_function("Brazil")
Output
I am from Sweden
I am from India
I am from Norway
I am from Brazil
sys.argv
In python sys module stores the command line arguments into a list, we
can access it using sys.argv. This is very useful and simple way to read
command line arguments as String.
import sys #first we have to write this before starting the program
print (sys.argv) #we have to access the elements i.e arguments printed in
#the program
Working
Write a program in python IDE.Save a file in python folder as
cmd.py
Example: import sys
Print (sys.argv)
Go with the command prompt and paste the location of the file.
It will display as
[‘cmd.py’, ‘1’, ‘2’, ‘3’, ‘4’, ‘5’ ]
6
II BCA, IV sem Python Programming
16
Divya S R, Assistant Professor, AESNC, Gauribidanur. Unit-2
getopt()
The getopt module helps us parse the options and operands that are
provided to our program on the command line. This module has one very
important function, also named getopt.
Syntax:
getopt.getopt( args , options ,< long_options>) → ( options, operands )
args is the argument list to be passed. The args value should not
include sys.argv[0], the program name. Therefore, the argument
value for args is almost always sys.argv[1:].
options is the string of options letter that the script wants to
recognize.
long_options is the list of strings with names of the long options
which should be supported.
It returns the list of (option, value/operands) pairs and list of program
arguments left after the option list was stripped.
Example
import sys
import getopt
def full_name():
first_name = None
last_name = None
argv = sys.argv[1:]
try:
opts, args = getopt.getopt(argv, "f:l:")
except:
print("Error")
full_name()
output:
argparse
The argparse module makes it easy to write user-friendly
command-line interfaces. It parses the defined arguments from the
sys.argv.
The argparse module also automatically generates help and usage
messages, and issues errors when users give the program invalid
arguments.
The argparse is a standard module; we do not need to install it.
A parser is created with ArgumentParser and a new parameter is
added with add_argument. Arguments can be optional, required,
or positional.
Example
team("Divya", "Setty")
In the example above, the function arguments are Divya and Setty,
whereas name and surname are the function parameters.
Types of Arguments
There are two types of arguments:
positional arguments
keyword arguments.
Positional arguments
Positional arguments are values that are passed into a function
based on the order in which the parameters were listed during the
function definition.
Here, the order is especially important as values passed into these
functions are assigned to corresponding parameters based on their
position.
Example
Output:
Ram is working as an Assistant Professor
Keyword arguments
Keyword arguments (or named arguments) are values that, when passed
into a function, are identifiable by specific parameter names. A keyword
argument is preceded by a parameter and the assignment operator, = .
Example
def team(name, project):
print(name, "is working on an", project)
team(project = "Edpresso", name = 'FemCode')
Output:
FemCode is working on an Edpresso
Recursive Functions
“Recursion is the process of defining something in terms of itself”.
we know that a function can call other functions. It is even possible for
the function to call itself. These types of construct are termed as recursive
functions.
The following image shows the working of a recursive function called
recurse.
Example
def factorial(x):
"""This is a recursive function
to find the factorial of an integer"""
if x == 1:
return 1
else:
return (x * factorial(x-1))
num = 3
print("The factorial of", num, "is", factorial(num))
Output
The factorial of 3 is 6
Note:
To create strings that span multiple lines, triple single quotes '''.
Triple double quotes """ are used to enclose the string.
Local Variable
Local Variables inside a function in Python
In the local variable, we will declare the variable inside the function.
Here funt() is the function name.
‘x’ is the variable.
For example
def funt(): //it is function
x='hello local variable' //variable inside function
print(x)
funt() //here it is function call
output
hello local variable
Global Variable
In Python, a variable declared outside of the function or in global scope is
known as a global variable. This means that a global variable can be
accessed inside or outside of the function.
Example
# declare global variable
message = 'Hello'
def greet():
# declare local variable
print('Local', message)
greet()
print('Global', message)
Output
Local Hello
Global Hello
Nonlocal Variables
In Python, nonlocal variables are used in nested functions whose
local scope is not defined. This means that the variable can be neither
in the local nor the global scope.
We use the nonlocal keyword to create nonlocal variables.
For example
# outside function
def outer():
message = 'local'
# nested function
def inner():
inner()
print("outer:", message)
outer()
output
inner: nonlocal variable
outer: nonlocal variable
Strings
Definition
Strings in python are surrounded by either single quotation marks, or
double quotation marks. 'hello' is the same as "hello".
Example
#You can use double or single quotes:
print("Hello")
print('Hello')
Output:
Hello
Hello
Example
#Using single quotes
str1 = 'Hello Python'
print(str1)
#Using double quotes
str2 = "Hello Python"
print(str2)
#Using triple quotes
str3 = “”””Triple quotes are generally used for
represent the multiline or
docstring”””
print(str3)
Output:
Hello Python
Hello Python
Triple quotes are generally used for
represent the multiline or
docstring
Note:
Multiline String
We can also create a multiline string in Python. For this, we use triple
double quotes """ or triple single quotes '''. For example,
Example
# multiline string
message = """
Never gonna give you up
Never gonna let you down
"""
print(message)
Output
Never gonna give you up
Never gonna let you down
For example
greet = 'hello'
# access 1st index element
print(greet[1])
Output:
e
For example 1
greet = 'hello'
# access 4th last element
print(greet[-4])
Output:
e
Example 2
str = 'Hellow World!'
print(str [0:-6]) # output is Hellow
print(str [7:-1]) # output is World
Example
greet = 'Hello'
# access character from 1st index to 3rd index
print(greet[1:4])
output
ell
Syntax
str(object, encoding=encoding, errors=errors)
Parameter Description
object Any object. Specifies the object to convert into a string
encoding The encoding of the object. Default is UTF-8
Specifies what to do if the decoding fails. a response when
errors
decoding fails (can be strict, ignore, replace, etc)
Example
str(object, encoding=’utf-8?, errors=’strict’)
Example 1:
# string representation of Divya
print(str('Divya'))
Output: Divya
Example 2:
x = str(3.5)
print(x)
Output: 3.5
Example 3:
# string representation of Luke
name = str('Luke')
print(name)
# string representation of an integer 40
age = str(40)
print(age)
# string representation of a numeric string 7ft
height = str('7ft')
print(height)
Output
Luke
40
7ft
In the above example, we have used the str() method with different
types of arguments like string, integer, and numeric string.
Note:
Errors in String
There are six types of error taken by this function.
strict (default): it raises a UnicodeDecodeError.
ignore: It ignores the unencodable Unicode
replace: It replaces the unencodable Unicode with a question mark
xmlcharrefreplace: It inserts XML character reference instead of
the unencodable Unicode
backslashreplace: inserts a \uNNNN Espace sequence instead of
unencodable Unicode
namereplace: inserts a \N{…} escape sequence instead of an
unencodable Unicode
Operations on Strings
1. Compare Two Strings
We use the equals == operator to compare two strings. If two strings
are equal, the operator returns True. Otherwise, it returns False.
For example
str1 = "Hello, world!"
str2 = "I love Python."
str3 = "Hello, world!"
# compare str1 and str2
print(str1 == str2)
# compare str1 and str3
print(str1 == str3)
Output
False
True
Example
greet = "Hello, "
name = "Jack"
# using + operator
result = greet + name
print(result)
3.String Length
In Python, we use the len() method to find the length of a string.
Example
greet = 'Hello'
# count length of greet string
print(len(greet))
Output: 5
Methods Description
Output:
yttesayvid
We can also reverse a string by using built-in join and reversed function.
Example
# Program to reverse a string
gfg = "geeksforgeeks"
# Reverse the string using reversed and join function
gfg = "".join(reversed(gfg))
print(gfg)
Output:
skeegrofskeeg
5. String Comparison
The relational operators compare the Unicode values of the characters of
the strings from the 0th index till the end of the string. It then returns a
boolean value according to the operator used.
Example
print("Geek" == "Geek")
print("Geek" < "geek")
print("Geek" > "geek")
print("Geek" != "Geek")
output
True
True
False
False
Join()
The join function is a more flexible way for concatenating string. With join
function, you can add any character into the string.
If you want to add a colon (:) after every character in the string “Python”
you can use the following code.
Example
print(":".join("Python"))
Output
P:y:t:h:o:n
Split()
Split strings is another function that can be applied in Python.
First here we will split the string by using the command ”word.split”
and get the result.
Output
['AES', 'College', 'GBD']
7. Traversing
Traversing a string means accessing all the elements of the string
one after the other by using the subscript. A string can be traversed
using for loop or while loop.
Example
For while loop
In Python, a while loop may have an optional else block.
Here, the else part is executed after the condition of the loop evaluates to
False.
Example
counter = 0
while counter < 3:
print('Inside loop')
counter = counter + 1
else:
print('Inside else')
Output
Inside loop
Inside loop
Inside loop
Inside else
For loop
The for loop is usually used when the number of iterations is known
Example
# this loop is iterated 4 times (0 to 3)
for i in range(4):
print(i)
Output:
0
1
2
3
Format Specifiers
The format() method formats the specified value(s) and insert them
inside the string's placeholder.
The placeholder is defined using curly brackets: {}.The format() method
returns the formatted string.
Syntax
string.format(value1, value2...)
Parameter Values
Parameter Description
value1, value2... The values are either a list of values separated by commas,
a key=value list, or a combination of both.
Example 1
txt = "For only {price:.2f} dollars!"
print(txt.format(price = 49))
output
For only 49.00 dollars!
Example 2
#named indexes:
#numbered indexes:
#empty placeholders:
print(txt1)
print(txt2)
print(txt3)
Output:
Escape Sequences
Example:
print('Interview \n Bit')
Output:
Interview
Bit
For example,
print(r'\n')
print(r'\t')
Output:
\n
\t
Unicode Strings
Unicode is a standard encoding system that is used to represent
characters from almost all languages. Every Unicode character is encoded
using a unique integer code point between 0 and 0x10FFFF. A Unicode
string is a sequence of zero or more code points.
Example
import sys
output:
The default encoding for python2 is: ascii
String Methods
Function
Description
Name
Function
Description
Name
isnumeric() Returns “True” if all characters in the string are numeric characters
Function
Description
Name
rindex() Returns the highest index of the substring inside the string
rsplit() Split the string from the right by the specified separator
strip() Returns the string with both leading and trailing characters
Returns a copy of the string with ‘0’ characters padded to the left
zfill()
side of the string
Example
# Python3 program to show the
# working of upper() function
text = 'geeKs For geEkS'
Output:
Converted String:
GEEKS FOR GEEKS
Converted String:
geeks for geeks
Converted String:
Geeks For Geeks
Original String
geeKs For geEkS