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

Python Unit 2

This document covers Exception Handling in Python, detailing the types of exceptions, the keywords used for handling them (try, except, raise, finally), and various examples of exception handling mechanisms. It also discusses Python functions, including built-in and user-defined functions, along with concepts like default parameters, recursion, and the scope and lifetime of variables. Additionally, it provides an overview of string operations, methods, and escape sequences in Python.

Uploaded by

Kanchan Patil
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views8 pages

Python Unit 2

This document covers Exception Handling in Python, detailing the types of exceptions, the keywords used for handling them (try, except, raise, finally), and various examples of exception handling mechanisms. It also discusses Python functions, including built-in and user-defined functions, along with concepts like default parameters, recursion, and the scope and lifetime of variables. Additionally, it provides an overview of string operations, methods, and escape sequences in Python.

Uploaded by

Kanchan Patil
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

PYTHON PROGRAMMING UNIT II

Exception Handling print(“Cannot divide number by zero”)


➢ An exception is defined as something that does not finally:
conform to the norm and therefore somewhat rare. print(“Finally Block always executed”)
➢ Exception handling is mechanism provided to handle Output: Cannot divide number by zero
the run-time errors or exceptions which often disrupt the Finally Block always executed
normal flow of execution.
➢ Most common types of exceptions are: TypeError, 3. Try with else block
IndexError, NameError and ValueError. try:
➢ When an exception is raised that causes program to A = 10/2
terminate, we say that an unhandled exception has been except ZeroDivisionError:
raised print(“Cannot divide number by zero”)
Process of Exception Handling else:
➢ There are 4 keywords used for exception handling print(“Value of A is “, A)
mechanism. They are try, except, raise and finally. Output: Value of A is 5
➢ If you feel that block of code is going to cause an
exception than such code you need to embed in a try 4. Try with multiple except block
block. try:
➢ Every try block should be followed by one or more A = [10, 20, 30]
except block(s). It is the place, where we catch the print(A[5])
exception. except ZeroDivisionError:
➢ In some cases, we need to manually raise an exception , print(“Cannot divide number by zero”)
its done through raise keyword followed by the except IndexError:
exception name. print(“Cannot access out of range value”)
➢ The finally block will include house-keeping task or Output: Cannot access out of range value
cleanup job. Its optional block, which always get
executed. 5. 5.Try with except, raise and finally block
➢ Try-else block: if the exception has not occurred than try:
control will be redirected to else block after try block. A = [10, 20, 30]
Examples: 5th example is best for(i in range(4)):
try: if(i == 3):
some statements here raise IndexError
except: else:
exception handling print(A[i])
except IndexError:
1. Try with except block print(“Cannot access out of range value”)
try: finally:
A =10/0 print(“Finally Block always executed”)
print(“Value of A is “, A) Output:
except ZeroDivisionError: 10
print(“Cannot divide number by zero”) 20
Output: Cannot divide number by zero 30
Cannot access out of range value
2. Try with except and finally block Finally Block always executed
try:
A =10/0
print(“Value of A is “, A)
except ZeroDivisionError: Few Types of Exception

1 KLE’s BCA College, Nipani


PYTHON PROGRAMMING UNIT II

➢ ZeroDivisionError - It occurs when we divide any


Function Name Description
number by zero. Example- Dividing 5/0
➢ ValueError - It occurs when operation or function Return the absolute value of a
receive a value of unexpected type. Example- Python abs()
number
num=”abc” and convert val=int(num)
➢ TypeError - it occurs when operation or function is Python dict() Creates a Python Dictionary
applied to object of inappropriate type. Example-
Dividing 5/abc Python id() Return the identity of an object
➢ IndexError - it occurs when we try to access index
which is non-existing Example- test = [10,20,30] and Python input() Take input from user as a string
accesstest[5].
Converts a number in given base
Python int()
to decimal
Python Functions Python iter() Convert an iterable to iterator
Function is structured sequence of statements written
in order to achieve specific task Python len() Returns the length of the object
Types of Functions in Python
There are mainly two types of functions in python. Python list() Creates a list in Python
• Built-in library function: These are Standard
functions in Python that are available to use. Python pow() Compute the power of a number
• User-defined function: We can create our own
functions based on our requirements. Python range() Generate a sequence of numbers

❖ Built-in library function: Python slice() Returns a slice object


Python provides a lot of built-in functions that eases
Returns a temporary object of the
the writing of code. Python super()
superclass

Python tuple() Creates a tuple in Python

Python type() Returns the type of the object

