Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
19 views

Functions&Exception Handling

A function is a block of code that performs a task and can be called multiple times. Functions can take in parameters and return values. To define a function, use the def keyword followed by the function name and parameters in parentheses. To call a function, use the function name followed by parentheses. Functions can take a variable number of arguments using *args. Variables inside functions are local, while variables outside are global, unless declared otherwise using the global keyword. Exceptions disrupt normal program flow and can be handled using try/except blocks.

Uploaded by

Bikash Ray
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Functions&Exception Handling

A function is a block of code that performs a task and can be called multiple times. Functions can take in parameters and return values. To define a function, use the def keyword followed by the function name and parameters in parentheses. To call a function, use the function name followed by parentheses. Functions can take a variable number of arguments using *args. Variables inside functions are local, while variables outside are global, unless declared otherwise using the global keyword. Exceptions disrupt normal program flow and can be handled using try/except blocks.

Uploaded by

Bikash Ray
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Function:

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.

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")

Arbitrary Arguments, *args


If you do not know how many arguments that will be passed into your function, add a * before the
parameter name in the function definition.
This way the function will receive a tuple of arguments, and can access the items accordingly:
def my_function(*kids):
print("The youngest child is " + kids[2])
my_function("Emil", "Tobias", "Linus")

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()

Function Inside Function


As explained in the example above, the variable x is not available outside the function, but it is
available for any function inside the function:
The local variable can be accessed from a function within the function:
def myfunc():
x = 300
def myinnerfunc():
print(x)
myinnerfunc()
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

ArithmeticError Raised when an error occurs in numeric calculations

AssertionError Raised when an assert statement fails

AttributeError Raised when attribute reference or assignment fails

Exception Base class for all exceptions

EOFError Raised when the input() method hits an "end of file" condition
(EOF)

FloatingPointError Raised when a floating point calculation fails

GeneratorExit Raised when a generator is closed (with the close() method)

ImportError Raised when an imported module does not exist

IndentationError Raised when indentation is not correct

IndexError Raised when an index of a sequence does not exist

KeyError Raised when a key does not exist in a dictionary

KeyboardInterrupt Raised when the user presses Ctrl+c, Ctrl+z or Delete

LookupError Raised when errors raised cant be found

MemoryError Raised when a program runs out of memory

NameError Raised when a variable does not exist


NotImplementedError Raised when an abstract method requires an inherited class to
override the method

OSError Raised when a system related operation causes an error

OverflowError Raised when the result of a numeric calculation is too large

ReferenceError Raised when a weak reference object does not exist

RuntimeError Raised when an error occurs that do not belong to any specific
exceptions

StopIteration Raised when the next() method of an iterator has no further


values

SyntaxError Raised when a syntax error occurs

TabError Raised when indentation consists of tabs or spaces

SystemError Raised when a system error occurs

SystemExit Raised when the sys.exit() function is called

TypeError Raised when two different types are combined

UnboundLocalError Raised when a local variable is referenced before assignment

UnicodeError Raised when a unicode problem occurs

UnicodeEncodeError Raised when a unicode encoding problem occurs

UnicodeDecodeError Raised when a unicode decoding problem occurs

UnicodeTranslateError Raised when a unicode translation problem occurs


ValueError Raised when there is a wrong value in a specified data type

ZeroDivisionError Raised when the second operator in a division is zero

You might also like