0% found this document useful (0 votes)
3 views

PYTHON BASIC PROGRAM -theory part 2

The document explains the creation of functions in Python, detailing how to pass parameters and return values. It covers exception handling using try and except statements, along with various exception types. Additionally, it describes sorting algorithms, specifically Insertion Sort and Merge Sort, highlighting their concepts and implementation.

Uploaded by

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

PYTHON BASIC PROGRAM -theory part 2

The document explains the creation of functions in Python, detailing how to pass parameters and return values. It covers exception handling using try and except statements, along with various exception types. Additionally, it describes sorting algorithms, specifically Insertion Sort and Merge Sort, highlighting their concepts and implementation.

Uploaded by

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

Demonstrating creation of functions, passing parameters and return values

1. Arguments: Arguments are values that are passed into a function to


provide it with the necessary data to perform its task. Functions can have zero
or more arguments.

Here's an example of a function with arguments:

def greet(name):
print(f"Hello, {name}!")

In this example, the greet function takes one argument called name. When the
function is called, a value can be provided for the name argument. For
instance:

greet("Alice")

Output:
Hello, Alice!

Here, the argument "Alice" is passed to the greet function, and the function
uses that value to print a personalized greeting.

2. Return Values: Return values are the results or outputs that a function
produces after performing its task. Functions can optionally return a value
using the return statement.
Here's an example of a function with a return value:

def add_numbers(a, b):


return a + b
In this example, the add_numbers function takes two arguments, a and b. It
adds these two values together and returns the result using the return
statement.

3. Function calling
result = add_numbers(3, 4)
print(result)
Output:

Here, the function add_numbers is called with the arguments 3 and 4. The
function adds these numbers and returns the result 7, which is then stored in
the result variable. Finally, the value of result is printed.
Note that a function can have multiple return statements or no return
statement at all. If a function doesn't explicitly return a value, it returns None
by default.
Additionally, functions can return multiple values as a tuple or any other
iterable object. Here's an example:

def calculate_rectangle_properties(length, width):

area = length * width


perimeter = 2 * (length + width) FUNCTION DEFINITION

return area, perimeter

result = calculate_rectangle_properties(4, 5) FUNCTION CALLING

print(result)

Output:
(20, 18)

In this example, the calculate_rectangle_properties function calculates the


area and perimeter of a rectangle using the given length and width. It returns
both values as a tuple, which is then assigned to the result variable. The
print(result) statement displays (20, 18), indicating the area and perimeter
values.

EXCEPTIONS
Exceptions are the unusual event that occurs during the execution of the
program that interrupts the normal flow of the program. Generally, exceptions
occur when the code written encounters a situation it cannot cope with.

Whenever an exception is raised, the program stops the execution, and thus
the further code is not executed. Therefore, an exception is a python object
that represents a run-time error.

Sr.No. Exception Description


