0% found this document useful (0 votes)
2 views21 pages

UNIT 2 Python

Notes

Uploaded by

bipruu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
2 views21 pages

UNIT 2 Python

Notes

Uploaded by

bipruu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 21

UNIT-2

Exception Handling in Python


Error in Python can be of two types i.e., Syntax errors and Exceptions. Errors
are 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 change the normal flow of the program.

Exceptions: Exceptions are raised when the program is syntactically correct,


but the code results in an error. This error does not stop the execution of the
program; however, it changes the normal flow of the program.

Different types of exceptions in 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:

File "C:\Users\lavan\PycharmProjects\pythonProject\p12.py", line 3

if a>b

SyntaxError: expected ':'

Exceptions: Exceptions are raised when the program is syntactically correct,


but the code results in an error. This error does not stop the execution of the
program, however, it changes the normal flow of the program.

Example:
a=10
print("this is zero division exception")
b=a/0
print(b)

Output:
this is zero_division exception

Traceback (most recent call last):

File "C:\Users\lavan\PycharmProjects\pythonProject\p12.py", line 3, in <module>

b=a/0
~^~

ZeroDivisionError: division by zero

Try and Except Statement - Catching Exceptions

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

How try() works?

• 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:

variable x is not defined

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:

I am not generating an error

Nothing went wrong


Finally Keyword in Python

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

im always executed if error occurred also


Python Functions
A function is a block of code which is used to perform a particular task. A function
only runs when it is called.

You can pass data, known as parameters, into a function.

Types of Functions in Python

There are mainly two types of functions in Python.


• Built-in or inbuilt functions
• User-defined functions
Built-in library function: These are predefined Standard functions in Python
that are available to use.
Example: Inbuilt string functions like upper(), lower(),strip() etc
Inbuilt functions performed on list like insert(), remove(), pop(), append(),
sort() etc
Above given examples are inbuilt functions these are predefined functions
we can’t change their names.
Example:

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

Python Function Declaration or Define a function


The syntax to declare a function is:

Example:

def myfunction():

print(“im a function,I will run only when I was called”)

myfunction()

Calling a Function

To call a function, use the function name followed by parenthesis:

Example1:

def myfunction():
print("i will run only,when i was called")
myfunction()

output:

i will run only,when i was called


Example2:

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

output:

30

Arguments

Information can be passed into functions as 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:

Sum of two numbers:50

Example2:

def myfunction(lang):
print(lang,"is a object oriented programming language")
myfunction("Python")
myfunction("C#")
myfunction("Java")
output:

Python is a object oriented programming language

C# is a object oriented programming language

Java is a object oriented programming language

Arbitrary Arguments, *args

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:

Python is a object oriented programming language

Keyword Arguments

You can also send arguments with the key = value.

This way the order of the arguments does not matter.

Example:

def myfunction(L1,L2,L3):
print(L2,"is a object oriented programming language")
myfunction(L1="Python",L2="C#",L3="Java")

output:

C# is a object oriented programming language


Default Parameter Value
The following example shows how to use a default parameter value.

If we call the function without argument, it uses the default value:

def myfunction(lang=”python”):
print(lang,"is a object oriented programming language")
myfunction()
myfunction("C#")
myfunction("Java")

output:

Python is a object oriented programming language

C# is a object oriented programming language

Java is a object oriented programming language

Return Values

To let a function return a value, use the return statement:

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.

Recursion is a concept in computer science when a function calls itself and


loops until it reaches the desired end condition.
Syntax:
def func(): <--
|
| (recursive call)
|
func() ----

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

Command Line arguments


The Python supports the programs that can be run on the command line, complete
with command line arguments. It is the input parameter that needs to be passed to
the script when executing them.

Access command line arguments

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.

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


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

Example for creating strings

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

Fourth Sem bca

in bca forth Sem we have

python,MM

and operating system

Strings indexing and storing

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.

H is stored in 0th index, E is stored in 1st index and so on


Accessing strings characters:
Strings characters can be accessed through the index value.

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.

Example below shown how to access the string

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

We can perform different operations on strings using below operators

Operator Description

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


either side of the operator.

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


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

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


from the specified range.

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


is present in the specified string.

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

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

The process of visiting each character in a string is known as string traverse.


We can traverse the string through looping(For loop).

Example:
for i in 'Lavanya':
print(i)

output:

L
a
v
a
n
y
a

Python String Formatting

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

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

print(str)

Output:

SyntaxError: invalid syntax

# escaping double quotes

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

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

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


This function is deprecated in python3

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


comparisons.

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


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

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


substring in a String between begin and end
index.

decode(encoding = 'UTF8', errors Decodes the string using codec registered for
= 'strict') encoding.

encode() Encode S using the codec registered for


encoding. Default encoding is 'utf-8'.

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


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

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


endIndex) works same as find() method.

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


alphanumeric i.e., alphabets or numbers and
there is at least 1 character. Otherwise, it returns
false.
isalpha() It returns true if all the characters are alphabets
and there is at least one character, otherwise
False.

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


are decimals.

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


there is at least one character, otherwise False.

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

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


lower case, otherwise false.

isnumeric() It returns true if the string contains only numeric


characters.

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


printable or s is empty, false otherwise.

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


Upper case, otherwise False.

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


white-space, otherwise false.

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


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

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


exists) is true otherwise it returns false.

join(seq) It merges the strings representation of the


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

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


case.

lstrip() It removes all leading whitespaces of a string


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

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


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

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


given str between begin and end.

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


string.

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

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


i.e., The string python will be converted to
Python.

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


Case.

Example:

str1="govt first grade college first"


str2="python"
print("original string is",str1)
print("upper case of str1=",str1.upper())
print("Lower case of str1=",str1.lower())
print("title of str1=",str1.title())
print("swap case of str1=",str1.swapcase())
print("length of str1=",len(str1))
print("count of sub strings=",str1.count("first"))
print("encode the string str1",str1.encode("1140"))
print("index of substring of str1 is=",str1.index('grade'))
print("check weather the str1 is alpha or not=",str1.isalpha())
print("check weather the str2 is alpha or not=",str2.isalpha())
print("check wether the str1 is printable=",str1.isprintable())
print("check wether the str1 is lower or not=",str1.islower())
print(str1.replace("g","G"))

output:

original string is govt first grade college first

upper case of str1= GOVT FIRST GRADE COLLEGE FIRST

Lower case of str1= govt first grade college first

title of str1= Govt First Grade College First

swap case of str1= GOVT FIRST GRADE COLLEGE FIRST

length of str1= 30

count of sub strings= 2

encode the string str1


b'\x87\x96\xa5\xa3@\x86\x89\x99\xa2\xa3@\x87\x99\x81\x84\x85@\x83\x96\x93\x9
3\x85\x87\x85@\x86\x89\x99\xa2\xa3'

index of substring of str1 is= 11

check weather the str1 is alpha or not= False

check weather the str2 is alpha or not= True

check wether the str1 is printable= True

check wether the str1 is lower or not= True

Govt first Grade colleGe first

You might also like