0% found this document useful (0 votes)
9 views35 pages

Lec 4 - Functions

The document discusses functions in Python including defining, calling, passing arguments to functions and exception handling. Functions are blocks of reusable code that perform tasks. The document covers different types of arguments that can be passed to functions and exceptions that may occur.

Uploaded by

Zane Tech
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views35 pages

Lec 4 - Functions

The document discusses functions in Python including defining, calling, passing arguments to functions and exception handling. Functions are blocks of reusable code that perform tasks. The document covers different types of arguments that can be passed to functions and exceptions that may occur.

Uploaded by

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

Python - Functions

04/04/24 Python Programming 1


Functions
• A function is a block of organized, reusable
code that is used to perform a single, related
action.
• Functions provide better modularity for your
application and a high degree of code
reusing.
• Python gives you many built-in functions like
print(), etc. but you can also create your own
functions. These functions are called user-
defined functions.
04/04/24 Python Programming 2
Defining a Function
• Function blocks begin with the keyword def followed by
the function name and parentheses ( ( ) ).
• Any input parameters or arguments should be placed
within these parentheses. You can also define parameters
inside these parentheses.
• The first statement of a function can be an optional
statement - the documentation string of the function or
docstring.
• The code block within every function starts with a colon
(:) and is indented.
• The statement return [expression] exits a function,
optionally passing back an expression to the caller. A
return statement with no arguments is the same as return
None.
04/04/24 Python Programming 3
• Syntax:

• Example

04/04/24 Python Programming 4


Calling a Function

04/04/24 Python Programming 5


Pass by reference vs value
• All parameters (arguments) in the Python
language are passed by reference.
• It means if you change what a parameter
refers to within a function, the change also
reflects back in the calling function.
• Example:

04/04/24 Python Programming 6


04/04/24 Python Programming 7
Function Arguments
• You can call a function by using the following
types of formal arguments −
• Required arguments
• Keyword arguments
• Default arguments
• Variable-length arguments

04/04/24 Python Programming 8


Required arguments
• Required arguments are the arguments passed to a
function in correct positional order.
• The number of arguments in the function call should
match exactly with the function definition

• To call the function printme(), you definitely need to


pass one argument, otherwise it’ll gives a syntax error
04/04/24 Python Programming 9
Keyword arguments
• 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
• Example:

04/04/24 Python Programming 10


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.

04/04/24 Python Programming 11


Variable-length arguments
• You may need to process a function for more
arguments than you specified while defining the
function.
• Syntax:

• An asterisk (*) is placed before the variable name that


holds the values of all nonkeyword variable arguments.
• This tuple remains empty if no additional arguments
are specified during the function call.
04/04/24 Python Programming 12
04/04/24 Python Programming 13
The Anonymous Functions
• These functions are called anonymous because
they are not declared in the standard manner by
using the def keyword.
• You can use the lambda keyword to create small
anonymous functions.
• Lambda forms can take any number of arguments but return just
one value in the form of an expression.
• An anonymous function cannot be a direct call to print because
lambda requires an expression
• Lambda functions have their own local namespace and cannot
access variables other than those in their parameter list and those
in the global namespace.

04/04/24 Python Programming 14


• Syntax:

• Example:

04/04/24 Python Programming 15


The return Statement
• The statement return [expression] exits a function,
optionally passing back an expression to the caller.
• A return statement with no arguments is the same
as return None.

04/04/24 Python Programming 16


Python - Exceptions
Handling

04/04/24 Python Programming 17


Exceptions Handling
• Python provides two very important features to
handle any unexpected error in your Python
programs and to add debugging capabilities in
them.
• Exception Handling
• Assertions

04/04/24 Python Programming 18


