Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
6 views65 pages

Unit2-Exceptions Functions String 11april25

The document outlines a syllabus for Unit 2 covering topics such as exception handling, functions, and strings in Python. It includes types of errors, exception handling mechanisms, and various operations on strings, along with examples and explanations. Additionally, it provides questions and answers related to these topics for assessment purposes.

Uploaded by

diyajith38
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)
6 views65 pages

Unit2-Exceptions Functions String 11april25

The document outlines a syllabus for Unit 2 covering topics such as exception handling, functions, and strings in Python. It includes types of errors, exception handling mechanisms, and various operations on strings, along with examples and explanations. Additionally, it provides questions and answers related to these topics for assessment purposes.

Uploaded by

diyajith38
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/ 65

Unit2

Ch1-Exceptions
Ch2-Functions
Ch3-Strings
Syllabus-Unit2
Exception handling: Types errors; Exceptions; Exception handling using try, except
and finally
Python Functions: Types of functions; Function Definition-Syntax, Function Calling,
Passing parameters/arguments, the return statements; Default parameters;
Command line arguments; Keyword arguments, Recursive functions; Scope and life
time of variables in functions.
Strings: Creating and storing strings; Accessing string character; the str()function;
Operation on strings-
Concatenation, comparison, slicing, and joining, Traversing of string
Format specifiers; Escape sequences; Raw and Unicode Strings;
Python String Methods
2023 QP-From unit2 and unit3

2 marks
1)What is a Recursive Function?
2) What is the use of raw strings
3) What is a Nested list?
4) What is a set? Give example

Section B
1) Explain the Types of Errors with example ?
2) Explain any three built-in functions used on list with example
3) Explain Traversing, Concatenation and slicing operation on tuple with example?

Section C
1a) Explain Passing arguments in python with example
b)Explain any 4 string methods with example?
2a) Explain the operation on Dictionary with example?
b)Explain Tuple methods Count(), index() with example
2024 QP-From unit2 and unit3
2marks
1) What is Raw string?
2) Define scope and life time of a variable
3) Define tuples in python
4) Mention any two operations of list
Section B
1) Explain Exception handling mechanism in python with example?
2) Write a python program to demonstrate the Lists in python?
Section C
1) a)Write short notes on the following: I) String Concatenation ii) String Slicing
b)What are user Defined Functions? Write a program to demonstrate user-defined functions?
2) Define Dictionaries in python?Explain any three dictionary operation in python
What are sets?Explain any 3 operation of sets in Python
Types of error-QP
In python there are three kinds of errors:
1)Syntax Error
2)Logical Error
3)Run time error also called exceptions
1)Syntax errors:
Errors that occur when you violate the rules of writing the
syntax are known as compile -time errors
example-missing parentheses, semicolon etc
2) Logical error:
occurs when logic of the program is written incorrect. This will
run the program but lead to wrong results.
Example: average=(10+20+30)/2
print(average)
3) Runtime Error: Also known as exceptions
Exception
An exception is an error that occurs during execution of program.
An exception is an unwanted event that disrupts/terminates the normal
flow of program. When exception occurs, the program gets terminated
abruptly
Runtime errors also called exceptions that occur during execution of
program
Common Built-in Exceptions
1)ZeroDivisionError: Zero division exceptions happen when second
argument in division operation is 0
>>>a=10/0
2) NameError: raised when the variable is used without defining it
• >>>print(a)
3)TypeError: Raised when an operation is attempted that is invalid
for the specified datatype
>>>print(1+”deepa”)
4)ValueError: Raised when a function gets an argument of correct type
but improper value
>>> int("hello") # trying to convert a non-numeric string to int
5) IndexError: Raised when we try to access an index which is out of given
range
Example
My_list=[10,20,30]
Print(My_list[5])
Explanation: Trying to access 6th element of list that only has 3 elements.
The correct way to access the elements of list is to use an index that is within
the range of the list:
My_list[0]
My_list[1],My_List[2]
6.KeyError:
Raised when key is not found in dictionary
>>>dict={
"name":"deepa",
"class":"bca",
“fee”:1000
}
>>>print(dict[gender])
Explanation: This will cause key error, because “gender” is not mentioned in
dictionary
Q)What is Exception handling in python?
Illustrate with program-Imp

