0% found this document useful (0 votes)
4 views63 pages

Introduction To Programming 2 - Python - Week 5

This document is a lecture on Python programming, focusing on functions, arguments, recursion, and exception handling. It covers topics such as function declaration, types of arguments, lambda functions, map and filter functions, and the concept of recursion with examples. Additionally, it discusses exception handling in Python, providing syntax and important points for managing exceptions in code.
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)
4 views63 pages

Introduction To Programming 2 - Python - Week 5

This document is a lecture on Python programming, focusing on functions, arguments, recursion, and exception handling. It covers topics such as function declaration, types of arguments, lambda functions, map and filter functions, and the concept of recursion with examples. Additionally, it discusses exception handling in Python, providing syntax and important points for managing exceptions in code.
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

Introduction To Programming 2

Python

Lecture 5

Department of Computer Engineering

Astana IT University

Zamart Ramazanova
Senior-Lecturer
[Link]@[Link]

January 2025
Topics
• Functions
• Arguments
• Lambda, Map, Filter Functions
• Recursion
• Exception Handling

2
Python - Functions
• A function is a block of code that performs a
specific task
Types of function:
• Standard library functions - These are
built-in functions in Python that are
available to use.
• User-defined functions - We can create
our own functions based on our
requirements.
3
Copyright © 2018 Pearson Education, Inc.
Python Function Declaration
The syntax to declare a function is:

Here,
• def - keyword used to declare a function
• function_name - any name given to the function
• arguments - any value passed to function
• return (optional) - returns value from a function

4
Copyright © 2018 Pearson Education, Inc.
Example
Let’s see an example:

Here, we have created a function named greet(). It


simply prints the text ’Hello World!’.

5
Copyright © 2018 Pearson Education, Inc.
Calling a Function in Python
In the above example, we have declared a function
named greet(), using this function, we can call it.

Example:

6
Copyright © 2018 Pearson Education, Inc.
Python Function Arguments
A function can also have arguments. An argument
is a value that is accepted by a function.
Example:

7
Copyright © 2018 Pearson Education, Inc.
The return Statement in Python
A Python function may or may not return a value. If we
want our function to return some value to a function call,
we use the return statement.

For example,

Here, we are returning the variable sum to the function


call.

8
Copyright © 2018 Pearson Education, Inc.
Example: Function return Type
In the this example, we have created a function
named find_square(). The function accepts a number and
returns the square of the number.

9
Copyright © 2018 Pearson Education, Inc.
Python Library Functions
In Python, standard library functions are the built-in
functions that can be used directly in our program.

For example,
• print ( ) - prints the string inside the quotation marks
• sqrt ( ) - returns the square root of a number
• pow ( ) - returns the power of a number

These library functions are defined inside the module.


And, to use them we must include the module inside our
program.

For example, sqrt() is defined inside the math module.


10
Copyright © 2018 Pearson Education, Inc.
Example: Python Library Function

Output

11
Copyright © 2018 Pearson Education, Inc.
Benefits of Using Functions
1. Code Reusable - We can use the same function multiple times in
our program which makes our code reusable. For example,

Hence, the same method is used again and againб the function is used
to calculate the square of numbers from 1 to 3.

2. Code Readability - Functions help us break our code into chunks


to make our program readable and easy to understand

12
Copyright © 2018 Pearson Education, Inc.
Function Arguments
• Arguments are specified after the function
name, inside the parentheses.
• Information can be passed into functions as
arguments.
• You can add as many arguments as you want,
just separate them with a comma.
Example:
A function with one argument (fname): This function has 2 arguments:

13
Copyright © 2018 Pearson Education, Inc.
Arguments
A function by using the following types of
formal arguments:
• Required arguments
• Keyword arguments
• Default arguments
• Variable-length arguments

14
Copyright © 2018 Pearson Education, Inc.
Required arguments
• Required arguments are the arguments passed to a
function in correct positional order.
def printme( str ): "This prints a passed
string"
print str;
return;
printme();

• This would produce following result:


Traceback (most recent call last):
File "[Link]", line 11, in <module> printme();
TypeError: printme() takes exactly 1 argument (0 given)
15
Copyright © 2018 Pearson Education, Inc.
Keyword arguments
Keyword arguments are related to the function calls. When you
use keyword arguments in a function call, the caller identifies the
arguments by the parameter name.
• This allows you to skip arguments or place them out of order
because the Python interpreter is able to use the keywords
provided to match the values with parameters.

def printme( str ): "This prints a passed string"


print str;
return;
printme( str = "My string");

• This would produce following result:


My string

16
Copyright © 2018 Pearson Education, Inc.
Following example gives more clear picture.
Note, here order of the parameter does not
matter:
def printinfo( name, age ): "Test
function"
print "Name: ", name;
print "Age ", age;
return;
printinfo( age=50, name="miki" );