S/N Exception Name & Description
1 Exception - Base class for all exceptions
2 StopIteration - Raised when the next() method of an iterator does not point to
any object.
3 SystemExit - Raised by the sys.exit() function.
4 StandardError - Base class for all built-in exceptions except StopIteration and
SystemExit.
5 ArithmeticError - Base class for all errors that occur for numeric calculation.
6 OverflowError - Raised when a calculation exceeds maximum limit for a numeric
type.
7 FloatingPointError - Raised when a floating point calculation fails.
8 ZeroDivisionError - Raised when division or modulo by zero takes place for all
numeric types.
9 AssertionError - Raised in case of failure of the Assert statement.
10 AttributeError - Raised in case of failure of attribute reference or assignment.
04/04/24 Python Programming 19
11 EOFError - Raised when there is no input from either the raw_input() or input()
function and the end of file is reached.
12 ImportError - Raised when an import statement fails.
13 KeyboardInterrupt - Raised when the user interrupts program execution, usually
by pressing Ctrl+c.
14 LookupError - Base class for all lookup errors.
15 IndexError - Raised when an index is not found in a sequence.
16 KeyError - Raised when the specified key is not found in the dictionary.
17 NameError - Raised when an identifier is not found in the local or global
namespace.
18 UnboundLocalError - Raised when trying to access a local variable in a function or
method but no value has been assigned to it.
19 EnvironmentError - Base class for all exceptions that occur outside the Python
environment.
20 IOError - Raised when an input/ output operation fails, such as the print
statement or the open() function when trying to open a file that does not exist.
04/04/24 Python Programming 20
21 IOError - Raised for operating system-related errors.

22 SyntaxError - Raised when there is an error in Python syntax.

23 IndentationError - Raised when indentation is not specified properly.

24 SystemError - Raised when the interpreter finds an internal problem, but when
this error is encountered the Python interpreter does not exit.
25 SystemExit - Raised when Python interpreter is quit by using the sys.exit()
function. If not handled in the code, causes the interpreter to exit.
26 TypeError - Raised when an operation or function is attempted that is invalid for
the specified data type.
27 ValueError - Raised when the built-in function for a data type has the valid type of
arguments, but the arguments have invalid values specified.
28 RuntimeError - Raised when a generated error does not fall into any category.

29 NotImplementedError - Raised when an abstract method that needs to be


implemented in an inherited class is not actually implemented.
04/04/24 Python Programming 21
Assertions in Python
• An assertion is a sanity-check can be can turn on or
turn off when you are done with testing the
program.
• An assertion is to liken it to a raise-if statement (or
to be more accurate, a raise-if-not statement). An
expression is tested, and if the result comes up
false, an exception is raised.
• Programmers often place assertions at the start of a
function to check for valid input, and after a
function call to check for valid output.

04/04/24 Python Programming 22


The assert Statement
• The syntax for assert is

• If the assertion fails, Python uses ArgumentExpression


as the argument for the AssertionError.
• AssertionError exceptions can be caught and handled
like any other exception using the try-except
statement, but if not handled, they will terminate the
program and produce a traceback.

04/04/24 Python Programming 23


04/04/24 Python Programming 24
What is Exception?
• An exception is an event, which occurs during the
execution of a program that disrupts the normal flow
of the program's instructions
• When a Python script raises an exception, it must
either handle the exception immediately otherwise it
terminates and quits.
• 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
04/04/24 Python Programming 25
• Syntax:

• Example:

04/04/24 Python Programming 26


The except Clause with No
Exceptions

• This kind of a try-except statement catches all the


exceptions that occur.
• Using this 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
04/04/24 Python Programming 27
The except Clause with
Multiple Exceptions
• You can also use the same except statement
to handle multiple exceptions as follows.
• Syntax:

04/04/24 Python Programming 28


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.
• Syntax:

04/04/24 Python Programming 29


• You cannot use else clause as well along with
a finally clause.
• Example:

04/04/24 Python Programming 30


Argument of an Exception
• An exception can have an argument, which is
a value that gives additional information
about the problem.
• Syntax:

04/04/24 Python Programming 31


04/04/24 Python Programming 32
Raising an Exceptions
• You can raise exceptions in several ways by using the raise
statement.
• Syntax:

• Here, Exception is the type of exception (Eg, NameError) and


argument is a value for the exception argument.
• The argument is optional; if not supplied, the exception
argument is None.
• The final argument, traceback, is also optional (and rarely used
in practice), and if present, is the traceback object used for the
exception.

04/04/24 Python Programming 33


• Note: In order to catch an exception, an "except"
clause must refer to the same exception thrown
either class object or simple string.
• For example

04/04/24 Python Programming 34


User-Defined Exceptions

04/04/24 Python Programming 35

You might also like