• The Process of handling exception is called Exception handling


• It is handled using 4 blocks namely try , except, else and finally
• Handling of exception ensures that the flow of the program does not
get terminated when an exception occurs. Handling of execution
results in the execution of all the statements in the program
Syntax
try:
# statements
except [Exception_name1] :
# statements
except [Exception-name2]:
#statements
else:
# if no exception then execute this block
finally:
# this block always gets executed, irrespective of exception
Explanation of Exception handling?

The try block contains the code that might raise an exception. It's where you anticipate potential issues. If an exception
occurs within the try block, the program's control is transferred to the corresponding except block.

except Block:

The except block follows the try block. When an exception occurs in the try block, Python checks if the exception
matches any of the specified types in the except block. If a match is found, the code within that except block is
executed to handle the exception.

There can be multiple except

else:

is executed when there is no exception in the try block. There is only one else block

finally:

It is always executed irrespective of whether an exception has occurred or not.


Program to demonstrate Exceptions
try:

div=10/0

print(div)

except ZeroDivisionError:

print(“denominator cannot be zero”)

else:

print(“No exception occurred”)

finally:

• print(“Finally will always be executed”)


Example2:NameError
try:
print(a)
except Exception as e:
print(e)
else:
print("No exception occurred")
finally:
print("Finally will always be executed")
Questions on Functions
Q)Define Function. Explain its types?
Q)Define Function definition and function call with syntax and example
Q)What is argument?
An argument is data passed to a function through function call statement.
For example, print(math.sqrt(25)) the integer 25 is argument.
Q Explain the scope and life time of variable?
Q Write two difference between local variable and global variable
Q Explain different ways to pass arguments in functions/Explain the types of
arguments in python with example?
Functions
A function is a subprogram that Performs specific task.
Advantages of function:
1)Code reusability:
Write the function once and call it as many times as you need.
2)Improves clarity of code:
• Since a large program is divided into small subprogram
(called functions), it helps to increase readability of the code.
3)Redundant code is at one place so making changes is
easier:
If any changes to be done, we need to change only in
one location (which is function itself).
Thus saves our time also.
4)Helps increase modularity: a large python program is
divided into smaller parts, thus making it easier to
implement
Advantage of Function
• Write once and use it as many time as you need. This provides code
reusability.
• Function facilitates ease of code maintenance.
• Divide Large task into many small task so it will help you to debug code
• You can remove or add new feature to a function anytime.
What is Function? How is it useful? 2m
Function is named block of statements within a program that
performs specific task.
Functions are useful as they can be reused anywhere through
their function call. So for the same functionality, one need not
rewrite the code every time it is needed; rather, through
functions it can be used again and again.
Q)Types of Function:
Two types of functions
1.Built-in Functions
2.User Defined Functions
I)Built-in Functions:
are pre-defined functions used to perform specific task
Example
input(), int(), type(), len() ,max(),min(),sum() etc
2. User Defined Functions
How to create/define function?
Syntax for function definition
def function_name(parameter1,…..parameter n):
statements
[return]
Explanation of syntax:

A user defined function consists of following components:


1 def keyword marks the start of function definition.
2 Function name that uniquely identify it.
3. Parameters: Parameters are optional
Parameters are variables specified inside parenthesis.
A colon (:) to mark the end of function header.
4 Body of the function: contains statement that make our function.
6 An optional return statement to return a value from the function.
Function calling
A Function runs only when we call it, function can not
run on its own.
Syntax
function-name()
example

def greet1():
print(“good morning”)
def greet2():
print(“good afternoon”)
greet1() #Function call 1
greet2() #Function call2
output

good morning

