Module4_Functions-Tuples-Dictionaries
Module4_Functions-Tuples-Dictionaries
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?
• 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
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.