This would produce following result:


Name: miki Age 50

17
Copyright © 2018 Pearson Education, Inc.
Default arguments
• A default argument is an argument that assumes a
default value if a value is not provided in the function call
for that argument.
• Following example gives idea on default arguments, it
would print default age if it is not passed:
def printinfo( name, age = 35 ): “Test function"
print "Name: ", name;
print "Age ", age;
return;
printinfo( age=50, name="miki" );
printinfo( name="miki" );
• This would produce following result:
Name: miki Age 50 Name: miki Age 35

18
Copyright © 2018 Pearson Education, Inc.
Variable-length arguments
• You may need to process a function for more
arguments than you specified while defining the
function. These arguments are called variable-
length arguments and are not named in the
function definition, unlike required and default
arguments.
• The general syntax for a function with non-
keyword variable arguments is this:
def functionname([formal_args,] *var_args_tuple ):
"function_docstring"
function_suite
return [expression]

19
Copyright © 2018 Pearson Education, Inc.
Lambda Functions
• A lambda function is a small anonymous
function.
• A lambda function can take any number of
arguments, but can only have one expression.
Syntax:
lambda arguments : expression

20
Copyright © 2018 Pearson Education, Inc.
Lambda Functions (con’d)
• Lambda function mainly used to create a function without
a name
• It is mainly used with filter() and map() functions.
• It can receive any number of arguments, but can only
have one expression.
• How to use Lambda()-

21
Copyright © 2018 Pearson Education, Inc.
Map Functions
• The map() function executes a specified function
for each item in an iterable. The item is sent to
the function as a parameter.

22
Copyright © 2018 Pearson Education, Inc.
Map Functions (cont’d)
• The Map() function takes a function and
a list as input.
• Map() performs an operation on the entire list
and return the result in a new list
• Syntax- map(function/lambda, list)

23
Copyright © 2018 Pearson Education, Inc.
Map Functions (cont’d)
• Map() can be used with lambda –

24
Copyright © 2018 Pearson Education, Inc.
Filter Functions
• The filter() function returns an iterator where the
items are filtered through a function to test if the
item is accepted or not.

25
Copyright © 2018 Pearson Education, Inc.
Filter Functions (con’d)
• Filter() is used to create a list of elements for
which a function returns “True”.
• Syntax- filter( function that returns True, list)
• Here's how we can use filter()-

26
Copyright © 2018 Pearson Education, Inc.
Introduction to Recursion
• Recursive function: a function that calls itself
(with different arguments)
• Recursive function must have a way to
control the number of times it repeats
Usually involves an if-else statement which
defines when the function should return a value
and when it should call itself
• Depth of recursion: the number of times a
function calls itself

27
Copyright © 2018 Pearson Education, Inc.
Recursion (cont’d)
Advantages of using recursion
• A complicated function can be split down into
smaller sub-problems utilizing recursion.
• Sequence creation is simpler through recursion
than utilizing any nested iteration.
• Recursive functions render the code look
simple and effective.

28
Copyright © 2018 Pearson Education, Inc.
Recursion (cont’d)
Disadvantages of using recursion recursion
• A lot of memory and time is taken through
recursive calls which makes it expensive for
use.
• Recursive functions are challenging to debug.
• The reasoning behind recursion can sometimes
be tough to think through.

29
Copyright © 2018 Pearson Education, Inc.
Example Recursion:

30
Copyright © 2018 Pearson Education, Inc.
Problem Solving with Recursion
• Recursion is a powerful tool for solving
repetitive problems
• Recursion is never required to solve
a problem
• Any problem that can be solved recursively
can be solved with a loop
• Recursive algorithms may be less efficient than
iterative ones in the number of computations
• Due to overhead of each function call
31
Copyright © 2018 Pearson Education, Inc.
Problem Solving with Recursion
(cont’d.)
• Some repetitive problems are more
easily solved with recursion
• General outline of recursive function:
• If the problem can be solved now without
recursion, solve and return
• Known as the base case
• Otherwise, reduce problem to smaller
problem of the same structure and call the
function again to solve the smaller problem
• Known as the recursive case
32
Copyright © 2018 Pearson Education, Inc.
Using Recursion (cont’d.)
• Since each call to the recursive
function reduces the problem:
• Eventually, it will get to the base case which
does not require recursion, and the recursion
will stop
• Usually the problem is reduced by
making one or more parameters
smaller at each function call

33
Copyright © 2018 Pearson Education, Inc.
Direct and Indirect Recursion
• Direct recursion: when a function
directly calls itself
• All the examples shown so far were of direct
recursion
• Indirect recursion: when function A
calls function B, which in turn calls
function A
• also known as mutual recursion