good afternoon
parentheses describes this is a
def represents starting function not variable or other object
of function definition
Parameter : describes beginning
of function body
def add (y) :
x = 10 Local Variable
Name of Function c = x + y Function Body
print(c) Statements
Parameters and Arguments in Functions
Parameters are the variable(s) provided in
the parenthesis when we write function
definition.
These parameters are called formal
parameters
Arguments: An argument is the value(s)
passed in the function call. Also called autual
parameter
Return Statement
Return statements can be used to return something from the function. In
Python, it is possible to return one or more variables/values.
Syntax : -
return (variable or expression);
Ex: - def add (y) : def add (y) : def add_sub (y) :
x = 10 x = 10 x = 10
c=x+y return x + y c=x+y
return c sum = add (20) d=y-x
sum = add (20) print(sum) return c, d
print(sum) sum, sub = add (20)
print(sum)
print(sub)
Q) Explain passing parameters/arguments in
python?-vvimp
Python supports 4 types of parameters passing
1 positional arguments
2 keyword argument
3 Default argument
4Variable list arguments
I)Positional Argument:
The number of arguments in the function call should exactly
match with the number of parameters specified in the
function definition. Also, the position(order) of passing should
be matched.
def person(name, age):
print(“my name is”,name)
print(“my age is”,age)
person(“deepa”,35) #Function calling
(Note: If we change order ,then result will be changed)
II) Keyword argument or Named Arguments
-order is not important
-The no of arguments must be equal to no of parameters
-Provide key=value pair as actual arguments.

Example2
def person(name, age):
print(name)
print(age)
person(age=35, name=”deepa”)
III)Default argument:
If the value is not passed in the function call, then default
value written in function definition will be taken
example
def person(name, age=35):
print(name)
print (age)
person(“deepa”)
IV)Variable length arguments: As the name suggests, in certain
situations, we can pass variable number of arguments to a
function. Such type of arguments is called variable length
arguments.
Variable length arguments are declared with *(asterisk sign).
>>> def f1 (*n)
We can call this function by passing any number of arguments
including zero
Example
def greet(*names):
for name in names:
print("Hello", name)

greet("Alice", "Bob", "Charlie") #function call


output
Hello Alice
Hello Bob
Hello Charlie
Q)Explain Scope and life time of variables in
function? Illustrate with program.
scope : The area where the variable can be
accessed ,is defined as the scope of that variable
Global variable: it is a variable which is
defined outside the functions or in a global
space
Its life time is throughout the program (ie it is
accessible anywhere throughout the program)
Local variable: it is a variable which is
declared within a function or within a
block
Its lifetime is within the function (ie it
cannot be accessed outside the function
but only within a function/block of
program)
global_variable = 10

def my_function():
local_variable = 20
print("Inside function:", local_variable)
print("Inside function accessing global variable:",
global_variable)

my_function() # function call


print(local_variable) # This will result in an error, as
local_variable is not in scope here
print("Outside function accessing global variable:",
global_variable)
Q)What is Recursive function?
Recursive function are the function which calls by itself

Example

def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)

num = int(input("Enter a number: "))


result = factorial(num)
print("The factorial is" , result)
Command Line arguments (2m)
What is command line arguments?
The arguments that are given after the name of the program in the
command line shell of the operating system are known as command
line arguments.
Syntax
C:\python filename.py arg1,arg2…argn
• The arg1 and arg2 are command line arguments for filename.py
script.
String
Creation of empty String
Str=“ “
String

String is a group of characters enclosed in quotations.

The datatype of string is represented as str

• String is immutable
Creating a string:
String is a group of characters enclosed in single quotes
or double quotes. String is Immutable.
Example:
str=”python”
print(str)
o/p
python
Where str is string creation
and “python” is value
Storing a string
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 string characters
Two ways of accessing a string character:-
1)Indexing
2) Slicing
We can access the individual character in a string using index number
Syntax
String- name[index]
Ex1)
str = 'hello'
# access 1st index element
print(str[1])

Negative Indexing: Python allows negative


