Functions&Exception Handling
Functions&Exception Handling
Creating a function
In Python a function is defined using the def keyword:
def my_function():
print("Hello from a function")
Calling a function
To call a function, use the function name followed by parenthesis:
def my_function():
print("Hello from a function")
my_function()
Arguments
Information can be passed into functions as arguments.
Arguments are specified after the function name, inside the parentheses. You can add as many
arguments as you want, just separate them with a comma. The following example has a function
with one argument (fname). When the function is called, we pass along a first name, which is used
inside the function to print the full name:
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
Parameters or Arguments?
The terms parameter and argument can be used for the same thing: information that are passed
into a function.
Number of Arguments
By default, a function must be called with the correct number of arguments. Meaning that if your
function expects 2 arguments, you have to call the function with 2 arguments, not more, and not
less.
def my_function(fname, lname):
print(fname + " " + lname)
my_function("Emil", "Refsnes")
Example:
def sum_function(*numbers):
total = 0
for i in numbers:
total += i
return total
print(sum_function(1,2,3,4,5))
NOTE:
*args is just a name. We can change arg to anything we want like how we changed it
to *numbers above.
The important thing here is the unpacking operator (*).
Actual Parameters & Formal Parameters:
The Actual parameters are the variables that are transferred to the function when it is requested.
The Formal Parameters are the values determined by the function that accepts values when the
function is declared. In actual parameters, only the variable is mentioned, not the data types.
Default Arguments:
Python has a different way of representing syntax and default values for function arguments.
Default values indicate that the function argument will take that value if no argument value is
passed during the function call. The default value is assigned by using the assignment (=)
operator of the form keywordname = value.
Let’s understand this through a function student. The function student contains 3-arguments out
of which 2 arguments are assigned with default values. So, the function student accepts one
required argument (firstname), and rest two arguments are optional.
def student(firstname, lastname ='Mark', standard ='Fifth'):
print(firstname, lastname, 'studies in', standard, 'Standard')
Scope of a variable:
A variable is only available from inside the region it is created. This is called scope.
Local Scope
A variable created inside a function belongs to the local scope of that function, and can only be
used inside that function.
A variable created inside a function is available inside that function:
def myfunc():
x = 300
print(x)
myfunc()
Global Scope
A variable created in the main body of the Python code is a global variable and belongs to the
global scope.
Global variables are available from within any scope, global and local.
A variable created outside of a function is global and can be used by anyone:
x = 300
def myfunc():
print(x)
myfunc()
print(x)
Naming Variables
If you operate with the same variable name inside and outside of a function, Python will treat
them as two separate variables, one available in the global scope (outside the function) and one
available in the local scope (inside the function):
The function will print the local x, and then the code will print the global x:
x = 300
def myfunc():
x = 200
print(x)
myfunc()
print(x)
Global Keyword
If you need to create a global variable, but are stuck in the local scope, you can use
the global keyword.
The global keyword makes the variable global.
If you use the global keyword, the variable belongs to the global scope:
def myfunc():
global x
x = 300
myfunc()
print(x)
Example
To change the value of a global variable inside a function, refer to the variable by using the
global keyword:
x = 300
def myfunc():
global x
x = 200
myfunc()
print(x)
Exception Handling:
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 try block lets you test a block of code for errors.
The except block lets you handle the error.
The else block lets you execute code when there is no error.
The finally block lets you execute code, regardless of the result of the try- and except blocks.
Test 1:
The try block will generate an exception, because x is not defined:
try:
print(x)
except:
print("An exception occurred")
Test 2:
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")
Test 3:
You can use the else keyword to define a block of code to be executed if no errors were raised:
In this example, the try block does not generate any error:
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
Using Finally
The finally block, if specified, will be executed regardless if the try block raises an error or not.
try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")
raise
The raise keyword is used to raise an exception.
You can define what kind of error to raise, and the text to print to the user.
Raise a TypeError if x is not an integer:
x = "hello"
if not type(x) is int:
raise TypeError("Only integers are allowed")
Built-in Exceptions
The table below shows built-in exceptions that are usually raised in Python:
Exception Description
EOFError Raised when the input() method hits an "end of file" condition
(EOF)
RuntimeError Raised when an error occurs that do not belong to any specific
exceptions