1 Exception It is the base class for all the exceptions
It occurs when the next() method of an iterator does not
2 StopIteration
point to any object.
3 SystemExit This occurs by the sys.exit() function.
This is the base class for all built-in exceptions, except
4 StandardError
StopIteration and SystemExit.
It is the base class for all errors related to the numeric
5 ArithmeticError
calculation.
It occurs when a calculation exceeds maximum limit for a
6 OverflowError
numeric type.
7 FloatingPointError This gets raised when a floating point calculation fails.
It gets raised when we try to divide or find modulus by zero. It
8 ZeroDivisionError
takes place for all numeric types.
9 AssertionError It gets raised when the Assert statement fails.
10 AttributeError This gets raised when attribute reference or assignment fails.
It gets raised when there is no input from either the
11 EOFError
raw_input() or input() function and the end of file is reached.
12 ImportError It gets raised when an import statement fails.
This gets raised when the user interrupts the program
13 KeyboardInterrupt
execution, usually by pressing Ctrl+c
14 LookupError It is the base class for all lookup errors.
It gets raised when an index is not in the range of the length
15 IndexError
of a sequence.
16 KeyError This gets raised when the specified key is not found in the
dictionary.
It gets raised when an identifier is not found in the local or
17 NameError
global namespace.
It gets raised when we try to access a local variable in a
18 UnboundLocalError
function or method but no value has been assigned to it.
This is the base class for all exceptions that occur outside the
19 EnvironmentError
Python environment.
It gets raised when an input/ output operation fails. For
20 IOError example, when the open() function tries to open a file that
does not exist.
21 OSError It is related to operating system-related errors.
22 SyntaxError This gets raised when there is an error in Python syntax.
23 IndentationError It gets raised when indentation rules are not followed.
It gets raised when the interpreter finds an internal problem,
24 SystemError but when this error is encountered the Python interpreter
does not exist.
This gets raised when the Python interpreter quits by using
25 SystemExit the sys.exit() function. And if this is not handled in the code, it
causes the interpreter to exit.
It gets raised when an operation or function is done on the
26 TypeError operands of that datatype on which the operation/function
cannot be applied.
It gets raised when the built-in function for a data type has
27 ValueError the valid type of arguments, but the arguments have invalid
values specified.
This gets raised when a generated error does not fall into any
28 RuntimeError
category.
It gets raised when an abstract method that needs to be
NotImplementedErro
29 implemented in an inherited class is not actually
r
implemented.

1.Try and Except in Python


Try and Except statements have been used to handle the exceptions in Python.
The try block has the code to be executed and if any exception occurs then the
action to perform is written inside the catch block.

The syntax is:

try:
Statements to be executed
except:
Statements get executed if an exception occurs

example.

num=10

try:
print("The number is:",Num)
except:
print("An exception occurred")

Output:
An exception occurred

2. We can have multiple except statements, each dealing with a specific


exception of our interest.

The syntax for this is:

try:
Statements to be executed
......................
except ExceptionI:
If ExceptionI occurs, this block gets executed.
except Exception2:
If Exception2 occurs, this block gets executed.
:
:
:
example.
num=10

try:
div=num/0
except ZeroDivisionError:
print("Zero cannot be in the denominator")
except SyntaxError:
print("There is some error in the syntax")

Output:
Zero cannot be in the denominator

3.We can also have else block along with the try/except blocks. The code in the
else block executes only if the code in the try block does not result in an
exception.

Example of try with else clause:

num=10
try:
div=num/2
except:
print("An exception occurred")
else:
print("The value is",div)

Output:
The value is 5.0

4. Finally Keyword in python


Finally is another addition to the try/except blocks. The statements in this
block execute independently of the execution of the code in the try block. The
syntax for this is:
try:
Statements to be executed
......................
except:
# optional block
Statements get executed if an exception occurs
else:
Statements get executed if no exception
finally:
Statements get executed always
Example of try with finally keyword:
num=10
try:
div=num/0
except:
print("An exception occurred")
finally:
print("This is finally block")
Output:
An exception occurred
This is finally block
Insertion Sort in Python
The Insertion sort is a straightforward and more efficient algorithm than the
previous bubble sort algorithm. The insertion sort algorithm concept is based
on the deck of the card where we sort the playing card according to a
particular card. It has many advantages, but there are many efficient
algorithms available in the data structure.

While the card-playing, we compare the hands of cards with each other. Most
of the player likes to sort the card in the ascending order so they can quickly
see which combinations they have at their disposal.

The insertion sort implementation is easy and simple because it's generally
taught in the beginning programming lesson. It is an in-place and stable
algorithm that is more beneficial for nearly-sorted or fewer elements.

The insertion sort algorithm is not so fast because of it uses nested loop for
sorting the elements.

The Concept of Insertion Sort

The array spilled virtually in the two parts in the insertion sort - An unsorted
part and sorted part.

The sorted part contains the first element of the array and other unsorted
subpart contains the rest of the array. The first element in the unsorted array is
compared to the sorted array so that we can place it into a proper sub-array.