indexing for its strings.
For example,
str = 'hello’ # access 4th last element
print(str[-4]) # "e"
In Python, strings are immutable.
That means the characters of a string cannot be changed.
For example,
>>>str=” HELLO”
>>>str[0]=‘Z’
print(str)
Output
TypeError: 'str' object does not support item assignment
2)String Slicing
The term slice refers to part of the string .The
operator used for slice is colon (:).For slicing ,
we use start index , end index and step value

Syntax
String- name[start: end: step]

Note : beginning with start till end-1,taking every


nth character
>>>str=” hello”
>>>str[1:4]
o/p ‘ell’
>>> str[:4] # starts with 0 and stop-1
Output
‘hell’
Example 3
>>> str[1:5:2]
output
'el'
Key-points
1 Indexing: The method used for accessing
individual character within the string based on
numeric value is called indexing
2 Slicing: A method to extract a part of the string
by specifying the start index , stop index and
step value
Difference between indexing and slicing ? 2m
Indexing: The method used for accessing individual characters within
the string based on numeric value is called indexing
Slicing: A method to extract a part of the string by specifying the
start index , stop index and step value .
Syntax
String-name[start : stop : step]
Ex >>>X=programming
>>>X[3:7]
Output ‘gram’
The str() Function
In Python, the str() is a built-in function which is used to convert any
data type (like numbers, lists, etc.) into a string .
Or
The str() function in Python converts any value into a string.
Example1
x = 10
print(str(x)) # Output: '10’
Example2
lst = [1, 2, 3]
text = str(lst)
print(text)
print(type(text))
output
[1, 2, 3]
<class 'str'>
Operations/operator on string-2022QP
Explain basic Operations/Operators on
string?
Some common Operations on string are :-
1 Concatenation
2 Replication
3 Slicing
4 Membership operator
5 Traversing of string
6 Comparison operators
1.Concatenation: The operator used for string
concatenation is ‘+’.
The + operator creates new string by joining two strings
Example:
>>>”hello” + “world”

o/p
helloworld
2)Replication: The operator used is ‘*’
Replication operator is used to repeat a given
string for a specified number of times.
It takes two operands-number and string.
>>>str=“Python”
>>>str*3
‘PythonPythonPython’
3) Slicing
The term slice refers to part of the string. The operator
used for slice is colon [:]
>>>str=” hello”
>>>str[1:4]
output
‘ell’
Syntax
String[start: stop: step]
4)Membership operator:
Python has two membership operators:
‘in’ and ‘not in’ operators
These operators are used to check whether the substring is present or
not.
Operator Description Example

in Returns True id the >>> 'h' in 'hello’


substring is present in the output
given string and False True
otherwise
not in Returns True if the >>> 'p' not in 'hello’
substring is not present in output
the given string and False True
otherwise
Traversing a String
We can iterate the various characters or a string by using a for
loop or a while loop .
Code Output Descrption
X=‘RAIN’ R 1st Run:i=‘R’
for i in x: A 2nd Run:i=‘A’
print(i) I 3rd Run : i=‘I’
N 4th Run : i=‘N’
Q) Explain built-in string functions and String
methods?

Syntax
string-name .method()

Part A :
Write a Program to explore string functions?(Refer Observation book)
Built in functions
Raw String
A raw string treats backslashes (\) as normal characters by adding r
before the string.
Example
print(r"Hello\nWorld")
Output:
Hello\nWorld
Explanation
Here, \n is not treated as a new line.
It is printed as it is — \n stays \n.
Format Specifiers 2m
Format specifiers are special symbols used inside strings to insert and
format values properly.

%s → for string
%d → for integer
%f → for float
{} → used with .format() method to insert values.
Format Specifier with example
name = "Nandini"
age = 16
print("My name is %s and I am %d years old." % (name, age))
Output
My name is Nandini and I am 16 years old.
Escape Sequence 2m
Escape Sequence Meaning
\n New Line
\t Tab Space
\’ Single Quote (‘)
\" Double Quote (")
\\ Backslash (\)

You might also like