0% found this document useful (0 votes)
36 views24 pages

Python UNIT2 Notes

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)
36 views24 pages

Python UNIT2 Notes

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/ 24

UNIT_2_NOTES

Exceptions
An exception is an event, which occurs during the execution of a program that disrupts the
normal flow of the program's instructions. In general, when a Python script encounters a
situation that it cannot cope with, it raises an exception. An exception is a Python object that
represents an error.

A Python program terminates as soon as it encounters an error. In Python, an error can be a


syntax error or an exception.

Exceptions versus Syntax Errors


Syntax errors occur when the parser detects an incorrect statement. Observe the following
example:
>>> print( 0 / 0 ))
File "<stdin>", line 1
print( 0 / 0 ))
^
SyntaxError: invalid syntax

The arrow indicates where the parser ran into the syntax error. In this example, there was
one bracket too many. Remove it and run your code again:

>>> print( 0 / 0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
This time, you ran into an exception error. This type of error occurs whenever syntactically
correct Python code results in an error. The last line of the message indicated what type of
exception error you ran into.

Instead of showing the message exception error, Python details what type of exception error
was encountered. In this case, it was a ZeroDivisionError. Python comes with various built-
in exceptions as well as the possibility to create self-defined exceptions.

Types of errors
• Syntax Error:

Syntax errors occur when the code violates the rules of the Python language syntax. These errors are
detected by the Python interpreter when its parsing the code. Ex : Missing colon, unmatched parentheses,
missing indentation
• Runtime Error:

Runtime errors occur when the code is syntactically correct but causes an error when its executed. These
errors can be caused by a variety of reasons such as invalid input data, division by zero, or accessing an
undefined variable.
• Logical Error:
A logical error occurs when the code runs without any syntax or runtime errors but produces
incorrect output due to flawed logic in the code. These types of errors are often caused by incorrect
assumptions, an incomplete understanding of the problem, or the incorrect use of algorithms or
formulas.

Typed of Built in errors


• SyntaxError: Raised when there is a syntax error in the python code.
• TypeError: Raised when an operation or function is applied to an object of inappropriate type.
• ValueError: Raised when a function receives an argument of the right type but inappropriate value.
• ZeroDivisionError: Raised when you try to divide a number by zero.
• NameError: Raised when a variable name is not defined.
• IndexError: Raised when trying to access an index that does not exist in a sequence.
• KeyError: Raised when trying to access a key that does not exist in a dictionary.
• MemoryError: Creating a large list or array that exceeds the available memory.
• AttributeError: Raised when trying to access an attribute that does not exist.
• ImportError: Raised when an import statement fails a specified module cannot be found.

Exception Handling
Try, Except & Finally

 The try block lets you test a block of code for errors.

 The except block lets you handle the error.

 The finally block lets you execute code, regardless of the result of the try- and except
blocks.

Syntax:

try:

# Code that may raise an exception

except SomeException as e:

# Code to handle the exception if SomeException occurs

# e is the exception object

except AnotherException:

# Code to handle AnotherException

finally:

# Code that will always execute regardless of whether an exception occurred or not

# This block is optional, but when present, it will always execute

Examples
try:
print(x)

except:
print("An exception occurred")

Output:
An exception occurred

Since the try block raises an error, the except block will be executed.
Many Exceptions

You can define as many exception blocks as you want, e.g. if you want to execute a special block of
code for a special kind of error:

Example
Print one message if the try block raises a NameError and another for other errors:

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("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")

Output:

Hello
Nothing went wrong
Finally

The finally block, if specified, will be executed regardless if the try block raises an
error or not.

Example
try:print(x)except:
print("Something
went wrong")
finally:
print("The 'try except' is finished")

Output:

Something went wrong


The 'try except' is finished

Example
try:

x = int(input("Please enter a number: "))

result = 10 / x

print("Result:", result)

except ValueError:

print("Error: Invalid input. Please enter a valid number.")

except ZeroDivisionError:

print("Error: Division by zero is not allowed.")

except Exception as e:

print(f"An error occurred: {e}”)

finally:

print("This finally block always executes, regardless of exceptions.")


FUNCTIONS
Python Function
Functions are the most important aspect of an application. A function can be defined as the
organized block of reusable code, which can be called whenever required.
Python allows us to divide a large program into the basic building blocks known as a
function. The function contains the set of programming statements enclosed by {}. A
function can be called multiple times to provide reusability and modularity to the Python
program.
The Function helps to programmer to break the program into the smaller part. It organizes the
code very effectively and avoids the repetition of the code. As the program grows, function
makes the program more organized.
Python provide us various inbuilt functions like range() or print(). Although, the user can
create its functions, which can be called user-defined functions.
There are mainly two types of functions.
User-define functions - The user-defined functions are those define by the user to perform
the specific task.
Built-in functions - The built-in functions are those functions that are pre-defined in Python.

Advantage of Functions in Python


There are the following advantages of Python functions.
Using functions, we can avoid rewriting the same logic/code again and again in a program.
We can call Python functions multiple times in a program and anywhere in a program.
We can track a large Python program easily when it is divided into multiple functions.
Reusability is the main achievement of Python functions.
However, Function calling is always overhead in a Python program.

Creating a Function
Python provides the def keyword to define the function. The syntax of the define function is
given below.
Syntax:

1. def my_function(parameters):
2. function_block
3. return expression

Let's understand the syntax of functions definition.


The def keyword, along with the function name is used to define the function.
The identifier rule must follow the function name.
A function accepts the parameter (argument), and they can be optional.
The function block is started with the colon (:), and block statements must be at the same
indentation.
The return statement is used to return the value. A function can have only one return
Function Calling
In Python, after the function is created, we can call it from another function. A function must
be defined before the function call; otherwise, the Python interpreter gives an error. To call
the function, use the function name followed by the parentheses.
Consider the following example of a simple example that prints the message "Hello World".
1. #function definition
2. def hello_world():
3. print("hello world")
4. # function calling
5. hello_world()

Output:
hello world

The return statement


The return statement is used at the end of the function and returns the result of the function. It
terminates the function execution and transfers the result where the function is called. The
return statement cannot be used outside of the function.
Syntax
1. return [expression_list]

It can contain the expression which gets evaluated and value is returned to the caller function.
If the return statement has no expression or does not exist itself in the function then it returns
the None object.

Consider the following example:


Example 1
1. # Defining function
2. def sum():
3. a = 10
4. b = 20
5. c = a+b
6. return c
7. # calling sum() function in print statement
8. print("The sum is:",sum())

Output:
The sum is: 30
In the above code, we have defined the function named sum, and it has a statement c = a+b,
which computes the given values, and the result is returned by the return statement to the
caller function.
Example 2 Creating function without return statement
1. # Defining function
2. def sum():
3. a = 10
4. b = 20
5. c = a+b
6. # calling sum() function in print statement
7. print(sum())

Output:
None

In the above code, we have defined the same function without the return statement as we can
see that the sum() function returned the None object to the caller function.

Arguments in function
The arguments are types of information which can be passed into the function. The
arguments are specified in the parentheses. We can pass any number of arguments, but they
must be separate them with a comma.
Consider the following example, which contains a function that accepts a string as the
argument.
Example 1
1. #defining the function
2. def func (name):
3. print("Hi ",name)
4. #calling the function
5. func("Devansh")

Output:
Hi Devansh

Example 2
1. #Python function to calculate the sum of two variables
2. #defining the function
3. def sum (a,b):
4. return a+b;
5.
6. #taking values from the user
7. a = int(input("Enter a: "))
8. b = int(input("Enter b: "))
9.
10. #printing the sum of a and b
11. print("Sum = ",sum(a,b))

Output:
Enter a: 10
Enter b: 20
Sum = 30
Scope of Variables
Python Local & Global Variables
Global Variables
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.
Let's see an example of how a global variable is created in Python.
Example 1: Create a Global Variable
x = "global"
def foo():
print("x inside:", x)
foo()
print("x outside:", x)
Output
x inside: global
x outside: global

In the above code, we created x as a global variable and defined a foo() to print the global
variable x. Finally, we call the foo() which will print the value of x.
What if you want to change the value of x inside a function?

x = "global"
def foo():
x=x*2
print(x)
foo()
Output
UnboundLocalError: local variable 'x' referenced before assignment

The output shows an error because Python treats x as a local variable and x is also not defined
inside foo().

Local Variables
A variable declared inside the function's body or in the local scope is known as a local
variable.
Example 2: Accessing local variable outside the scope
def foo():
y = "local"
foo()
print(y)
Output
NameError: name 'y' is not defined
The output shows an error because we are trying to access a local variable y in a global scope
whereas the local variable only works inside foo() or local scope.

Let's see an example on how a local variable is created in Python.


Example 3: Create a Local Variable
Normally, we declare a variable inside the function to create a local variable.
def foo():
y = "local"
print(y)
foo()
Output
local
Let's take a look at the earlier problem where x was a global variable and we wanted to
modify x inside foo().

Global and local variables


Here, we will show how to use global variables and local variables in the same code.
Example 4: Using Global and Local variables in the same code
x = "global "
def foo():
global x
y = "local"
x=x*2
print(x)
print(y)
foo()
Output
global global
local

In the above code, we declare x as a global and y as a local variable in the foo(). Then, we use
multiplication operator * to modify the global variable x and we print both x and y.
After calling the foo(), the value of x becomes global global because we used the x * 2 to
print two times global. After that, we print the value of local variable y i.e local.

Example 5: Global variable and Local variable with same name


x=5
def foo():
x = 10
print("local x:", x)
foo()
print("global x:", x)
Output
local x: 10
global x: 5
In the above code, we used the same name x for both global variable and local variable. We
get a different result when we print the same variable because the variable is declared in both
scopes, i.e. the local scope inside foo() and global scope outside foo().
When we print the variable inside foo() it outputs local x: 10. This is called the local scope of
the variable.
Similarly, when we print the variable outside the foo(), it outputs global x: 5. This is called
the global scope of the variable
What is recursion?
Recursion is the process of defining something in terms of itself.
A physical world example would be to place two parallel mirrors facing each other. Any
object in between them would be reflected recursively.

Python Recursive Function


In Python, 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.

Recursive Function in Python


Following is an example of a recursive function to find the factorial of an integer.
Factorial of a number is the product of all the integers from 1 to that number. For example,
the factorial of 6 (denoted as 6!) is 1*2*3*4*5*6 = 720.
Example of a recursive function
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
In the above example, factorial() is a recursive function as it calls itself.
When we call this function with a positive integer, it will recursively call itself by decreasing
the number.
Each function multiplies the number with the factorial of the number below it until it is equal
to one. This recursive call can be explained in the following steps.
factorial(3) # 1st call with 3
3 * factorial(2) # 2nd call with 2
3 * 2 * factorial(1) # 3rd call with 1
3 * 2 * 1 # return from 3rd call as number=1
3 * 2 # return from 2nd call
6 # return from 1st call
Let's look at an image that shows a step-by-step process of what is going on:
Working of a recursive factorial function
Our recursion ends when the number reduces to 1. This is called the base condition.
Every recursive function must have a base condition that stops the recursion or else the
function calls itself infinitely.
The Python interpreter limits the depths of recursion to help avoid infinite recursions,
resulting in stack overflows.
By default, the maximum depth of recursion is 1000. If the limit is crossed, it results in
RecursionError. Let's look at one such condition.
def recursor():
recursor()
recursor()
Output
Traceback (most recent call last):
File "<string>", line 3, in <module>
File "<string>", line 2, in a
File "<string>", line 2, in a
File "<string>", line 2, in a
[Previous line repeated 996 more times]
RecursionError: maximum recursion depth exceeded
Advantages of Recursion
1. Recursive functions make the code look clean and elegant.
2. A complex task can be broken down into simpler sub-problems using recursion.
3. Sequence generation is easier with recursion than using some nested iteration.

Disadvantages of Recursion
1. Sometimes the logic behind recursion is hard to follow through.
2. Recursive calls are expensive (inefficient) as they take up a lot of memory and time.
3. Recursive functions are hard to debug

Command Line Arguments in Python


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. Python provides various ways
of dealing with these types of arguments. The three most common are:
 Using sys.argv

 Using getopt module


 Using argparse module
Using sys.argv
The sys module provides functions and variables used to manipulate different parts of the
Python runtime environment. This module provides access to some variables used or
maintained by the interpreter and to functions that interact strongly with the interpreter.
One such variable is sys.argv which is a simple list structure. It’s main purpose are:
 It is a list of command line arguments.

 len(sys.argv) provides the number of command line arguments.


 sys.argv[0] is the name of the current Python script.

Example: Let’s suppose there is a Python script for adding two numbers and the numbers are
passed as command-line arguments.

# Python program to demonstrate


# command line arguments
import sys

# total arguments
n = len(sys.argv)
print("Total arguments passed:", n)

# Arguments passed
print("\nName of Python script:", sys.argv[0])

print("\nArguments passed:", end = " ")


for i in range(1, n):
print(sys.argv[i], end = " ")

# Addition of numbers
Sum = 0
# Using argparse module
for i in range(1, n):
Sum += int(sys.argv[i])

print("\n\nResult:", Sum)

Keyword and Positional Argument in Python

Python provides different ways of passing the arguments during the function call from which
we will explore keyword-only argument means passing the argument by using the
parameter names during the function call.is

Types of arguments

 Keyword-only argument
 Positional-only argument

Difference between the Keyword and Positional Argument

Keyword-Only Argument Positional-Only Argument

Arguments are passed in the order of parameters.


Parameter Names are used to pass the
The order defined in the order function
argument during the function call.
declaration.

Order of parameter Names can be


Order of values cannot be changed to avoid
changed to
Keyword-Only Argument Positional-Only Argument

pass the argument(or values). the unexpected output.

Keyword-Only Arguments

Keyword-only arguments mean whenever we pass the arguments(or value) by their


parameter names at the time of calling the function in Python in which if you change the
position of arguments then there will be no change in the output.

Example

So now, we will call the function by using the keyword-only arguments(or by using the
parameter names) in two ways and In both cases, we will be getting the correct output but not
necessarily in the positional argument. Here we have used argument naming to declare the
value. This is called the keyword-only argument. Let’s assume we have a function that tells
the name and age of the individual(or person) as defined below:

def nameAge(name, age):

print("Hi, I am", name)

print("My age is ", age)

nameAge(name="Prince", age=20)

nameAge(age=20, name="Prince")

Output
Hi, I am Prince
My age is 20
Hi, I am Prince
My age is 20
STRINGS

Python String
Till now, we have discussed numbers as the standard data-types in Python. In this section of
the tutorial, we will discuss the most popular data type in Python, i.e., string.
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.
Consider the following example in Python to create a string.
Syntax:
1. str = "Hi Python !"Here, if we check the type of the variable str using a Python script
1. print(type(str)), then it will print a string (str).

In Python, strings are treated as the sequence of characters, which means that Python doesn't
support the character data-type; instead, a single character written as 'p' is treated as the string
of length 1.
Creating String in Python
We can create a string by enclosing the characters in single-quotes or double- quotes. Python
also provides triple-quotes to represent the string, but it is generally used for multiline string
or docstrings.
1. #Using single quotes
2. str1 = 'Hello Python'
3. print(str1)
4. #Using double quotes
5. str2 = "Hello Python"
6. print(str2)
7.
8. #Using triple quotes
9. str3 = '''''Triple quotes are generally used for
10. represent the multiline or
11. docstring'''
12. print(str3)

Output:
Hello Python
Hello Python
Triple quotes are generally used for represent the multiline or docstring

Strings indexing and splitting


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 Consider the following example:
1. str = "HELLO"
2. print(str[0])
3. print(str[1])
4. print(str[2])
5. print(str[3])
6. print(str[4])
7. # It returns the IndexError because 6th index doesn't exist
8. print(str[6])

Output:
H
E
L
L
O
IndexError: string index out of range

As shown in Python, the slice operator [] is used to access the individual characters of the
string. However, we can use the : (colon) operator in Python to access the substring from the
given string. Consider the following example.

Here, we must notice that the upper range given in the slice operator is always exclusive i.e.,
if str = 'HELLO' is given, then str[1:3] will always include str[1] = 'E', str[2] = 'L' and nothing
else.
Consider the following example:
1. # Given String
2. str = "JAVATPOINT"
3. # Start Oth index to end
4. print(str[0:])
5. # Starts 1th index to 4th index
6. print(str[1:5])
7. # Starts 2nd index to 3rd index
8. print(str[2:4])
9. # Starts 0th to 2nd index
10. print(str[:3])
11. #Starts 4th to 6th index
12. print(str[4:7])

Output:
JAVATPOINT
AVAT
VA
JAV
TPO

We can do the negative slicing in the string; it starts from the rightmost character, which is
indicated as -1. The second rightmost index indicates -2, and so on. Consider the following
image.

Consider the following example


1. str = 'JAVATPOINT'
2. print(str[-1])
3. print(str[-3])
4. print(str[-2:])
5. print(str[-4:-1])
6. print(str[-7:-2])
7. # Reversing the given string
8. print(str[::-1])
9. print(str[-12])

Output:
T
I
NT
OIN
ATPOI
TNIOPTAVAJ
IndexError: string index out of range

Deleting the String


As we know that strings are immutable. We cannot delete or remove the characters from the
string. But we can delete the entire string using the del keyword.
1. str = "JAVATPOINT"
2. del str[1]

Output:
TypeError: 'str' object doesn't support item deletion
Now we are deleting entire string.
1. str1 = "JAVATPOINT"
2. del str1
3. print(str1)

Output:
NameError: name 'str1' is not defined

String operation
Example
Consider the following example to understand the real use of Python operators.
1. str = "Hello"
2. str1 = " world"
3. print(str*3) # prints HelloHelloHello
4. print(str+str1)# prints Hello world
5. print(str[4]) # prints o
6. print(str[2:4]); # prints ll
7. print('w' in str) # prints false as w is not present in str
8. print('wo' not in str1) # prints false as wo is present in str1.
9. print(r'C://python37') # prints C://python37 as it is written
10. print("The string str : %s"%(str)) # prints The string str : Hello

Output:
HelloHelloHello
Hello world
o
ll
False
False
C://python37
The string str : Hello

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.
r/R It is used to specify the raw string. Raw strings are used in the
cases where
we need to print the actual meaning of escape characters such
as "C://python".
To define any string as a raw string, the character r or R is
followed by the string.
% It is used to perform string formatting. It makes use of the
format specifiers
used in C programming like %d or %f to map their values in
python.
We will discuss how formatting is done in python.
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.
Example
Consider the following example to understand the real use of Python operators.
1. str = "They said, "Hello what's going on?""
2. print(str)

Output:
SyntaxError: invalid syntax
We can use the triple quotes to accomplish this problem but Python provides the escape sequence.
The backslash(/) symbol denotes the escape sequence. The backslash can be followed by a special
character and it interpreted differently. The single quotes inside the string must be escaped. We
can apply the same as in the double quotes.
Example -
1. # using triple quotes
2. print('''''They said, "What's there?"''')
3.
4. # escaping single quotes
5. print('They said, "What\'s going on?"')
7. # escaping double quotes
8. print("They said, \"What's going on?\"")

Output:
They said, "What's there?"
They said, "What's going on?"
They said, "What's going on?"

STRING METHODS/FUNCTIONS
Python string methods is a collection of in-built Python functions that operates on lists.
Python string is a sequence of Unicode characters that is enclosed in quotation marks. In
this article, we will discuss the in-built string functions i.e. the functions provided by
Python to operate on strings.
List of String Methods in Python
Here is the list of in-built Python string methods, that you can use to perform actions on
string:

Function Name Description

Converts the first character of the string to


capitalize()
a capital (uppercase) letter

Returns the number of occurrences of a


count()
substring in the string.
Function Name Description

Returns “True” if a string ends with the


endswith()
given suffix

Returns the lowest index of the substring


find()
if it is found

Formats the string for printing it to


format()
console

Returns the position of the first occurrence


index()
of a substring in a string

Checks whether all the characters in a


isalnum()
given string is alphanumeric or not

Returns “True” if all characters in the


isalpha()
string are alphabets

Returns true if all characters in a string are


isdecimal()
decimal

Returns “True” if all characters in the


isdigit()
string are digits

Checks if all characters in the string are


islower()
lowercase

Returns “True” if all characters in the


isnumeric()
string are numeric characters

Checks if all characters in the string are


isupper()
uppercase

join() Returns a concatenated String

Converts all uppercase characters in a


lower()
string into lowercase
Function Name Description

Replaces all occurrences of a substring


replace()
with another substring

Converts all uppercase characters to


swapcase()
lowercase and vice versa

title() Convert string to title case

Modify string according to given


translate()
translation mappings

Converts all lowercase characters in a


upper()
string into uppercase

Examples
1. The capitalize() method returns a string where the first character is upper case.
Syntax
string.capitalize()
Example:
txt = "hello, and welcome to my world."
x = txt.capitalize()
print (x)

Output:
Hello, and welcome to my world.

2. The index() method finds the first occurrence of the specified value.

The index() method raises an exception if the value is not found.


The index() method is almost the same as the find() method, the only difference is that the find()
method returns -1 if the value is not found. (See example below)
Syntax
string.index(value, start, end)
Example:
txt = "Hello, welcome to my world."
x = txt.index("welcome")
print(x)
Output:
7

3. The swapcase() method returns a string where all the upper case letters are lower case and vice
versa.

Syntax
string.swapcase()
Example:
txt = "Hello My Name Is PETER"
x = txt.swapcase()
print(x)

Output:
hELLO mY nAME iS peter

4. The count() method returns the number of times a specified value appears in the string.

Syntax
string.count(value, start, end)
Example:
txt = "I love apples, apple are my favorite fruit"
x = txt.count("apple") print(x)

Output: 2

5. The isupper() method returns True if all the characters are in upper case, otherwise False.
Numbers, symbols and spaces are not checked, only alphabet characters.

Syntax
string.isupper()
Example:
a = "Hello World!"
b = "hello 123"
c = "MY NAME IS PETER"
print(a.isupper())
print(b.isupper())
print(c.isupper())
OUTPUT
False
False
True

You might also like