❖ User-defined function:
We can create our own functions based on our
requirements.
❖ Syntax
In python each function is defined as

def name_of_function(list of formal parameters):


body of function

➢ Ex:
# A simple Python function
def max(x, y):
if(x>y):
return x

2 KLE’s BCA College, Nipani


PYTHON PROGRAMMING UNIT II

else: A default argument is a parameter that assumes a


return y default value if a value is not provided in the function
call for that argument.
# calling a function Example:
max(30, 40) # Python program to demonstrate
# default arguments
• def is keyword specifying function is defined with def myFun(x, y=50):
name followed by formal parameters. print("x: ", x)
• Function body is any piece of python code. print("y: ", y)

❖ Function Calling # (We call myFun() with only argument)


• After creating a function we can call it by using the myFun(10)
name of the function followed by parenthesis Output:
containing parameters of that particular function. x: 10
y: 50

❖ Command line Arguments


❖ Passing Parameters/arguments
• Arguments are the values passed inside the parenthesis ❖ Key Word Arguments
of the function. A function can have any number of Keyword arguments are commonly used in
arguments separated by a comma. conjunction with default parameter values
• When function is used, formal parameters are bound to
actual parameters during function invocation or def printName(fName, lName, reverse = False):
if reverse:
function call.
print lName + ', ' + fName
• The point of execution moves from point of invocation else:
to first statement in function. Body of function is print fName, lName
performed & after return statement, its transferred back
to code immediately following invocation. #default values allow to call function with fewer than
• Example: A simple Python function to check specified number of arguments
whether x is even or odd
❖ Recursive Functions
def evenOdd(x):
The term Recursion can be defined as the process of
if (x % 2 == 0):
defining something in terms of itself. Recursion is
print("even")
programming technique where-in function is called
else:
repeatedly until a condition is met.
print("odd")
Recursion is programming technique where-in
# Driver code to call the function
function call itself.
evenOdd(2)
➢ In general, a recursive definition is made up of
evenOdd(3)
two parts. There is at least one base case that
Output: directly specifies result for a special case and there
even is least one recursive case.
odd ➢ Example 1
Program to print the fibonacci series upto n_terms
❖ The return statement
There is special statement, return that can be used only def fib(n):
within body which returns control back to function call if n <= 1:
with some value. return n
else:
return(fib(n-1) + fib(n-2))
❖ Default Parameters

3 KLE’s BCA College, Nipani


PYTHON PROGRAMMING UNIT II

n_terms = 5
if n_terms <= 0:
print("Invalid input ! input a positive value")
else:
print("Fibonacci series:")
for i in range(n_terms):
print(recursive_fibonacci(i))

Output
Fibonacci series:
0
1
1
2
3

4 KLE’s BCA College, Nipani


PYTHON PROGRAMMING UNIT II

➢ Example 2 Outside the function global total : 0


# Program to print factorial of a numbe recursively. The lifetime of a variable in Python:
def fact(n): The variable lifetime is the period during which
if n == 1: the variable remains in the memory of the Python
return n program. The variables' lifetime inside a function remains
else: as long as the function runs. These local types of variables
return n * fact(n-1) are terminated as soon as the function replaces or
terminates.
num = 6
if num < 0: Write example of local and global variable.
print("Invalid input ! enter a positive number.")
elif num == 0:
print("Factorial of number 0 is 1")
else:
print("Factorial of number", num, "=", fact(num))
Output
Factorial of number 6 = 720 Strings
Python string is the collection of the characters
❖ Scope and Lifetime of Variables in Functions.
All variables in a program may not be accessible at all surrounded by single quotes, double quotes, or triple
locations in that program. This depends on where you have quotes.
declared a variable. ❖ Creating and Storing Strings
The scope of a variable determines the portion of the ✓ Create a string by enclosing the characters in
program where you can access a particular identifier. There single-quotes or double- quotes.
are two basic scopes of variables in Python − Examples

• Global variables str1 = 'Hello Python'


• Local variables str2 = "Hello Python"

Global variables ✓ Strings are stored as individual characters in a


Variables that are defined outside have a global contiguous memory location. It can be accessed
scope. Global variables can be accessed throughout the from both directions: forward and backward.
program body by all functions. Example
The string "HELLO" is indexed as given in the
Local variables below figure.
Variables that are defined inside a function body have a
local scope.This means that local variables can be accessed
only inside the function in which they are declared.
Example
total = 0; # This is global variable.
def sum( arg1, arg2 ):
total = arg1 + arg2; # Here total is local variable.
print "Inside the function local total : ", total
return total;
sum( 10, 20 );
print "Outside the function global total : ", total