It focuses on inserting the elements by moving all elements if the right-side


value is smaller than the left side.

It will repeatedly happen until the all element is inserted at correct place.

To sort the array using insertion sort below is the algorithm of insertion sort.

o Spilt a list in two parts - sorted and unsorted.


o Iterate from arr[1] to arr[n] over the given array.
o Compare the current element to the next element.
o If the current element is smaller than the next element, compare to the
element before, Move to the greater elements one position up to make
space for the swapped element.

Let's understand the following example.

We will consider the first element in the sorted array in the following array.

[10, 4, 25, 1, 5]

The first step to add 10 to the sorted subarray

[10, 4, 25, 1, 5]

Now we take the first element from the unsorted array - 4. We store this value
in a new variable temp. Now, we can see that the 10>4 then we move the 10 to
the right and that overwrite the 4 that was previously stored.

[10, 10, 25, 1, 5] (temp = 4)

Here the 4 is lesser than all elements in sorted subarray, so we insert it at the
first index position.

[4, 10, 25, 1, 5]

We have two elements in the sorted subarray.

Now check the number 25. We have saved it into the temp variable. 25> 10 and
also 25> 4 then we put it in the third position and add it to the sorted sub
array.

[4, 10, 25, 1, 5]

Again we check the number 1. We save it in temp. 1 is less than the 25. It
overwrites the 25.

[4, 10, 25, 25, 5] 10>1 then it overwrites again

[4, 25, 10, 25, 5]

[25, 4, 10, 25, 5] 4>1 now put the value of temp = 1


[1, 4, 10, 25, 5]

Now, we have 4 elements in the sorted subarray. 5<25 then shift 25 to the
right side and pass temp = 5 to the left side.

[1, 4, 10, 25, 25] put temp = 5

Now, we get the sorted array by simply putting the temp value.

[1, 4, 5, 10, 25]

Merge Sort in Python

Merge sort is similar to the quick sort algorithm as works on the concept of
divide and conquer. It is one of the most popular and efficient sorting
algorithm. It is the best example for divide and conquer category of algorithms.

It divides the given list in the two halves, calls itself for the two halves and then
merges the two sorted halves. We define the merge() function used to merging
two halves.

The sub lists are divided again and again into halves until we get the only one
element each. Then we combine the pair of one element lists into two element
lists, sorting them in the process. The sorted two element pairs is merged into
the four element lists, and so on until we get the sorted list.

Merge Sort Concept

We have divided the given list in the two halves. The list couldn't be divided in
equal parts it doesn't matter at all.

Merge sort can be implement using the two ways - top-down approach and
bottom-up approach. We use the top down approach in the above example,
which is Merge sort most often used.

The bottom-up approach provides the more optimization which we will define
later.

The main part of the algorithm is that how we combine the two sorted sublists.
Let's merge the two sorted merge list.
o A : [2, 4, 7, 8]
o B : [1, 3, 11]
o sorted : empty

First, we observe the first element of both lists. We find the B's first element is
smaller, so we add this in our sorted list and move forward in the B list.

o A : [2, 4, 7, 8]
o B : [1, 3, 11]
o Sorted : 1

Now we look at the next pair of elements 2 and 3. 2 is smaller so we add it into
our sorted list and move forward to the list.

o A : [2, 4, 7, 8]
o B : [1, 3, 11]
o Sorted : 1

Continue this process and we end up with the sorted list of {1, 2, 3, 4, 7, 8, 11}.
There can be two special cases.

o What if both sublists have same elements - In such case, we can move
either one sublist and add the element to the sorted list. Technically, we
can move forward in both sublist and add the elements to the sorted
list.
o We have no element left in one sublist. When we run out the in a sublist
simply add the element of the second one after the other.

We should remember that we can sort the element in the any order. We sort
the given list in ascending order but we can easily sort in descending order.

You might also like