Python UNIT2 Notes
Python UNIT2 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.
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.
Exception Handling
Try, Except & Finally
The try block lets you test a block of code for errors.
The finally block lets you execute code, regardless of the result of the try- and except
blocks.
Syntax:
try:
except SomeException as e:
except AnotherException:
finally:
# Code that will always execute regardless of whether an exception occurred or not
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:
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:
Example
try:
result = 10 / x
print("Result:", result)
except ValueError:
except ZeroDivisionError:
except Exception as e:
finally:
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
Output:
hello world
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.
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.
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.
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
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
Example: Let’s suppose there is a Python script for adding two numbers and the numbers are
passed as command-line arguments.
# total arguments
n = len(sys.argv)
print("Total arguments passed:", n)
# Arguments passed
print("\nName of Python script:", sys.argv[0])
# Addition of numbers
Sum = 0
# Using argparse module
for i in range(1, n):
Sum += int(sys.argv[i])
print("\n\nResult:", Sum)
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
Keyword-Only Arguments
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:
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
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.
Output:
T
I
NT
OIN
ATPOI
TNIOPTAVAJ
IndexError: string index out of range
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:
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.
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