Output
Inside the function local total : 30

5 KLE’s BCA College, Nipani


PYTHON PROGRAMMING UNIT II

❖ Accessing Sting Characters ❖ Operations on Strings


✓ In Python, individual characters of a String can be ✓ Concatenation
accessed by using the method of Indexing. Two strings can be concatenated in Python by
✓ the indexing of the Python strings starts from 0 simply using the ‘+’ operator between them.
✓ Use the square brackets for slicing along with the
s1="bca"
index or indices to obtain your substring. Example
s2="kle"
str = "HELLO"
s3=s1+s2
print(str[0])
s4=s1+" "+s2
print(str[1])
print(str[2]) print(s3)

print(str[3]) print(s4)
print(str[4]) OUTPUT:
# It returns the IndexError because 6th index doesn't exist bcakle
print(str[6]) bca kle

✓ Comparison
OUTPUT:
H To compare two strings, to identify whether the two
E strings are equivalent to each other or not, or
L greater or smaller than the other.
L Name=KLE
O Name1=BCA
IndexError: string index out of range print("Are name and name 1 equal?")
print (name == name2)
❖ The str()function OUTPUT:
Python str() function returns the string version of the Are name and name 1 equal False
object.
Syntax: str(object, encoding=’utf-8?, errors=’strict’) ✓ Slicing
Parameters:
You can return a range of characters by using the slice
• object: The object whose string representation is to
syntax.
be returned.
Specify the start index and the end index, separated by
• encoding: Encoding of the given object.
a colon, to return a part of the string.
• errors: Response when decoding fails.
Example:
# Python program to demonstrate strings String = 'ASTRING'

num = 100 # Using slice constructor


s1 = slice(3)
s = str(num) s2 = slice(1, 5, 2)
s3 = slice(-1, -12, -2)
print(s, type(s))
print("String slicing")
num = 100.1 print(String[s1])
print(String[s2])
s = str(num) print(String[s3])

print(s, type(s)) Output:


String slicing
OUTPUT AST
100 <class 'str'> SR
GITA
100.1 <class 'str'>

6 KLE’s BCA College, Nipani


PYTHON PROGRAMMING UNIT II

✓ Join Python1
The string join() method returns a string by joining Python2
Python3
all the elements of an iterable (list, string, tuple),
\\ Backslash print("\\")
separated by the given separator. Output:
Example: \
text = ['Python', 'is', 'a', 'fun', 'programming', \' Single Quotes print('\'')
'language'] Output:
'
\\'' Double Quotes print("\"")
# join elements of text with space Output:
print(' '.join(text)) "
Output: \a ASCII Bell print("\a")
Python is a fun programming language \b ASCII print("Hello
\b World")
Backspace(BS)
✓ Traversing Output:
Hello World
Example 1:
\f ASCII Formfeed print("Hello
string_name = "Pythonprogram" \f World!")
Hello World!
# Iterate over the string \n ASCII Linefeed print("Hello
\n World!")
for element in string_name: Output:
print(element, end=' ') Hello
print("\n") World!
\r ASCII Carriege print("Hello
\r World!")
output: Return(CR)
Output:
Pythonprogram World!

Example 2: ❖ Raw and Unicode Strings


string_name = "Python" Normal strings in Python are stored internally as 8-bit
ASCII, while Unicode strings are stored as 16-bit
# Iterate over index Unicode. This allows for a more varied set of
for element in range(0, len(string_name)): characters, including special characters from most
print(string_name[element]) languages in the world.

Output:
❖ Python String Methods.
P
Method Description
y
capitalize() It capitalizes the first character of the
t String.
h isalnum() It returns true if the characters in the string
o are alphanumeric
n isalpha() It returns true if all the characters are
alphabets and there is at least one
character, otherwise False.
❖ Escape Sequences
isdecimal() It returns true if all the characters of the
Escape Description Example string are decimals.
Sequence isdigit() It returns true if all the characters are
\newline It ignores the new print("Python1
digits and there is at least one character,
\
line. otherwise False.
Python2 \
Python3") islower() It returns true if the characters of a string
Output: are in lower case, otherwise false.

7 KLE’s BCA College, Nipani


PYTHON PROGRAMMING UNIT II

isnumeric() It returns true if the string contains only


numeric characters.
isupper() It returns false if characters of a string are
in Upper case, otherwise False.
lower() It converts all the characters of a string to
Lower case.
upper() It converts all the characters of a string to
Upper Case.

8 KLE’s BCA College, Nipani

You might also like