34
Copyright © 2018 Pearson Education, Inc.
Examples of Recursive
Algorithms
• Summing a range of list elements with
recursion
• Function receives a list containing range of
elements to be summed, index of starting item
in the range, and index of ending item in the
range
• Base case:
• if start index > end index return 0
• Recursive case:
• return current_number + sum(list, start+1, end)
35
Copyright © 2018 Pearson Education, Inc.
Examples of Recursive
Algorithms (cont’d.)

36
Copyright © 2018 Pearson Education, Inc.
The Fibonacci Series
• Fibonacci series: has two base cases
• if n = 0 then Fib(n) = 0
• if n = 1 then Fib(n) = 1
• if n > 1 then Fib(n) = Fib(n-1) + Fib(n-2)

• Corresponding function code:

37
Copyright © 2018 Pearson Education, Inc.
The Fibonacci Series
• Fibonacci series: has two base cases
• if n = 0 then Fib(n) = 0
• if n = 1 then Fib(n) = 1
• if n > 1 then Fib(n) = Fib(n-1) + Fib(n-2)

• Corresponding function code:

38
Copyright © 2018 Pearson Education, Inc.
Example the Fibonacci Series
A Fibonacci sequence is the integer sequence of
0, 1, 1, 2, 3, 5, 8….

39
Copyright © 2018 Pearson Education, Inc.
The Towers of Hanoi
• Mathematical game commonly used to
illustrate the power of recursion
• Uses three pegs and a set of discs in
decreasing sizes
• Goal of the game: move the discs from
leftmost peg to rightmost peg
• Only one disc can be moved at a time
• A disc cannot be placed on top of a smaller disc
• All discs must be on a peg except while being
moved

40
Copyright © 2018 Pearson Education, Inc.
41
Copyright © 2018 Pearson Education, Inc.
The Towers of Hanoi (cont’d)
• Problem statement: move n discs from
peg 1 to peg 3 using peg 2 as a
temporary peg
• Recursive solution:
• If n == 1: Move disc from peg 1 to peg 3
• Otherwise:
• Move n-1 discs from peg 1 to peg 2, using peg 3
• Move remaining disc from peg 1 to peg 3
• Move n-1 discs from peg 2 to peg 3, using peg 1

42
Copyright © 2018 Pearson Education, Inc.
The Towers of Hanoi (cont’d)

43
Copyright © 2018 Pearson Education, Inc.
Recursion versus Looping
• Reasons not to use recursion:
• Less efficient: entails function calling
overhead that is not necessary with a loop
• Usually a solution using a loop is more
evident than a recursive solution
• Some problems are more easily solved
with recursion than with a loop
• Example: Factorial, where the mathematical
definition lends itself to recursion
44
Copyright © 2018 Pearson Education, Inc.
Let’s Take a Break

45
Copyright © 2018 Pearson Education, Inc.
Exception Handling
i. What is an Exception in Python?
An exception is an error which happens at the time of
execution of a program. However, while running a
program, Python generates an exception that should
be handled to avoid your program to crash.

In Python language, exceptions trigger automatically


on errors, or they can be triggered and intercepted by
your code

When a Python script raises an exception, it must


either handle the exception immediately otherwise it
would terminate and come out. 46
Copyright © 2018 Pearson Education, Inc.
Handling an exception:
• If you have some suspicious code that may raise an
exception, you can defend your program by placing the
suspicious code in a try: block. After the try: block, include an
except: statement, followed by a block of code which handles
the problem as elegantly as possible.
Syntax:
try:
You do your operations here;
......................
except Exception I:
If there is ExceptionI, then execute this block.
except Exception II:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.
47
Copyright © 2018 Pearson Education, Inc.
Here are few important points above the above
mentioned syntax:
• A single try statement can have multiple except
statements. This is useful when the try block
contains statements that may throw different types
of exceptions.
• You can also provide a generic except clause, which
handles any exception.
• After the except clause(s), you can include an else-
clause. The code in the else-block executes if the
code in the try: block does not raise an exception.
• The else-block is a good place for code that does
not need the try: block's protection.

