You are on page 1of 36

Functions and Exception Handling

Definition
A function is a block of code which only runs when it
is called.
You can pass data, known as parameters, into a
function.
A function can return data as a result.
Types of Functions
Basically, we can divide functions into the following two types:

 Built-in functions -
Functions that are built into Python.
 User-defined functions -
Functions defined by the users themselves.
Creating a Function
using the def keyword:
Example
def my_function():
  print("Hello from a function")
Calling a Function

To call a function, use the function name followed by parenthesis:


Example
def my_function():
  print("Hello from a function")

my_function()
Working with Parameters
 A parameter is a named entity in a function definition, specifying an
argument that the function can accept.
 Let’s create a small program that takes in parameters x, y, and z. 

def add_numbers(x, y, z):


a=x+y
b=x+z
c=y+z
print(a, b, c)
add_numbers(1, 2, 3)
Keyword Arguments
Variable Number of Arguments
In cases where you don’t know the exact number of
arguments that you want to pass to a function, you can
use the following syntax with *args:
Example:
Anonymous function
 n Python, anonymous function means that a function is without a name. As we
already know that def keyword is used to define the normal functions and
the lambda keyword is used to create anonymous functions. It has the
following syntax:
lambda arguments: expression

 This function can have any number of arguments but only one expression,
which is evaluated and returned.
 One is free to use lambda functions wherever function objects are required.
 You need to keep in your knowledge that lambda functions are syntactically
restricted to a single expression.
 It has various uses in particular fields of programming besides other types of
expressions in functions.
Example:
 Program to show the use of lambda functions
double = lambda x: x * 2
# Output: 10
print(double(5))

 In the above program, lambda x: x * 2 is the lambda function. Here x is


the argument and x * 2 is the expression that gets evaluated and returned.
 This function has no name. It returns a function object which is assigned
to the identifier double. We can now call it as a normal function. The
statement
 double = lambda x: x * 2 is nearly the same as
 def double(x): return x * 2
Global variable
A variable declared outside of the function or in global
scope is known as global variable. This means, global
variable can be accessed inside or outside of the
function.
A variable declared inside the function's body or in the
local scope is known as local variable.
Create a Global Variable
Example: Global Variable
Local Variables
A variable declared inside the function's body or in the local
scope is known as local variable.
Accessing local variable outside the scope

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 a() or local scope.
Create a Local Variable
Example:
Exceptions
Exception Handling
 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.

These exceptions can be handled using:

 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.
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
Why We need Exception handling
Exceptional Handling Mechanism
Exception handling is managed by the following 5
keywords:
try
Catch/Except
finally
Throw(Raise)
Mechanism
The Try Statement
 try statement is used for exception handling and has two
forms: try/except and try/finally. In the first case, the try clause can be
followed by one or more except clauses, while in the latter case, it can
only be followed by only one finally clause.
try/except
 The try/except syntax is as follows:
try:
    # try block code
except:
    # except block code
  if an exception was generated, all the statements in the block are
skipped. On the other hand, the body of the except clause is called
the exception handler, as it is used to catch the exception.
The Try Block:
The try block will generate an exception, because x is not defined:
Else Block
You can use the else keyword to define a block of code
to be executed if no errors were raised:
Finally
The finally block, if specified, will be executed
regardless if the try block raises an error or not.
Example:
Try to open and write to a file that is not writable.
Raise an exception
 We can choose to throw an exception if a condition occurs.
 To throw (or raise) an exception, use the raise keyword.
 The raise keyword is used to raise an exception.
Example
 Raise an error and stop the program if x is lower than 0:
Raise an error and stop the program if x is lower than 0:
You can define what kind of error to raise, and the text to print to the
user.
Example:
Raise a TypeError if x is not an integer:
Summary

You might also like