SlideShare ist ein Scribd-Unternehmen logo
1 von 56
Mohammad Hassan
Array, Tuples, Dictionary, Exception
Objectives
Arrays;
Sequence Type & Mutability;
Understand the need of Tuples;
Solve problems by using Tuples;
 Get clear idea about Tuple functions;
Understand the difference between list, dictionary and
tuples; and
Exceptions
Arrays are used to store multiple values in one single variable:
cars = ["Ford", "Volvo", "BMW"]
An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars in
single variables could look like this:
car1 = "Ford"
car2 = "Volvo"
car3 = "BMW“
what if you want to loop through the cars and find a specific one? And what if
you had not 3 cars, but 300?
The solution is an array!
An array can hold many values under a single name, and you can access the
values by referring to an index number.
ARRAY
Access the Elements of an Array
Get the value of the first array item:
cars = ["Ford", "Volvo", "BMW"]
x = cars[0]
print(x)
This will give output:
Ford
Modify the value of the first array
Modify the value of the first array item:
cars = ["Ford", "Volvo", "BMW"]
cars[0] = "Toyota"
print(cars)
This will give output:
['Toyota', 'Volvo', 'BMW']
The Length of an Array
Use the len() method to return the length of an array (the number of
elements in an array).
Return the number of elements in the cars array:
cars = ["Ford", "Volvo", "BMW"]
x = len(cars)
print(x)
This will give output:
3
The length of an array is always one more than the highest
array index.
Looping Array Elements
Print each item in the cars array:
cars = ["Ford", "Volvo", "BMW"]
for x in cars:
print(x)
This will give output:
Ford
Volvo
BMW
WHAT IS TUPLE?
A tuple is essentially an immutable list. Below is a list with three
elements and a tuple with three elements:
L = [1,2,3]
t = (1,2,3)
Tuples are enclosed in parentheses, though the parentheses are
actually optional.
Indexing and slicing work the same as with lists.
As with lists, you can get the length of the tuple by using the len
function, and, like lists, tuples have count and index
methods.However, since a tuple is immutable, it does not have any
of the other methods that lists have, like sort or reverse, as those
change the list.
Adding Array Elements
You can use the append() method to add an element to an
array.
Add one more element to the cars array:
cars = ["Ford", "Volvo", "BMW"]
cars.append("Honda")
print(cars)
This will give output:
['Ford', 'Volvo', 'BMW', 'Honda']
Removing Array Elements
You can use the pop() method to remove an element from the array.
Delete the second element of the cars array:
cars = ["Ford", "Volvo", "BMW"]
cars.pop(1)
print(cars)
This will give output:
['Ford', 'BMW’]
You can also use the remove() method to remove an element from the array.
Delete the element that has the value "Volvo":
cars = ["Ford", "Volvo", "BMW"]
cars.remove("Volvo")
print(cars)
This will give output:
['Ford', 'BMW']
Array Methods
Python has a set of built-in methods that you can
use on lists/arrays.
Sequence Type & Mutability
A sequence type is a type of data in Python which is
able to store more than one value (or less than one, as a
sequence may be empty), and these values can be
sequentially (hence the name) browsed, element by
element.
As the for loop is a tool especially designed to iterate
through sequences, we can express the definition as: a
sequence is data which can be scanned by
the for loop.
Mutability is a property of any Python data that
describes its readiness to be freely changed during
program execution. There are two kinds of Python
data: mutable and immutable.
Mutable data can be freely updated at any time − we call
such an operation in situ.
In situ is a Latin phrase that translates as literally in position.
For example, the following instruction modifies the data in situ:
list.append(1)
Immutable data cannot be modified in this way.
Imagine that a list can only be assigned and read over. You
would be able neither to append an element to it, nor remove
any element from it. This means that appending an element to
the end of the list would require the recreation of the list from
scratch.
You would have to build a completely new list, consisting of the
Sequence Type & Mutability
A tuple is a sequence of values, which can be of any type and they
are indexed by integer. Tuples are just like list, but we can’t change
values of tuples in place.
A tuple is an immutable sequence type. It can behave like a list,
but it can't be modified in situ.
The index value of tuple starts from 0.
A tuple consists of a number of values separated by commas.
tuple_1 = (1, 2, 4, 8)
tuple_2 = 1., .5, .25, .125
print(tuple_1)
print(tuple_2)
The output:
(1, 2, 4, 8)
(1.0, 0.5, 0.25, 0.125)
Each tuple element may be of a different type (floating-point,
integer, or any other not-as-yet-introduced kind of data).
WHAT IS TUPLE?
CREATING EMPTY TUPLE
It is possible to create an empty tuple – parentheses
are required then:
If you want to create a one-element tuple, you have to take
into consideration the fact that, due to syntax reasons (a
tuple has to be distinguishable from an ordinary, single
value), you must end the value with a comma:
one_element_tuple_1 = (1, )
one_element_tuple_2 = 1.,
Removing the commas won't spoil the program in any
syntactical sense, but you will instead get two single
variables, not tuples.
CREATING TUPLE
ACCESSING TUPLE
If you want to get the elements of a tuple in order to read
them over, you can use the same conventions to which
you're accustomed while using lists.
The similarities may be misleading − don't try to modify a
tuple's contents! It's not a list!
ACCESSING TUPLE USING LOOPS
OUTPUT
OUTPUT
CHECK IF ITEM EXISTS
OUTPUT
TUPLE LENGTH
You cannot remove or delete or update items in a
tuple.
Tuples are unchangeable, so you cannot remove
items from it, but you can delete the tuple completely:
NOTE: TUPLES ARE IMMUTABLE
REMOVING A TUPLE
Python provides two built-in methods that you can
use on tuples.
1. count() Method
2. index() Method
TUPLE METHODS
1. count() Method
Return the number of times the value appears in the
tuple
Count()
method
returns
total no
times
‘banana’
present in
the given
tuple
TUPLE METHODS
What else can tuples do for you?
•the len() function accepts tuples, and returns the
number of elements contained inside;
•the + operator can join tuples together (we've shown
you this already)
•the * operator can multiply tuples, just like lists;
•the in and not in operators work in the same way as in
lists.
What else can tuples do for you?
my_tuple = (1, 10, 100)
t1 = my_tuple + (1000, 10000)
t2 = my_tuple * 3
print(len(t2))
print(t1)
print(t2)
print(10 in my_tuple)
print(-10 not in my_tuple)
The output should look
as follows:
9
(1, 10, 100, 1000,
10000)
(1, 10, 100, 1, 10, 100,
1, 10, 100)
True
True
•One of the most useful tuple properties is their ability
to appear on the left side of the assignment operator.
• A tuple's elements can be variables, not only literals.
Moreover, they can be expressions if they're on the right side
of the assignment operator.
var = 123
t1 = (1, )
t2 = (2, )
t3 = (3, var)
t1, t2, t3 = t2, t3, t1
print(t1, t2, t3)
What else can tuples do for you?
2. index() Method
index() Method returns index of
“banana” i.e 1
index()
Method
TUPLE METHODS
LIST TUPLE
Syntax for list is slightly
different comparing with
tuple
Syntax for tuple is slightly
different comparing with lists
Weekdays=[‘Sun’,’Mon’,
‘wed’,46,67]
type(Weekdays)
class<‘lists’>
twdays = (‘Sun’, ‘mon', ‘tue',
634)
type(twdays)
class<‘tuple’>
List uses [ and ] (square
brackets) to bind the
elements.
Tuple uses rounded brackets(
and ) to bind the elements.
DIFFERENCE BETWEEN LIST AND TUPLE
LIST TUPLE
List can be edited once it
is created in python. Lists
are mutable data
structure.
A tuple is a list which one
cannot edit once it is created in
Python code. The tuple is an
immutable data structure
More methods or functions
are associated with lists.
Compare to lists tuples have
Less methods or functions.
DIFFERENCE BETWEEN LIST AND TUPLE
Dictionaries
The dictionary is another Python data structure. It's not a
sequence type (but can be easily adapted to sequence processing)
and it is mutable.
Dictionaries are not lists - they don't preserve the order of their
data, as the order is completely meaningless (unlike in real, paper
dictionaries).
In Python 3.6x dictionaries have become ordered collections by
default. Your results may vary depending on what Python version
you're using. The order in which a dictionary stores its data is
completely out of your control, and your expectations.
In Python's world, the word you look for is named a key. The word
you get from the dictionary is called a value.
This means that a dictionary is a set of key-value pairs. Note:
•each key must be unique − it's not possible to have more than one
key of the same value;
•a key may be any immutable type of object: it can be a number
(integer or float), or even a string, but not a list;
•a dictionary is not a list − a list contains a set of numbered values,
while a dictionary holds pairs of values;
•the len() function works for dictionaries, too − it returns the number
of key-value elements in the dictionary;
•a dictionary is a one-way tool − if you have an English-French
dictionary, you can look for French equivalents of English terms, but
not vice versa.
Dictionaries
How to use a dictionary
dictionary = {"cat": "chat", "dog": "chien", "horse": "cheval"}
phone_numbers = {'boss' : 5551234567, 'Suzy' : 22657854310}
empty_dictionary = {}
print(dictionary['cat'])
print(phone_numbers['Suzy’])
Getting a dictionary's value resembles indexing, especially thanks to the brackets
surrounding the key's value.
Note:
•if the key is a string, you have to specify it as a string;
•keys are case-sensitive: 'Suzy' is something different from 'suzy'.
The snippet outputs two lines of text:
chat
5557654321
you mustn't use a non-existent key.
Dictionary methods and functions
Can dictionaries be browsed using the for loop, like lists or tuples?
No and yes.
No, because a dictionary is not a sequence type − the for loop is
useless with it.
Yes, because there are simple and very effective tools that can adapt
any dictionary to the for loop requirements (in other words,
building an intermediate link between the dictionary and a temporary
sequence entity).
The keys() method
keys(), is possessed by each dictionary. The
method returns an iterable object consisting of all
the keys gathered within the dictionary. Having a
group of keys enables you to access the whole
dictionary in an easy and handy way. dictionary =
{"cat": "chat", "dog": "chien", "horse": "che
val"}
for key in dictionary.keys():
print(key, "->", dictionary[key]
Dictionary methods and functions
The items() method
items() method returns tuples (this is the first example where
tuples are something more than just an example of
themselves) where each tuple is a key-value pair.
dictionary =
{"cat": "chat", "dog": "chien", "horse": "cheval"}
for english, french in dictionary.items():
print(english, "->", french)
Note the way in which the tuple has been used as a for loop
variable.
Dictionary methods and functions
Modifying and adding values in Dictionary
Assigning a new value to an existing key is simple - as
dictionaries are fully mutable, there are no obstacles to
modifying them.
We're going to replace the value "chat" with "minou", which is
not very accurate, but it will work well with our example.
dictionary =
{"cat": "chat", "dog": "chien", "horse": "cheval"}
dictionary['cat'] = 'minou'
print(dictionary)
The output is:
{'cat': 'minou', 'dog': 'chien', 'horse': 'cheval'}
Do you want it sorted? Just enrich the for loop to get such a form:
for key in sorted(dictionary.keys()):
There is also a method called values(), which works similarly
to keys(), but returns values.
Here is a simple example:
dictionary =
{"cat": "chat", "dog": "chien", "horse": "cheval"}
for french in dictionary.values():
print(french)
As the dictionary is not able to automatically find a key for a given
value, the role of this method is rather limited.
Modifying and adding values in Dictionary
Adding a new key-value pair to a dictionary is as simple as changing a
value – you only have to assign a value to a new, previously non-
existent key.
Note: this is very different behavior compared to lists, which don't allow
you to assign values to non-existing indices.
Let's add a new pair of words to the dictionary − a bit weird, but still valid:
dictionary =
{"cat": "chat", "dog": "chien", "horse": "cheval"}
dictionary['swan'] = 'cygne'
print(dictionary)
The example outputs:
{'cat': 'chat', 'dog': 'chien', 'horse': 'cheval', 'swan': '
cygne’}
Adding a new key in Dictionary
You can also insert an item to a dictionary by using
the update() method, e.g.:
dictionary =
{"cat": "chat", "dog": "chien", "horse": "che
val"}
dictionary.update({"duck": "canard"})
print(dictionary)
Adding a new key in Dictionary
Removing a key in Dictionary
Can you guess how to remove a key from a dictionary?
Note: removing a key will always cause the removal of the associated
value. Values cannot exist without their keys.
This is done with the del instruction.
Here's the example:
dictionary = {"cat": "chat", "dog": "chien", "horse": "cheval"}
del dictionary['dog']
print(dictionary)
Note: removing a non-existing key causes an error.
The example outputs:
{'cat': 'chat', 'horse': 'cheval’}
To remove the last item in a dictionary, you can use
the popitem() method:
dictionary =
{"cat": "chat", "dog": "chien", "horse": "cheval"
}
dictionary.popitem()
print(dictionary) # outputs: {'cat': 'chat',
'dog': 'chien’}
In the older versions of Python, i.e., before 3.6.7,
the popitem() method removes a random item from a
dictionary.
Removing a key in Dictionary
TUPLE DICTIONARY
Order is maintained. Ordering is not guaranteed.
They are immutable. Values in a dictionary can be
changed.
They can hold any type,
and types can be mixed.
Every entry has a key and a
value.
DIFFERENCE BETWEEN TUPLE AND
DICTIONARY
Tuples and dictionaries can work together
TUPLE DICTIONARY
Elements are accessed via
numeric (zero based)
indices
Elements are accessed using
key's values
There is a difference in
syntax and looks easy to
define tuple
Differ in syntax, looks bit
complicated when compare
with Tuple or lists
DIFFERENCE BETWEEN TUPLE AND
DICTIONARY
Python Exceptions Handling
Python provides a very important features to handle any unexpected error in
your Python programs and to add debugging capabilities in them:
 Exception Handling: This would be covered in this tutorial.
What is Exception?
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 can't cope with,
it raises an exception. An exception is a Python object that represents an
error.
When a Python script raises an exception, it must either handle the exception
immediately otherwise it would terminate and come out.
Handling an exception
If you have some suspicious code that may raise an exception, you can
defend your program by placing the suspicious code in a try: block.
After the try: block, include an except: statement, followed by a block of code
which handles the problem as elegantly as possible.
Syntax:
try:
You do your operations here;
......................
except Exception I:
If there is ExceptionI, then execute this block.
except Exception II:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.
Here are few important points above the above mentioned syntax:
A single try statement can have multiple except statements. This is useful
when the try block contains statements that may throw different types of
exceptions.
You can also provide a generic except clause, which handles any exception.
After the except clause(s), you can include an else-clause. The code in the
else-block executes if the code in the try: block does not raise an exception.
The else-block is a good place for code that does not need the try: block's
protection.
Handling an exception
Example:
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception
handling!!")
except IOError: print "Error: can't find file or read
data"
else: print "Written content in the file successfully"
fh.close()
This will produce following result:
Written content in the file successfully
Handling an exception
The except clause with no exceptions:
You can also use the except statement with no exceptions defined as follows:
try:
You do your operations here;
......................
except:
If there is any exception, then execute this block.
......................
else:
If there is no exception then execute this block.
This kind of a try-except statement catches all the exceptions that occur. Using this
kind of try-except statement is not considered a good programming practice, though,
because it catches all exceptions but does not make the programmer identify the root
cause of the problem that may occur.
Handling an exception
The except clause with multiple exceptions:
You can also use the same except statement to handle multiple
exceptions as follows:
try:
You do your operations here;
......................
except(Exception1[, Exception2[,...ExceptionN]]]):
If there is any exception from the given exception
list, then execute this block
.......................
else:
If there is no exception then execute this block.
Handling an exception
Standard Exceptions
Here is a list standard Exceptions available in Python: Standard
Exceptions
The try-finally clause:
You can use a finally: block along with a try: block. The finally block
is a place to put any code that must execute, whether the try-block raised an
exception or not. The syntax of the try-finally statement is this:
try:
You do your operations here;
......................
Due to any exception, this may be skipped.
finally:
This would always be executed.
......................
Note that you can provide except clause(s), or a finally clause, but
not both. You can not use else clause as well along with a finally clause.
Example:
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception
handling!!")
finally:
print "Error: can't find file or read data"
If you do not have permission to open the file in writing mode then this
will produce following result:
Error: can't find file or read data
Standard Exceptions
Argument of an Exception
An exception can have an argument, which is a value that gives
additional information about the problem. The contents of the argument vary
by exception. You capture an exception's argument by supplying a variable in
the except clause as follows:
try:
You do your operations here;
......................
except ExceptionType, Argument:
You can print value of Argument here...
If you are writing the code to handle a single exception, you can have a
variable follow the name of the exception in the except statement. If you are
trapping multiple exceptions, you can have a variable follow the tuple of the
exception.
This variable will receive the value of the exception mostly containing the
cause of the exception. The variable can receive a single value or multiple
values in the form of a tuple. This tuple usually contains the error string, the
error number, and an error location.
Example:
Following is an example for a single exception:
def temp_convert(var):
try:
return int(var)
except ValueError, Argument:
print "The argument does not contain
numbersn", Argument
temp_convert("xyz");
This would produce following result:
The argument does not contain numbers
invalid literal for int() with base 10: 'xyz'
Argument of an Exception
Raising an exceptions
You can raise exceptions in several ways by using the raise
statement. The general syntax for the raise statement.
Syntax:
raise [Exception [, args [, traceback]]]
Here Exception is the type of exception (for example, NameError) and
argument is a value for the exception argument. The argument is optional; if
not supplied, the exception argument is None.
The final argument, traceback, is also optional (and rarely used in practice),
and, if present, is the traceback object used for the exception
Example:
def functionName( level ):
if level < 1:
raise "Invalid level!", level
# The code below to this would not be executed
# if we raise the exception
Note: In order to catch an exception, an "except" clause must refer to
the same exception thrown either class object or simple string. For
example to capture above exception we must write our except clause
as follows:
try:
Business Logic here...
except "Invalid level!":
Exception handling here...
else:
Rest of the code here...
Raising an exceptions
User-Defined Exceptions
Python also allows you to create your own exceptions by deriving classes
from the standard built-in exceptions.
Here is an example related to RuntimeError. Here a class is created that is
subclassed from RuntimeError. This is useful when you need to display more
specific information when an exception is caught.
In the try block, the user-defined exception is raised and caught in the except
block. The variable e is used to create an instance of the class Networkerror.
class Networkerror(RuntimeError):
def __init__(self, arg):
self.args = arg
So once you defined above class, you can raise your exception as follows:
try:
raise Networkerror("Bad hostname")
except Networkerror,e:
print e.args

Weitere ähnliche Inhalte

Ähnlich wie Lecture 09.pptx

RANDOMISATION-NUMERICAL METHODS FOR ENGINEERING.pptx
RANDOMISATION-NUMERICAL METHODS  FOR ENGINEERING.pptxRANDOMISATION-NUMERICAL METHODS  FOR ENGINEERING.pptx
RANDOMISATION-NUMERICAL METHODS FOR ENGINEERING.pptxOut Cast
 
11 Introduction to lists.pptx
11 Introduction to lists.pptx11 Introduction to lists.pptx
11 Introduction to lists.pptxssuser8e50d8
 
Mastering Python lesson 5a_lists_list_operations
Mastering Python lesson 5a_lists_list_operationsMastering Python lesson 5a_lists_list_operations
Mastering Python lesson 5a_lists_list_operationsRuth Marvin
 
CS 360 LAB 3 STRINGS, FUNCTIONS, AND METHODSObjective The purpos.docx
CS 360 LAB 3 STRINGS, FUNCTIONS, AND METHODSObjective The purpos.docxCS 360 LAB 3 STRINGS, FUNCTIONS, AND METHODSObjective The purpos.docx
CS 360 LAB 3 STRINGS, FUNCTIONS, AND METHODSObjective The purpos.docxfaithxdunce63732
 
PYTHON LISTsjnjsnljnsjnosojnosojnsojnsjsn.pptx
PYTHON LISTsjnjsnljnsjnosojnosojnsojnsjsn.pptxPYTHON LISTsjnjsnljnsjnosojnosojnsojnsjsn.pptx
PYTHON LISTsjnjsnljnsjnosojnosojnsojnsjsn.pptxsurajnath20
 
Towards a New Data Modelling Architecture - Part 1
Towards a New Data Modelling Architecture - Part 1Towards a New Data Modelling Architecture - Part 1
Towards a New Data Modelling Architecture - Part 1JEAN-MICHEL LETENNIER
 
Arrays in programming
Arrays in programmingArrays in programming
Arrays in programmingTaseerRao
 
COMPLEX AND USER DEFINED TYPESPlease note that the material on t.docx
COMPLEX AND USER DEFINED TYPESPlease note that the material on t.docxCOMPLEX AND USER DEFINED TYPESPlease note that the material on t.docx
COMPLEX AND USER DEFINED TYPESPlease note that the material on t.docxdonnajames55
 
MODULE-2.pptx
MODULE-2.pptxMODULE-2.pptx
MODULE-2.pptxASRPANDEY
 
Python Interview Questions And Answers
Python Interview Questions And AnswersPython Interview Questions And Answers
Python Interview Questions And AnswersH2Kinfosys
 
Python For Data Science.pptx
Python For Data Science.pptxPython For Data Science.pptx
Python For Data Science.pptxrohithprabhas1
 
Chapter 2.2 data structures
Chapter 2.2 data structuresChapter 2.2 data structures
Chapter 2.2 data structuressshhzap
 
Improve Your Edge on Machine Learning - Day 1.pptx
Improve Your Edge on Machine Learning - Day 1.pptxImprove Your Edge on Machine Learning - Day 1.pptx
Improve Your Edge on Machine Learning - Day 1.pptxCatherineVania1
 

Ähnlich wie Lecture 09.pptx (20)

RANDOMISATION-NUMERICAL METHODS FOR ENGINEERING.pptx
RANDOMISATION-NUMERICAL METHODS  FOR ENGINEERING.pptxRANDOMISATION-NUMERICAL METHODS  FOR ENGINEERING.pptx
RANDOMISATION-NUMERICAL METHODS FOR ENGINEERING.pptx
 
11 Introduction to lists.pptx
11 Introduction to lists.pptx11 Introduction to lists.pptx
11 Introduction to lists.pptx
 
Mastering Python lesson 5a_lists_list_operations
Mastering Python lesson 5a_lists_list_operationsMastering Python lesson 5a_lists_list_operations
Mastering Python lesson 5a_lists_list_operations
 
CS 360 LAB 3 STRINGS, FUNCTIONS, AND METHODSObjective The purpos.docx
CS 360 LAB 3 STRINGS, FUNCTIONS, AND METHODSObjective The purpos.docxCS 360 LAB 3 STRINGS, FUNCTIONS, AND METHODSObjective The purpos.docx
CS 360 LAB 3 STRINGS, FUNCTIONS, AND METHODSObjective The purpos.docx
 
PYTHON LISTsjnjsnljnsjnosojnosojnsojnsjsn.pptx
PYTHON LISTsjnjsnljnsjnosojnosojnsojnsjsn.pptxPYTHON LISTsjnjsnljnsjnosojnosojnsojnsjsn.pptx
PYTHON LISTsjnjsnljnsjnosojnosojnsojnsjsn.pptx
 
Towards a New Data Modelling Architecture - Part 1
Towards a New Data Modelling Architecture - Part 1Towards a New Data Modelling Architecture - Part 1
Towards a New Data Modelling Architecture - Part 1
 
pyton Notes6
 pyton Notes6 pyton Notes6
pyton Notes6
 
Arrays in programming
Arrays in programmingArrays in programming
Arrays in programming
 
COMPLEX AND USER DEFINED TYPESPlease note that the material on t.docx
COMPLEX AND USER DEFINED TYPESPlease note that the material on t.docxCOMPLEX AND USER DEFINED TYPESPlease note that the material on t.docx
COMPLEX AND USER DEFINED TYPESPlease note that the material on t.docx
 
MODULE-2.pptx
MODULE-2.pptxMODULE-2.pptx
MODULE-2.pptx
 
Chapter - 2.pptx
Chapter - 2.pptxChapter - 2.pptx
Chapter - 2.pptx
 
Python Interview Questions And Answers
Python Interview Questions And AnswersPython Interview Questions And Answers
Python Interview Questions And Answers
 
Tuples-and-Dictionaries.pptx
Tuples-and-Dictionaries.pptxTuples-and-Dictionaries.pptx
Tuples-and-Dictionaries.pptx
 
tupple.pptx
tupple.pptxtupple.pptx
tupple.pptx
 
Python For Data Science.pptx
Python For Data Science.pptxPython For Data Science.pptx
Python For Data Science.pptx
 
Chapter 2.2 data structures
Chapter 2.2 data structuresChapter 2.2 data structures
Chapter 2.2 data structures
 
Ch-8.pdf
Ch-8.pdfCh-8.pdf
Ch-8.pdf
 
Python revision tour II
Python revision tour IIPython revision tour II
Python revision tour II
 
dataStructuresInPython.pptx
dataStructuresInPython.pptxdataStructuresInPython.pptx
dataStructuresInPython.pptx
 
Improve Your Edge on Machine Learning - Day 1.pptx
Improve Your Edge on Machine Learning - Day 1.pptxImprove Your Edge on Machine Learning - Day 1.pptx
Improve Your Edge on Machine Learning - Day 1.pptx
 

Kürzlich hochgeladen

9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxShobhayan Kirtania
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 

Kürzlich hochgeladen (20)

Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptx
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 

Lecture 09.pptx

  • 1. Mohammad Hassan Array, Tuples, Dictionary, Exception
  • 2. Objectives Arrays; Sequence Type & Mutability; Understand the need of Tuples; Solve problems by using Tuples;  Get clear idea about Tuple functions; Understand the difference between list, dictionary and tuples; and Exceptions
  • 3. Arrays are used to store multiple values in one single variable: cars = ["Ford", "Volvo", "BMW"] An array is a special variable, which can hold more than one value at a time. If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this: car1 = "Ford" car2 = "Volvo" car3 = "BMW“ what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300? The solution is an array! An array can hold many values under a single name, and you can access the values by referring to an index number. ARRAY
  • 4. Access the Elements of an Array Get the value of the first array item: cars = ["Ford", "Volvo", "BMW"] x = cars[0] print(x) This will give output: Ford
  • 5. Modify the value of the first array Modify the value of the first array item: cars = ["Ford", "Volvo", "BMW"] cars[0] = "Toyota" print(cars) This will give output: ['Toyota', 'Volvo', 'BMW']
  • 6. The Length of an Array Use the len() method to return the length of an array (the number of elements in an array). Return the number of elements in the cars array: cars = ["Ford", "Volvo", "BMW"] x = len(cars) print(x) This will give output: 3 The length of an array is always one more than the highest array index.
  • 7. Looping Array Elements Print each item in the cars array: cars = ["Ford", "Volvo", "BMW"] for x in cars: print(x) This will give output: Ford Volvo BMW
  • 8. WHAT IS TUPLE? A tuple is essentially an immutable list. Below is a list with three elements and a tuple with three elements: L = [1,2,3] t = (1,2,3) Tuples are enclosed in parentheses, though the parentheses are actually optional. Indexing and slicing work the same as with lists. As with lists, you can get the length of the tuple by using the len function, and, like lists, tuples have count and index methods.However, since a tuple is immutable, it does not have any of the other methods that lists have, like sort or reverse, as those change the list.
  • 9. Adding Array Elements You can use the append() method to add an element to an array. Add one more element to the cars array: cars = ["Ford", "Volvo", "BMW"] cars.append("Honda") print(cars) This will give output: ['Ford', 'Volvo', 'BMW', 'Honda']
  • 10. Removing Array Elements You can use the pop() method to remove an element from the array. Delete the second element of the cars array: cars = ["Ford", "Volvo", "BMW"] cars.pop(1) print(cars) This will give output: ['Ford', 'BMW’] You can also use the remove() method to remove an element from the array. Delete the element that has the value "Volvo": cars = ["Ford", "Volvo", "BMW"] cars.remove("Volvo") print(cars) This will give output: ['Ford', 'BMW']
  • 11. Array Methods Python has a set of built-in methods that you can use on lists/arrays.
  • 12. Sequence Type & Mutability A sequence type is a type of data in Python which is able to store more than one value (or less than one, as a sequence may be empty), and these values can be sequentially (hence the name) browsed, element by element. As the for loop is a tool especially designed to iterate through sequences, we can express the definition as: a sequence is data which can be scanned by the for loop. Mutability is a property of any Python data that describes its readiness to be freely changed during program execution. There are two kinds of Python data: mutable and immutable.
  • 13. Mutable data can be freely updated at any time − we call such an operation in situ. In situ is a Latin phrase that translates as literally in position. For example, the following instruction modifies the data in situ: list.append(1) Immutable data cannot be modified in this way. Imagine that a list can only be assigned and read over. You would be able neither to append an element to it, nor remove any element from it. This means that appending an element to the end of the list would require the recreation of the list from scratch. You would have to build a completely new list, consisting of the Sequence Type & Mutability
  • 14. A tuple is a sequence of values, which can be of any type and they are indexed by integer. Tuples are just like list, but we can’t change values of tuples in place. A tuple is an immutable sequence type. It can behave like a list, but it can't be modified in situ. The index value of tuple starts from 0. A tuple consists of a number of values separated by commas. tuple_1 = (1, 2, 4, 8) tuple_2 = 1., .5, .25, .125 print(tuple_1) print(tuple_2) The output: (1, 2, 4, 8) (1.0, 0.5, 0.25, 0.125) Each tuple element may be of a different type (floating-point, integer, or any other not-as-yet-introduced kind of data). WHAT IS TUPLE?
  • 15. CREATING EMPTY TUPLE It is possible to create an empty tuple – parentheses are required then:
  • 16. If you want to create a one-element tuple, you have to take into consideration the fact that, due to syntax reasons (a tuple has to be distinguishable from an ordinary, single value), you must end the value with a comma: one_element_tuple_1 = (1, ) one_element_tuple_2 = 1., Removing the commas won't spoil the program in any syntactical sense, but you will instead get two single variables, not tuples. CREATING TUPLE
  • 17. ACCESSING TUPLE If you want to get the elements of a tuple in order to read them over, you can use the same conventions to which you're accustomed while using lists. The similarities may be misleading − don't try to modify a tuple's contents! It's not a list!
  • 18. ACCESSING TUPLE USING LOOPS OUTPUT
  • 21. You cannot remove or delete or update items in a tuple. Tuples are unchangeable, so you cannot remove items from it, but you can delete the tuple completely: NOTE: TUPLES ARE IMMUTABLE REMOVING A TUPLE
  • 22. Python provides two built-in methods that you can use on tuples. 1. count() Method 2. index() Method TUPLE METHODS
  • 23. 1. count() Method Return the number of times the value appears in the tuple Count() method returns total no times ‘banana’ present in the given tuple TUPLE METHODS
  • 24. What else can tuples do for you? •the len() function accepts tuples, and returns the number of elements contained inside; •the + operator can join tuples together (we've shown you this already) •the * operator can multiply tuples, just like lists; •the in and not in operators work in the same way as in lists.
  • 25. What else can tuples do for you? my_tuple = (1, 10, 100) t1 = my_tuple + (1000, 10000) t2 = my_tuple * 3 print(len(t2)) print(t1) print(t2) print(10 in my_tuple) print(-10 not in my_tuple) The output should look as follows: 9 (1, 10, 100, 1000, 10000) (1, 10, 100, 1, 10, 100, 1, 10, 100) True True
  • 26. •One of the most useful tuple properties is their ability to appear on the left side of the assignment operator. • A tuple's elements can be variables, not only literals. Moreover, they can be expressions if they're on the right side of the assignment operator. var = 123 t1 = (1, ) t2 = (2, ) t3 = (3, var) t1, t2, t3 = t2, t3, t1 print(t1, t2, t3) What else can tuples do for you?
  • 27. 2. index() Method index() Method returns index of “banana” i.e 1 index() Method TUPLE METHODS
  • 28. LIST TUPLE Syntax for list is slightly different comparing with tuple Syntax for tuple is slightly different comparing with lists Weekdays=[‘Sun’,’Mon’, ‘wed’,46,67] type(Weekdays) class<‘lists’> twdays = (‘Sun’, ‘mon', ‘tue', 634) type(twdays) class<‘tuple’> List uses [ and ] (square brackets) to bind the elements. Tuple uses rounded brackets( and ) to bind the elements. DIFFERENCE BETWEEN LIST AND TUPLE
  • 29. LIST TUPLE List can be edited once it is created in python. Lists are mutable data structure. A tuple is a list which one cannot edit once it is created in Python code. The tuple is an immutable data structure More methods or functions are associated with lists. Compare to lists tuples have Less methods or functions. DIFFERENCE BETWEEN LIST AND TUPLE
  • 30. Dictionaries The dictionary is another Python data structure. It's not a sequence type (but can be easily adapted to sequence processing) and it is mutable. Dictionaries are not lists - they don't preserve the order of their data, as the order is completely meaningless (unlike in real, paper dictionaries). In Python 3.6x dictionaries have become ordered collections by default. Your results may vary depending on what Python version you're using. The order in which a dictionary stores its data is completely out of your control, and your expectations.
  • 31. In Python's world, the word you look for is named a key. The word you get from the dictionary is called a value. This means that a dictionary is a set of key-value pairs. Note: •each key must be unique − it's not possible to have more than one key of the same value; •a key may be any immutable type of object: it can be a number (integer or float), or even a string, but not a list; •a dictionary is not a list − a list contains a set of numbered values, while a dictionary holds pairs of values; •the len() function works for dictionaries, too − it returns the number of key-value elements in the dictionary; •a dictionary is a one-way tool − if you have an English-French dictionary, you can look for French equivalents of English terms, but not vice versa. Dictionaries
  • 32. How to use a dictionary dictionary = {"cat": "chat", "dog": "chien", "horse": "cheval"} phone_numbers = {'boss' : 5551234567, 'Suzy' : 22657854310} empty_dictionary = {} print(dictionary['cat']) print(phone_numbers['Suzy’]) Getting a dictionary's value resembles indexing, especially thanks to the brackets surrounding the key's value. Note: •if the key is a string, you have to specify it as a string; •keys are case-sensitive: 'Suzy' is something different from 'suzy'. The snippet outputs two lines of text: chat 5557654321 you mustn't use a non-existent key.
  • 33. Dictionary methods and functions Can dictionaries be browsed using the for loop, like lists or tuples? No and yes. No, because a dictionary is not a sequence type − the for loop is useless with it. Yes, because there are simple and very effective tools that can adapt any dictionary to the for loop requirements (in other words, building an intermediate link between the dictionary and a temporary sequence entity).
  • 34. The keys() method keys(), is possessed by each dictionary. The method returns an iterable object consisting of all the keys gathered within the dictionary. Having a group of keys enables you to access the whole dictionary in an easy and handy way. dictionary = {"cat": "chat", "dog": "chien", "horse": "che val"} for key in dictionary.keys(): print(key, "->", dictionary[key] Dictionary methods and functions
  • 35. The items() method items() method returns tuples (this is the first example where tuples are something more than just an example of themselves) where each tuple is a key-value pair. dictionary = {"cat": "chat", "dog": "chien", "horse": "cheval"} for english, french in dictionary.items(): print(english, "->", french) Note the way in which the tuple has been used as a for loop variable. Dictionary methods and functions
  • 36. Modifying and adding values in Dictionary Assigning a new value to an existing key is simple - as dictionaries are fully mutable, there are no obstacles to modifying them. We're going to replace the value "chat" with "minou", which is not very accurate, but it will work well with our example. dictionary = {"cat": "chat", "dog": "chien", "horse": "cheval"} dictionary['cat'] = 'minou' print(dictionary) The output is: {'cat': 'minou', 'dog': 'chien', 'horse': 'cheval'}
  • 37. Do you want it sorted? Just enrich the for loop to get such a form: for key in sorted(dictionary.keys()): There is also a method called values(), which works similarly to keys(), but returns values. Here is a simple example: dictionary = {"cat": "chat", "dog": "chien", "horse": "cheval"} for french in dictionary.values(): print(french) As the dictionary is not able to automatically find a key for a given value, the role of this method is rather limited. Modifying and adding values in Dictionary
  • 38. Adding a new key-value pair to a dictionary is as simple as changing a value – you only have to assign a value to a new, previously non- existent key. Note: this is very different behavior compared to lists, which don't allow you to assign values to non-existing indices. Let's add a new pair of words to the dictionary − a bit weird, but still valid: dictionary = {"cat": "chat", "dog": "chien", "horse": "cheval"} dictionary['swan'] = 'cygne' print(dictionary) The example outputs: {'cat': 'chat', 'dog': 'chien', 'horse': 'cheval', 'swan': ' cygne’} Adding a new key in Dictionary
  • 39. You can also insert an item to a dictionary by using the update() method, e.g.: dictionary = {"cat": "chat", "dog": "chien", "horse": "che val"} dictionary.update({"duck": "canard"}) print(dictionary) Adding a new key in Dictionary
  • 40. Removing a key in Dictionary Can you guess how to remove a key from a dictionary? Note: removing a key will always cause the removal of the associated value. Values cannot exist without their keys. This is done with the del instruction. Here's the example: dictionary = {"cat": "chat", "dog": "chien", "horse": "cheval"} del dictionary['dog'] print(dictionary) Note: removing a non-existing key causes an error. The example outputs: {'cat': 'chat', 'horse': 'cheval’}
  • 41. To remove the last item in a dictionary, you can use the popitem() method: dictionary = {"cat": "chat", "dog": "chien", "horse": "cheval" } dictionary.popitem() print(dictionary) # outputs: {'cat': 'chat', 'dog': 'chien’} In the older versions of Python, i.e., before 3.6.7, the popitem() method removes a random item from a dictionary. Removing a key in Dictionary
  • 42. TUPLE DICTIONARY Order is maintained. Ordering is not guaranteed. They are immutable. Values in a dictionary can be changed. They can hold any type, and types can be mixed. Every entry has a key and a value. DIFFERENCE BETWEEN TUPLE AND DICTIONARY Tuples and dictionaries can work together
  • 43. TUPLE DICTIONARY Elements are accessed via numeric (zero based) indices Elements are accessed using key's values There is a difference in syntax and looks easy to define tuple Differ in syntax, looks bit complicated when compare with Tuple or lists DIFFERENCE BETWEEN TUPLE AND DICTIONARY
  • 44. Python Exceptions Handling Python provides a very important features to handle any unexpected error in your Python programs and to add debugging capabilities in them:  Exception Handling: This would be covered in this tutorial. What is Exception? 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 can't cope with, it raises an exception. An exception is a Python object that represents an error. When a Python script raises an exception, it must either handle the exception immediately otherwise it would terminate and come out.
  • 45. Handling an exception If you have some suspicious code that may raise an exception, you can defend your program by placing the suspicious code in a try: block. After the try: block, include an except: statement, followed by a block of code which handles the problem as elegantly as possible. Syntax: try: You do your operations here; ...................... except Exception I: If there is ExceptionI, then execute this block. except Exception II: If there is ExceptionII, then execute this block. ...................... else: If there is no exception then execute this block.
  • 46. Here are few important points above the above mentioned syntax: A single try statement can have multiple except statements. This is useful when the try block contains statements that may throw different types of exceptions. You can also provide a generic except clause, which handles any exception. After the except clause(s), you can include an else-clause. The code in the else-block executes if the code in the try: block does not raise an exception. The else-block is a good place for code that does not need the try: block's protection. Handling an exception
  • 47. Example: try: fh = open("testfile", "w") fh.write("This is my test file for exception handling!!") except IOError: print "Error: can't find file or read data" else: print "Written content in the file successfully" fh.close() This will produce following result: Written content in the file successfully Handling an exception
  • 48. The except clause with no exceptions: You can also use the except statement with no exceptions defined as follows: try: You do your operations here; ...................... except: If there is any exception, then execute this block. ...................... else: If there is no exception then execute this block. This kind of a try-except statement catches all the exceptions that occur. Using this kind of try-except statement is not considered a good programming practice, though, because it catches all exceptions but does not make the programmer identify the root cause of the problem that may occur. Handling an exception
  • 49. The except clause with multiple exceptions: You can also use the same except statement to handle multiple exceptions as follows: try: You do your operations here; ...................... except(Exception1[, Exception2[,...ExceptionN]]]): If there is any exception from the given exception list, then execute this block ....................... else: If there is no exception then execute this block. Handling an exception
  • 50. Standard Exceptions Here is a list standard Exceptions available in Python: Standard Exceptions The try-finally clause: You can use a finally: block along with a try: block. The finally block is a place to put any code that must execute, whether the try-block raised an exception or not. The syntax of the try-finally statement is this: try: You do your operations here; ...................... Due to any exception, this may be skipped. finally: This would always be executed. ...................... Note that you can provide except clause(s), or a finally clause, but not both. You can not use else clause as well along with a finally clause.
  • 51. Example: try: fh = open("testfile", "w") fh.write("This is my test file for exception handling!!") finally: print "Error: can't find file or read data" If you do not have permission to open the file in writing mode then this will produce following result: Error: can't find file or read data Standard Exceptions
  • 52. Argument of an Exception An exception can have an argument, which is a value that gives additional information about the problem. The contents of the argument vary by exception. You capture an exception's argument by supplying a variable in the except clause as follows: try: You do your operations here; ...................... except ExceptionType, Argument: You can print value of Argument here... If you are writing the code to handle a single exception, you can have a variable follow the name of the exception in the except statement. If you are trapping multiple exceptions, you can have a variable follow the tuple of the exception. This variable will receive the value of the exception mostly containing the cause of the exception. The variable can receive a single value or multiple values in the form of a tuple. This tuple usually contains the error string, the error number, and an error location.
  • 53. Example: Following is an example for a single exception: def temp_convert(var): try: return int(var) except ValueError, Argument: print "The argument does not contain numbersn", Argument temp_convert("xyz"); This would produce following result: The argument does not contain numbers invalid literal for int() with base 10: 'xyz' Argument of an Exception
  • 54. Raising an exceptions You can raise exceptions in several ways by using the raise statement. The general syntax for the raise statement. Syntax: raise [Exception [, args [, traceback]]] Here Exception is the type of exception (for example, NameError) and argument is a value for the exception argument. The argument is optional; if not supplied, the exception argument is None. The final argument, traceback, is also optional (and rarely used in practice), and, if present, is the traceback object used for the exception Example: def functionName( level ): if level < 1: raise "Invalid level!", level # The code below to this would not be executed # if we raise the exception
  • 55. Note: In order to catch an exception, an "except" clause must refer to the same exception thrown either class object or simple string. For example to capture above exception we must write our except clause as follows: try: Business Logic here... except "Invalid level!": Exception handling here... else: Rest of the code here... Raising an exceptions
  • 56. User-Defined Exceptions Python also allows you to create your own exceptions by deriving classes from the standard built-in exceptions. Here is an example related to RuntimeError. Here a class is created that is subclassed from RuntimeError. This is useful when you need to display more specific information when an exception is caught. In the try block, the user-defined exception is raised and caught in the except block. The variable e is used to create an instance of the class Networkerror. class Networkerror(RuntimeError): def __init__(self, arg): self.args = arg So once you defined above class, you can raise your exception as follows: try: raise Networkerror("Bad hostname") except Networkerror,e: print e.args