UNIT 2 Python
UNIT 2 Python
In Python, there are several built-in exceptions that can be raised when an error
occurs during the execution of a program. Here are some of the most common types
of exceptions in Python:
• SyntaxError: This exception is raised when the interpreter encounters a
syntax error in the code, such as a misspelled keyword, a missing colon,
or an unbalanced parenthesis.
• TypeError: This exception is raised when an operation or function is
applied to an object of the wrong type, such as adding a string to an
integer.
• NameError: This exception is raised when a variable or function name is
not found in the current scope.
• IndexError: This exception is raised when an index is out of range for a
list, tuple, or other sequence types.
• KeyError: This exception is raised when a key is not found in a dictionary.
• ValueError: This exception is raised when a function or method is called
with an invalid argument or input, such as trying to convert a string to an
integer when the string does not represent a valid integer.
• AttributeError: This exception is raised when an attribute or method is
not found on an object, such as trying to access a non-existent attribute
of a class instance.
• IOError: This exception is raised when an I/O operation, such as reading
or writing a file, fails due to an input/output error.
• ZeroDivisionError: This exception is raised when an attempt is made to
divide a number by zero.
• ImportError: This exception is raised when an import statement fails to
find or load a module.
Difference between Syntax Error and Exceptions
Syntax Error: As the name suggests this error is caused by the wrong syntax in the
code. It leads to the termination of the program.
• A misspelled keyword,
• A missing colon, or
• An unbalanced parenthesis.
Example:
a=10
b=30
if a>b
print("a is big")
else:
print("b is big")
output:
if a>b
Example:
a=10
print("this is zero division exception")
b=a/0
print(b)
Output:
this is zero_division exception
b=a/0
~^~
Try and except statements are used to catch and handle exceptions in
Python.
Try: Statements that can raise exceptions are kept inside the try clause
Except: The statements that handle the exception are written inside except
clause.
Syntax:
try:
# Some Code
except:
# Executed if error in the try block
• First, the try clause is executed i.e. the code between try.
• If there is no exception, then only the try clause will
run, except clause is finished.
• If any exception occurs, the try clause will be skipped
and except clause will run.
• If any exception occurs, but the except clause within the code
doesn’t handle it, it is passed on to the outer try statements. If the
exception is left unhandled, then the execution stops.
• A try statement can have more than one except clause
Example 1
The try block will generate an exception, because x is not defined:
try:
print(x)
except:
print("An exception occurred")
output:
An exception occurred
Example 2
#The try block will generate a NameError, because x is not defined
try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
output:
Else:
You can use the else keyword to define a block of code to be executed if no errors
were raised:
Example:
In this example, the try block does not generate any error:
try:
print("I am not generating an error")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
output:
Python provides a keyword finally, which is always executed after the try and
except blocks. The final block always executes after the normal termination of
the try block or after the try block terminates due to some exceptions.
Syntax:
try:
# Some Code
except:
# Executed if error in the try block
else:
# execute if no exception
finally:
# Some code .....(always executed)
Example:
try:
print(x)
except:
print("an exception appeared")
finally:
print("im always executed if error occurred also")
output:
an exception appeared
Str='Bca'
print(Str.upper())
print(Str.lower())
print(Str.swapcase())
print(len(Str))
Output:
BCA
bca
bCA
3
User-defined function: We can create our own functions based on our
requirements. these functions are called as user defined functions. Example is
given below
Example:
def myfunction():
myfunction()
Calling a Function
Example1:
def myfunction():
print("i will run only,when i was called")
myfunction()
output:
a=10
b=20
def myfunction():
c=a+b
print(c)
myfunction()
output:
30
Arguments
Arguments are specified after the function name, inside the parentheses. You can
add as many arguments as you want, just separate them with a comma.
The following example has a function with two arguments (a,b). When the function is
called, we pass along values of a and b, which is used inside the function to print the
sum:
Example1:
def myfunction(a,b):
c=a+b
print(“Sum of two numbers:”,c)
myfunction(20,30)
output:
Example2:
def myfunction(lang):
print(lang,"is a object oriented programming language")
myfunction("Python")
myfunction("C#")
myfunction("Java")
output:
If we do not know how many arguments that will be passed into our function, add
a * before the parameter name in the function definition.
This way the function will receive a tuple of arguments, and can access the items
accordingly:
def myfunction(*lang):
print(lang[0],"is a object oriented programming language")
myfunction("Python","C#","Java")
output:
Keyword Arguments
Example:
def myfunction(L1,L2,L3):
print(L2,"is a object oriented programming language")
myfunction(L1="Python",L2="C#",L3="Java")
output:
def myfunction(lang=”python”):
print(lang,"is a object oriented programming language")
myfunction()
myfunction("C#")
myfunction("Java")
output:
Return Values
Example1:
def function_return(a,b):
return a+b
print(function_return(12,30))
print(function_return(12.3,4.5))
output:
42
16.8
Example2:
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
output:
15
25
45
Recursive functions
It is a process in which a function calls itself directly or indirectly is known as
recursive function.
Recursive solutions are best when a problem has clear subproblems that
must be repeated and if you’re unsure how many times you’d need to loop
with an iterative solution.
For example, if you wanted to create a factorial function program that finds
the factorial of an unknown number.
Example1:
num=int(input("enter n value="))
def fact(n):
if n==0:
return 1;
else:
return (n*fact(n-1))
print("factorial of n is",fact(num))
output:
enter n value=4
factorial of n is 24
Example2:
Fibonacci Sequence
First, we’ll look at a classic recursion example: the Fibonacci sequence. This program takes a given
number and returns its Fibonacci numbers.
n=int(input("enter n value="))
def fibo(n):
if n<=1:
return n;
else:
return (fibo(n-1)+fibo(n-2))
print("fibo of n is",fibo(n))
output:
enter n value=8
fibo of n is 21
The Python sys module provides access to command-line arguments via sys.argv. It
solves the two purposes:
It is a basic module that was shipped with Python distribution from the early days on.
It is a similar approach as C library using argc/argv to access the arguments. The sys
module implements command-line arguments in a simple list structure named
sys.argv.
Each list element represents a single argument. The first one -- sys.argv[0] -- is the
name of Python script. The other list elements are sys.argv[1] to sys.argv[n]- are the
command line arguments 2 to n. As a delimiter between arguments, space is used.
Argument values that contain space in it have to be quoted, accordingly.
Example:
import sys
print(type(sys.argv))
print('The command line arguments are:')
for i in sys.argv:
print(i)
Output:
C:\Users\lavan\OneDrive\Desktop\javaprograms>python p3.py 2 3 4
<class 'list'>
The command line arguments are:
p3.py
2
3
4
Python Strings
Python string is the collection of the characters surrounded by single quotes, double
quotes, or triple quotes. The computer does not understand the characters;
internally, it stores manipulated character as the combination of the 0's and 1's.
Each character is encoded in the ASCII or Unicode character. So we can say that
Python strings are also called the collection of Unicode characters.
Below example shown the string enclosed with single, double and triple quotes
str1='second bca'
print(str1)
str2="Fourt Sem bca"
print(str2)
str3="""in bca forth Sem we have
python, MM
and operating system"""
print(str3)
output:
second bca
python,MM
Like other languages, the indexing of the Python strings starts from 0. For example,
The string "HELLO" is indexed as given in the below figure.
You can access each specific character of string by giving particular index value, you
can access entire string by displaying the string name in print statement.
str1='second bca'
print(str1[0])
print(str1[1])
print(str1[2])
print(str1)
#string can access reversely by giving minus index value
print(str1[-1])
print(str1[-2])
output:
s
e
c
second bca
a
c
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.
Example:
str1='Bangalore'
str2='North University'
print(str1+str2)
print(str1[1])
print(str2[0:4])
#string can access reversely by giving minus index value
print(str1[-1])
print(str1[-2])
print(str1*2)
print('B' in str1)
print('s' not in str1)
Output:
BangaloreNorth University
a
North
e
r
BangaloreBangalore
True
True
Traverse the String
Example:
for i in 'Lavanya':
print(i)
output:
L
a
v
a
n
y
a
Escape Sequence
Let's suppose we need to write the text as - They said, "Hello what's going on?"- the
given statement can be written in single quotes or double quotes but it will raise
the SyntaxError as it contains both single and double-quotes.
print(str)
Output:
output:
They said, "What's going on?"
Python String functions
Python provides various in-built functions that are used for string handling. Many String fun
Method Description
decode(encoding = 'UTF8', errors Decodes the string using codec registered for
= 'strict') encoding.
Example:
output:
length of str1= 30