48
Copyright © 2018 Pearson Education, Inc.
Example:
try:
fh = open("testfile", "w")
[Link]("This is my test file for
exception handling!!")
except IOError: print "Error: can\'t find
file or read data"
else: print "Written content in the file
successfully"
[Link]()

• This will produce following result:


Written content in the file successfully

49
Copyright © 2018 Pearson Education, Inc.
ii. Common Examples of Exception

 Division by Zero
 Accessing a file which does not exist.
 Addition of two incompatible types
 Trying to access a nonexistent index of a sequence
 Removing the table from the disconnected
database server.
 ATM withdrawal of more than the available amount

50
Copyright © 2018 Pearson Education, Inc.
iii. Rules of Exceptions

 Exceptions must be class objects


 For class exceptions, you can use try statement
with an except clause which mentions a particular
class.
 Even if a statement or expression is syntactically
correct, it may display an error when an attempt is
made to execute it.
 Errors found during execution are called
exceptions, and they are not unconditionally fatal.

51
Copyright © 2018 Pearson Education, Inc.
iii. Rules of Exceptions

 Exceptions must be class objects


 For class exceptions, you can use try statement
with an except clause which mentions a particular
class.
 Even if a statement or expression is syntactically
correct, it may display an error when an attempt is
made to execute it.
 Errors found during execution are called
exceptions, and they are not unconditionally fatal.

52
Copyright © 2018 Pearson Education, Inc.
iv. Exceptional Handling Mechanism

Exception handling is managed by the following 4


keywords:
1. try
2. catch
3. finally
4. throw

53
Copyright © 2018 Pearson Education, Inc.
The Try Statement:

A try statement includes keyword try, followed by a colon


(:) and a suite of code in which exceptions may occur. It
has one or more clauses.

During the execution of the try statement, if no exceptions


occurred then, the interpreter ignores the exception
handlers for that specific try statement.

In case, if any exception occurs in a try suite, the try suite


expires and program control transfers to the matching
except handler following the try suite.

54
Copyright © 2018 Pearson Education, Inc.
The catch Statement:
Catch blocks take one argument at a time, which is the type of
exception that it is likely to catch. These arguments may range
from a specific type of exception which can be varied to a
catch-all category of exceptions

55
Copyright © 2018 Pearson Education, Inc.
Finally Block:
Finally block always executes irrespective of an exception
being thrown or not. The final keyword allows you to create a
block of code that follows a try-catch block.

Finally, clause is optional. It is intended to define clean-up


actions which should be that executed in all conditions.

56
Copyright © 2018 Pearson Education, Inc.
The Raise Statement:
The raise statement specifies an argument which initializes the
exception object. Here, a comma follows the exception name,
and argument or tuple of the argument that follows the comma.

In this syntax, the argument is optional, and at the time of


execution, the exception argument value is always none.

57
Copyright © 2018 Pearson Education, Inc.
The except clause with no exceptions
You can also use the except statement with no exceptions defined as
follows:
try:
You do your operations here;
......................
except:
If there is any exception, then execute this block.
......................
else:
If there is no exception then execute this block.

This kind of a try-except statement catches all the exceptions that


occur. Using this kind of try-except statement is not considered a
good programming practice, though, because it catches all exceptions
but does not make the programmer identify the root cause of the
problem that may occur.
58
Copyright © 2018 Pearson Education, Inc.
The except clause with multiple
exceptions
You can also use the same except statement to handle multiple
exceptions as follows:
try:
You do your operations here;
......................
except(Exception1[, Exception2[,...ExceptionN]]]):
If there is any exception from the given exception
list, then execute this block
.......................
else:
If there is no exception then execute this block.

59
Copyright © 2018 Pearson Education, Inc.
Standard Exceptions
Here is a list standard Exceptions available in Python: Standard
Exceptions
The try-finally clause:
You can use a finally: block along with a try: block. The finally block is
a place to put any code that must execute, whether the try-block
raised an exception or not. The syntax of the try-finally statement is
this:
try:
You do your operations here;
......................
Due to any exception, this may be skipped.
finally:
This would always be executed.
......................
Note that you can provide except clause(s), or a finally clause, but not
both. You can not use else clause as well along with a finally clause.
60
Copyright © 2018 Pearson Education, Inc.
User-Defined Exceptions
• Python also allows you to create your own exceptions by deriving
classes from the standard built-in exceptions.
• Here is an example related to RuntimeError. Here a class is created
that is subclassed from RuntimeError. This is useful when you need to
display more specific information when an exception is caught.
• In the try block, the user-defined exception is raised and caught in the
except block. The variable e is used to create an instance of the class
Networkerror.
class Networkerror(RuntimeError):
def __init__(self, arg):
[Link] = arg
• So once you defined above class, you can raise your exception as
follows:
try:
raise Networkerror("Bad hostname")
except Networkerror,e:
print [Link]
61
Copyright © 2018 Pearson Education, Inc.
Summary
• This chapter covered:
– Functions, including:
• Declaration
• Calling a Function
• The return Statement
• Library Functions
• Benefits
- Function Arguments, including:
• Required arguments
• Keyword arguments
• Default arguments
• Variable-length arguments
- Lambda, Map, Filter Functions
- Introduction to Recursion (advantages and disadvantages)
- Exception Handling

62
Ramazanova Zamart. Introduction to Programming 2

You might also like