0% found this document useful (0 votes)
26 views

Module4_Functions-Tuples-Dictionaries

tài liệu học tập

Uploaded by

tranvanthai5577
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)
26 views

Module4_Functions-Tuples-Dictionaries

tài liệu học tập

Uploaded by

tranvanthai5577
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
You are on page 1/ 41

Functions, Tuples, Dictionaries,

Exceptions, and Data Processing


Objective
In this module, you will cover the following topics:
• code structuring and the concept of function;
• function invocation and returning a result from a function;
• name scopes and variable shadowing;
• tuples and their purpose, constructing and using tuples;
• dictionaries and their purpose, constructing and using dictionaries;
• exceptions – the try statement and the except clause, Python built-in
exceptions, code testing and debugging.
Python functions
• 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.
Type of functions in Python
• User-defined Functions
• Built-in Functions
• Lambda Functions
• Recursion Functions
Function definition
How functions work
It tries to show you the whole process:
• Look at the picture below:
• when you invoke a function, Python
remembers the place where it happened
and jumps into the invoked function;

• the body of the function is then executed;

• reaching the end of the function forces


Python to return to the place directly
after the point of invocation.

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


Parameters or Arguments?
• The terms parameter and argument can be used for the same thing:
information that are passed into a function.

• From a function's perspective:


▪ A parameter is the variable listed inside the parentheses in the
function definition.
▪ An argument is the value that is sent to the function when it is called.
Keyword Arguments
• You can also send arguments with the key = value syntax.
• This way the order of the arguments does not matter.
Default Parameter Value
• The following example shows how to use a default parameter value.
• If we call the function without argument, it uses the default value:
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:
Arbitrary Keyword Arguments, **kwargs
• If you do not know how many keyword arguments that will be passed into your
function, add two asterisk: ** before the parameter name in the function
definition.
• This way the function will receive a dictionary of arguments, and can access the
items accordingly.
Return values
• To let a function return a value, use the return statement:
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.

• The expression is executed and the result is returned.


Recursion Functions
• Python also accepts function recursion, which means a defined
function can call itself.
• Recursion is a common mathematical and programming concept. It
means that a function calls itself. This has the benefit of meaning that
you can loop through data to reach a result.
Recursion Functions: example
Functions and scopes
• The scope of a name (e.g., a variable name) is the part of a code
where the name is properly recognizable.

The program will fail when run. The error message will
read:
Functions and scopes: the global keyword
Tuples
• Tuple items are ordered, unchangeable, and allow duplicate values.
• Tuples are written with round brackets.
Create a tuple?

It is also possible to use the tuple() constructor to make a tuple.


Assess Tuples
• You can access tuple items by referring to the index number, inside square
brackets:
Assess Tuples: Negative Indexing
• Negative indexing means start from the end.
Assess Tuples: Range of Indexes
• You can specify a range of indexes by specifying where to start and where to end
the range.
• When specifying a range, the return value will be a new tuple with the specified
items.

• Specify negative indexes if you want to start the search from the end of the tuple.
Tuple: check if Item Exists
• To determine if a specified item is present in a tuple use the in keyword:
Dictionarys
• Dictionaries are used to store data values in key:value pairs.
• A dictionary is a collection which is ordered*, changeable and do not
allow duplicates.
Create a dictionary
Add Dictionary Items
• Adding an item to the dictionary is done by using a new index key and
assigning a value to it.
Update Dictionary
• The update() method will update the dictionary with the items from a given
argument. If the item does not exist, the item will be added.
• The argument must be a dictionary, or an iterable object with key:value pairs.
Removing Items
• The pop() method removes the item with the specified key name.
• The popitem() method removes the last inserted item.
Removing Items (continue)
• The del keyword removes the item with the specified key name.
• The clear() method empties the dictionary.
Loop Dictionaries
• You can loop through a dictionary by using a for loop.
Loop Dictionaries (continue)
Loop Dictionaries (continue)
• You can also use the values() method to return values of a dictionary.
• You can use the keys() method to return the keys of a dictionary.
Python Dictionary Methods
Method Description
clear() Removes all the elements from the dictionary
copy() Returns a copy of the dictionary
fromkeys() Returns a dictionary with the specified keys and value

get() Returns the value of the specified key


items() Returns a list containing a tuple for each key value pair

keys() Returns a list containing the dictionary's keys


pop() Removes the element with the specified key
popitem() Removes the last inserted key-value pair
setdefault() Returns the value of the specified key. If the key does not exist: insert the key, with the specified value

update() Updates the dictionary with the specified key-value pairs

values() Returns a list of all the values in the dictionary


Exceptions
• An exception is an unexpected event that occurs during program execution. For
example
Exceptions (continue)
Errors that occur at runtime (after passing the syntax test) are
called exceptions or logical errors.
For instance, they occur when we
• try to open a file(for reading) that does not exist
(FileNotFoundError)
• try to divide a number by zero (ZeroDivisionError)
• try to import a module that does not exist (ImportError) and so on.
Whenever these types of runtime errors occur, Python creates an
exception object.
Built-in Exceptions

https://docs.python.org/3/library/exceptions.html
Defining Custom Exceptions
• In Python, we can define
custom exceptions by
creating a new class that
is derived from the built-
in Exception class.
Python try...except Block
• The try...except block is used to handle exceptions in Python. Here's
the syntax of try...except block:
Catching Specific Exceptions
• For each try block, there can be zero or more except blocks.
Multiple except blocks allow us to handle each exception differently.
Python try with else clause
• Exceptions in the else clause are not handled by the preceding except
clauses.
Python try...finally
• In Python, the finally block is always executed no matter whether
there is an exception or not.

You might also like