Understanding Python Dictionary

Python has multiple data structures, and Dictionary is one of them. This tutorial will take you through every aspect of the dictionary data structure in Python language.

What is a Dictionary in Python?

When Python was launched, Dictionary was introduced as an unordered collection of items. However, later with Python 3.7 launch, Dictionary was made an ordered collection of items.

Dictionary is somewhat similar to an array, but every element of the dictionary has a key linked. You can use that key to access its respective element, unlike an array.

Note: The key of a dictionary has to be unique. Let’s understand the syntax of a Dictionary:

Syntax

Every element in a dictionary is comma-separated, and all the elements with their keys are enclosed in the curly brackets. The syntax is as follows:

Dic = {"key1":"value","key2":"value"}

Example: One real example of the dictionary is to store the number of subjects every student is enrolled in:

SubRecord = {"Smith":5,"Sam":4,"Lucy":6}

Here “SubRecord” is the name associated with the dictionary, and “Smith,” “Sam,” and “Lucy” are the keys of the dictionary. Whereas the integer values represent the number of subjects students are enrolled in.

How to define a Dictionary?

Though the syntax might seem simple to you, but there are multiple ways to define a dictionary in Python.  In this section, we will learn about some of the ways to create a dictionary in a Python program:

Basic Implementation

Dict1 = {1:"This",2:"is",3:"Python",4:"Programming"}
print(type(Dict1))

Output:

<class 'dict'>

Using “Dict()” Method with Assigning Operator

In the above method, we have used the colon “:” to link every element and key. It is preferred when we have to set integers as keys. However, if you want to use string instead of the colon, “:” equals to “=” can also be used. 

Dict2 = dict(
First =&nbsp; 'Python',
Second = "Programming"
print(type(Dict2))

Output:

<class 'dict'>

Apart from these two, there could be another way to create/define a dictionary in Python. We have listed the most popular ones among all. 

Accessing Dictionary Elements

Accessing Dictionary elements is pretty straightforward. It is almost similar to accessing elements of an array. In Array, we use the index values to access the elements, whereas, in Dictionary, we have to use keys to access the elements.

For instance,
We have the following dictionary:

Dict1 = {1:"This",2:"is",3:"Python",4:"Programming"}

Now, if you want to access the 4th element i.e., “Programming,” you have to write a code statement like this:

print(Dict1[4])

Output:

Programming

In case you provide a key input that doesn’t exist; you will get a similar exception message:

Traceback (Most recent call last):
  File '<string>', line 5, in <module>
KeyError: 5
>

Adding and Removing Elements from Dictionary

To add elements in a dictionary, you can use multiple ways. A few of them are listed below:

Adding Elements directly using Key

In this method, we simply add an element by defining it with a unique key.

For instance,

Let’s assume we have a pre-existing dictionary with the following elements:

Dict1 = {1:"This",2:"is",3:"Python",4:"Programming"}

Now, add a new element, we can use a similar code statement:

Dict1[5] = "Tutorial"
print(Dict1)

Output:

{1:"This",2:"is",3:"Python",4:"Programming,5:Tutorial"}

Here we have used a unique key; however, its value gets updated if an existing key is used.

For instance,

Dict1 = {1:"This",2:"is",3:"Python",4:"Programming"}
	Dict1[4] = "Tutorial"
	print(Dict1)

Output:

{1:"This",2:"is",3:"Python",4:"Tutorial"}

Adding Element using Update() Method

Python also has a built-in method to Add or Update existing dictionary elements.

For Instance,

Adding an new element:

Dict1 = {1:"This",2:"is",3:"Python",4:"Programming"}
Dict1.update({5:"Tutorial"})
print(Dict1)

Output:

{1:"This",2:"is",3:"Python",4:"Programming,5:Tutorial"}

Updating a existing element:

Dict1 = {1:"This",2:"is",3:"Python",4:"Programming"}
Dict1.update({3:"a"})
print(Dict1)

Output:

{1:"This",2:"is",3:"a",4:"Programming"}

So, that’s how you can add or update elements in the Python dictionary using the update() method. Now, lets learn:

Removing an Element from Dictionary

To remove an element from a dictionary, you can use the built-in del keyword of python.

For instance,

Dict1 = {1: 'This', 2: 'is', 3: 'Python', 4: 'Programming', 5: 'Tutorial'}
del Dict1[5]
print(Dict1)

Output:

{1:"This",2:"is",3:"Python",4:"Programming"}

Using the del keyword, you can also delete the whole dictionary.

Final Notes

Since you have gone through the whole tutorial, we hope now you have a clear understanding of Dictionaries in Python. In the next article, you will learn about other python data structures.

Python Operators Examples

The python operators are used to evaluate expressions. An expression consists of values and operators which always evaluates to a single value.

The python operators are classified in following types.

Figure 1 - Python Operators
Figure 1 – Python Operators

Program 1: Write a program to demonstrate the working of python arithmetic operator.

Solution:

#Filename : Arithmetic_Demo.py
#Write a program to demonstrate the working of python arithmetic operator.

#plus 

num1 = 23
num2 = 56
result = num1 + num2
print("Addition",result)

#minus

num1 = 321
num2 = 100
result = num1 - num2
print("Subtraction",result)

#multiplication

num1 = 24
num2 = 10
result = num1 * num2
print("Multiplication",result)

#division

num1 = 59
num2 = 3
result = num1 / num2
print("Division",result)

#floor division

num1 = 100
num2 = 31
result = num1 // num2
print("Floor Division",result)

#exponential

num1 = 3
num2 = 2
result = num1 ** num2
print("Exponential",result)

Solution:

Addition 79
Subtraction 221
Multiplication 240
Division 19.666666666666668
Floor Division 3
Exponential 9

Program 2: Write a program to demonstrate the working of python assignment operators.

Solution:

File name: Assignment_demo.py

# simple assignment 

x = 10
y = 20
z = 0

# compound addition assignment

x += 10
print("Compound Addition Assignment", x)

Python Mutable And Immutable Type Examples

Some data types in python are mutable type which means you can make changes to them without changing the data type memory location, which immutable types do not allow changes to existing values in memory. Any change in variable value will be stored in a different location in memory.

Figure 1 - Python Mutable And Immutable Types
Figure 1 – Python Mutable And Immutable Types

Here you will work on examples that demonstrate how mutable and immutable types work in python programming language. We recommend you to try the problem on your own first, then compare the results.

Program 1: Write a program that demonstrates working of immutable types.

Solution:

# Filename : Immutable_types.py
# Write a program that demonstrates working of immutable types

myInteger = 35
print("Before Integer Update",id(myInteger))

#update the integer
myInteger = myInteger + 100

#print the new value and its memory address
print(myInteger)
print("After Integer Update",id(myInteger))


myFloat = 15.45
print("Before Float Update",id(myFloat))

#update the floating number
myFloat = myFloat + 5.42

#print the new value and its memory address
print(myFloat)
print("After Float Update",id(myFloat))


myString = "Hello"
print("Before String Update",id(myString))

#update the string
myString = myString + "Radha"

#print the new value and its memory address
print(myString)
print("After String Update",id(myString))

myComplex = 2 + 5j
myComplexTwo = 4 + 2j

print("Before Complex Update",id(myComplex))

#update the complex numbers 
myComplex = myComplex + myComplexTwo 

#print the new value and its memory address
print(myComplex)
print("After Complex Update",id(myComplex))


myTuple = (34,66,77)
print("Before Tuple Update",id(myTuple))

#update the tuple 
#Tuples cannot be changed , but if you convert a tuple to list then you can update it.
myChangeList = list(myTuple)
myChangeList[1] ="Superman"
myTuple = tuple(myChangeList)

#print the value and the memory address
print(myTuple)
print("After Tuple Update",id(myTuple))

Output:

Before Integer Update 1747543680
135
After Integer Update 1747545280
Before Float Update 43183456
20.869999999999997
After Float Update 42192624
Before String Update 43542976
HelloRadha
After String Update 43617040
Before Complex Update 42811048
(6+7j)
After Complex Update 42056088
Before Tuple Update 42121816
(34, 'Superman', 77)
After Tuple Update 42423680

Program 2: Write a program to demonstrate the working of mutable data types.

Solution:

# Filename : Mutable_type.py
# Write a program to demonstrate the working of mutable data types.

#sets 

mySet = {23, 5, 66}
print("Before Set Update",id(mySet))

#update the sets using function update()
mySet.update("B")

#print the updated value
print(mySet)
print("After Set Update",id(mySet))

#lists

myList = [3, 6, 98, 22]
print("Before List Update",id(myList))

#update list by accessing the individual items
myList[1] = "Krishna"

#print the updated list
print(myList)
print("After List Update",id(myList))

#dictionary

myDictionary = {
              "ID": 234,
              "Name": "Mary",
              "Subject": "Mathematics",
             }

print("Before Dictionary Update",id(myDictionary))

#update the dictionary by accessing individual key
myDictionary.update({"Course":"BSc"})

#print the updated dictionary
print(myDictionary)
print("After Dictionary Update",id(myDictionary))

Output:

Before Set Update 44014208
{66, 5, 'B', 23}
After Set Update 44014208
Before List Update 42321400
[3, 'Krishna', 98, 22]
After List Update 42321400
Before Dictionary Update 43772976
{'ID': 234, 'Name': 'Mary', 'Subject': 'Mathematics', 'Course': 'BSc'}
After Dictionary Update 43772976

Observations: The mutable types do not have a different memory address after the update like the immutable types.

Python Data Types Examples

Data types are fundamental to programming languages and they define the type of values get stored in a python variable. Here you will practice python data types which are similar to other programming languages, yet python don’t have strict type checking like C++, Java, etc. Strict type checking means the you need to declare the type of data before storing value in a variable. For example, int Num; Here ‘int’ means integer type.

Figure 1: Python Data Types

It is recommended that you try these problems on your own and then compare the results. May be you may come up with a better way to solve the problem.

Program 1: Write a program that store number data types , output the type and the data.

Solution:

# Filename : Number_type.py
# write a program that store number types, output the values and type

# number types are - integer, float , complex , and boolean

integer_type = 23
float_type = 344.66
complex_type = 3 + 2j
bool_type1 = True
bool_type2 = False

# Print values and their types

print(integer_type)
print(type(integer_type))

print(float_type)
print(type(float_type))

print(complex_type)
print(type(complex_type))

print(bool_type1)
print(type(bool_type1))

print(bool_type2)
print(type(bool_type2))

Output:

23
<class 'int'>
344.66
<class 'float'>
(3+2j)
<class 'complex'>
True
<class 'bool'>
False
<class 'bool'>

Program 2: Writing a program to store ordered data types such as strings, lists, and tuples and display their value. Also, output their type information.

Solution:

# Filename : ordered_data_type.py
# Writing a program to display values of ordered data type with type information

# python ordered types are string, list, and tuple

myString = "Himalayas"

myList = ["Milk","Banana", "Bread", "Chocolate", 400]

myTuple = (100, "Notesformsc", "ComputerScience")

# print the values and the type 

print(myString)
print(type(myString))

print(myList)
print(type(myList))

print(myTuple)
print(type(myTuple))

Output:

Himalayas
<class 'str'>
['Milk', 'Banana', 'Bread', 'Chocolate', 400]
<class 'list'>
(100, 'Notesformsc', 'ComputerScience')
<class 'tuple'>

Program 3: Write a program to display third letter of the string “MOUNTAIN”.

Solution:

# Filename : Display_letter.py
# Writing a program to display third letter of the string "MOUNTAIN"

myString = "MOUNTAIN"

# index start at 0; therefore, third letter is index is 2

myLetter = myString[2]

# print the output

print("Third letter is",myLetter)

Output:

Third letter is U

Program 4: Write a program in Python to store a None type and display the results with its type information.

Solution:

# Filename : None_type.py
# Write a program that store None type and display the results with its type information.

# the None type store nothing, its not zero, not null, etc

myValue = None

print(myValue)
print(id(myValue))

Output:

None
1786346564

Program 5: Write a program that demonstrate that python sets cannot store duplicate values.

Solution:

# Filename : Sets_duplicate_value.py
# Write a program to demonstrate that python sets cannot store duplicate values.

mySet = {230, 500,100, 500, 670}

print(mySet)
print(type(mySet))

Output:

{100, 670, 500, 230}
<class 'set'>

Program 6: Write a program using dictionary to store records of 5 students and display them as output.

Solution:

# Filename : Student_record_dictionary.py
# Write a program using dictionary to store records of 5 students and display them as output.

firstStudent = {
                 "ID": 35,
                 "Name": "Ram",
                 "Subject":"Math",
                 "Class": 10,
                 }
secondStudent = {
                 "ID": 36,
                 "Name": "Megha",
                 "Subject":"Chem",
                 "Class": 10,
                 }
thirdStudent = {
                 "ID": 37,
                 "Name": "John",
                 "Subject":"Hist",
                 "Class": 11,
                 }
fourthStudent = {
                 "ID": 38,
                 "Name": "Lee",
                 "Subject":"Engl",
                 "Class": 12,
                 }
fifthStudent = {
                 "ID": 39,
                 "Name": "Geeta",
                 "Subject":"Math",
                 "Class": 12,
                 }
# Display student data 

print("ID","Name","Section","Class")
print(firstStudent["ID"],firstStudent["Name"],firstStudent["Subject"],firstStudent["Class"])
print(secondStudent["ID"],secondStudent["Name"],secondStudent["Subject"],secondStudent["Class"])
print(thirdStudent["ID"],thirdStudent["Name"],thirdStudent["Subject"],thirdStudent["Class"])
print(fourthStudent["ID"],fourthStudent["Name"],fourthStudent["Subject"],fourthStudent["Class"])
print(fifthStudent["ID"],fifthStudent["Name"],fifthStudent["Subject"],fifthStudent["Class"])

Output:

ID Name Section Class
35 Ram Math 10
36 Megha Chem 10
37 John Hist 11
38 Lee Engl 12
39 Geeta Math 12

Python Examples

Python is a high level language and you as a learner must practice a lot to master this programming language. Here we provide you examples to practice with solutions.

You must install the python 3x compiler suitable for your computer and practice programming as you learn python. To learn the python language visit our Python tutorial page.

Prerequisites

There are few prerequisites before you start practicing the examples,

  • You must install a Python 3.x.x compiler on you computer. Make sure there are no error while working with the compiler.
  • Keep a note book or use computer notepad to manually work out the problem before writing the programs.
  • Keep a separate folder to keep your programs so that you can work on them later.

Python Example Programs

The python examples are organized based on programming concepts. If you are learning a particular concept, you can check you understanding by working through these examples.

Python Variable Examples

This post contains python variable examples. You can start with first example and work your way through rest of the programs. For each program the solution is provided after the source code.

You must try to write the program yourself and compare the results later.

Program 1: Write a program to display the value of variables

Solution:

# filename: greetings.py 
# program to display values of variables

greeting = "Happy Diwali"
print(greeting)

memberID = 343
print("MemberID is",memberID)

Output:

Happy Diwali
MemberID is 343

Program 2: Writing a program to find the area of a rectangle where length of the rectangle is 120 units and breadth is 40 units.

Solution:

# filename : rectangle_area.py
# write a program to find the area of a rectangle with length = 120 units and breadth = 40 units.

length = 120
breadth = 40
area_rectangle = length * breadth
print("Area =",area_rectangle)

Output:

Area= 4800

Program 3: Write a program to display total marks in 3 subjects – Math, English, and Science and include comments to explain your code.

Solution:

# filename : total_marks.py
# write a program to display total marks in 3 subjects - Math, English, and Science and include comments to explain your code.

# marks in three subjects for a student
Math = 77
English = 100
Science = 233

# compute total marks by adding all subject marks

Total_Marks = 77 + 100 + 233

# print total marks 

print("Total Marks","=",Total_Marks)

Output:

Total Marks = 410

Program 4: Python treat every value as an object by assigning a unique ID number. Write a program using function “id()” to display the object unique id.

Solution:

# filename : find_object_id.py
# Write a program to display object unique id using function id()

num = 30
print(id(num))

name = "Ram"
print(id(name))

Output:

1802659376
43805184

Python Strings

Python string is a data structure that holds list or a string of characters. These characters could be

  1. a single letter
  2. a number
  3. symbol
  4. or special character

Unicode

The letters are both lowercase and uppercase which we human can understand. The capital 'A' for us is same as lowercase 'a'

The Unicode is a universal IT standard that use hexadecimal letters to represent a single character.

Therefore, we can represent 'A' in Unicode.

\u0041  # represent Unicode A
\u0061  # represent Unicode a

Note that the hexadecimal is a number system to represent decimal numbers using 0 to 9 and A to F. The A to F stands for 10 to 15. Therefore, to total character in hexadecimal is between 0 to 15.

Special Characters

There are characters that does not have symbols. For example, line feed(LF) or carriage return (CR).

The computer start writing or reading from a new line of the text upon receiving these characters.The computer use Unicode characters for these special characters.

There are many special characters in a normal Qwerty keyboard. Here is a list of common characters used in python programming language.

CharacterName
\\backslash
\’single quote
\”double quote
\bbackspace
\fform feed(FF)
\nline feed(LF)
\rcarriage return(CR)
\tsingle TAB space
Special characters in python

The rest of the string related topic is discussed in future articles.

Python Built-in Methods

Earlier you learned about functions and built-in functions. One of the built-in function is print() function. In this article, you will learn about python built-in methods.

There are two types of methods in python. One that comes from python modules and built-in methods. The python module will have function definition which you can use after importing the module into the program.

Built-in Methods

For built-in methods, there is no need to import any module. The built-in methods are associated with python data types, because the data types themselves are objects.

For example, let us consider isdigit() method. The isdigit() method is part of string type. Use the .(dot) notation to access any method.

# declare a string
myString = "13445"
myString_2 = "Hello"
# check if the strings contains any digits
result = myString.isdigit()
# print result
print(result)
result = myString_2.isdigit()
# print result 
print(result)

The isdigit() method checks the string object and look for any non-digit character. If it finds one, then returns False.If each character is a digit, then, it will return True. The output of the above program is given below.

True
False

Consider another method associated with list object.

# create a list
myDrink = ["tea","coffee","milk"]
# append the list
myDrink.append("juice")
# print the updated list
print(myDrink)

In the above example, we have created a new list of beverages. We are using .append method to update the list. Therefore, different types of data types have different types of methods. Some return an integer, Boolean value, and some update the values.

Functions vs. Methods

As we mentioned earlier, that the function is declared above the of program and called to do some tasks. The method is function that is associated to a data type.

For method, you need to use the dot(.) notation to access it.

Can we replace the built-in method with a function ?

The answer is Yes.

Let us consider another example where we replace the isdigit() method with isDigit() function.

import string 
def isDigit(myStr):
    for character in myStr:
           if not character in string.digits:
                   return False
    return True
myStr = "32455"
print(isDigit(myStr))
print(myStr.isdigit())

In the above program, both isDigit() and isdigit() are same.

True
True

Only difference is that the isDigit() needs argument string, and isdigit() is from the string class where argument comes from the object of that string class.

Python Mutable vs. Non-Mutable Data Types

In this article, you will learn about python mutable vs. non-mutable date type and how they affect passing of arguments to the function.

In the previous article, you learned about passing arguments by reference and passing arguments using values. The choice of passing arguments depends on the data type.

Mutability is the ability of variable to change its value after being declared. A mutable variable can change its value after being declared. The data type of mutable give this ability.

An immutable variable is that which cannot change its value after being declared. The data type of such variable does permit mutability. Python basic data types are mostly immutable types.

Variable Declaration

A variable declaration is the process of assigning a value to the variable. This process reserves a memory location for the variable to store its data.

For example.

myInt  = 44
print(id(myInt))
myList = ["Apple","Orange","Grapes"]
print(id(myList))

The code above will create two memory location and store its values. The first value is an integer and second one is a list type.

The program uses id() function to display the memory addresses of the variables. Output is given below.

140713857296112
321864522440

Now, if we try to change the value of integer which is a mutable variable because of integer type. It won’t update the existing variable, but create a new variable at a new memory location.

myInt = 44
print("Before: ",id(myInt))
myInt = myInt + 10
print("After: ",id(myInt))

The result of myInt = myInt + 10 is stored in new location. Here is the output.

Before:  140713857296112
After:  140713857296432

This is because integer is immutable type.

Python Immutable Type

Consider same example with a string.

myString = "mycar"
print(myString)
print("Before: ",id(myString))
print(myString.upper())
print("After: ",id(myString))

In the example above, the program changes the original text lowercase letters to uppercase letters using python upper() function.

After changing the string to uppercase, it does not change the value or memory address of the original text.This is because python string type is also immutable. Here is the output.

mycar
Before:  321865256432
MYCAR
After:  321865256432

Immutable Type with Function

An immutable variable when passed as parameter will act list it is passed by value because it will not change the original value passed variable.

Passed by Value means variable is immutable.
Passed by Value means variable is immutable.

Python Mutable Type

There are newer data types in python that allows to change the original variable data.

myList = ["Apple","Orange","Grapes"]
print(id(myList))

The above is a list data type which is mutable. That means you can change it without re-declaring it in a new location.

myList = ["Apple","Orange","Grapes"]
# printing the memory address of the list
print(myList)
print(id(myList))
# adding banana to the list 
myList.append("Banana")
# print the memory address of the updated list
print(myList)
print(id(myList))

Once we run the program, the program adds a new item to the list. We also print the original list with the updated list.

Here output is given below.

['Apple', 'Orange', 'Grapes']
321864522760
['Apple', 'Orange', 'Grapes', 'Banana']
321864522760

The list is updated and the new item appears in the list. However, you note that the memory address of the myList has not changed. That is because the list data type is mutable.

Mutable Variable and Function

A mutable variable when passed as parameter to the function will compute and change the original value of the variable. It works similar to passing by reference to a function.

Passing by reference changes original value because it is mutable
Passing by reference changes original value because it is mutable

Re-Declaration

Whenever we re-declare a mutable variable, it will be created in a new location. However, immutable variable is value based, therefore, when you create a new variable and assign it some value. If the value is already available in the memory. Python assign that value to new variable.

Suppose myInt has a value of 23 stored at 74384844. If you re-declare myInt than it is going to point to same memory location 74384844 where 23 is available.

See the example below.

print("Before")
myInt = 23 
myStr = "Hello"
myList = [1, 3 , 6, 9]
print(id(myInt))
print(id(myStr))
print(id(myList))
# re-declare the variable with same value
print("After")
myInt = 23 
myStr = "Hello"
myList = [1, 3 , 6, 9]
print(id(myInt))
print(id(myStr))
print(id(myList))

The output of the program is given below.

Before
140713857295440
321852102896
321864540808
After
140713857295440
321852102896
321852148936

The value of immutable type is does not change memory location because it is assigning the available value 23 and “Hello” in the memory. The value of mutable variable myList changes due to re-declaration.

Python Nested Try-Catch

In earlier lessons, you learned about try-catch-else-finally blocks. In this article, you will learn that we can put a try-catch block inside another try-catch block. Therefore, there can be more than one level of python nested try-catch blocks.

Understanding Nested Try-Catch

Each of these try-catch will handle different exceptions. Earlier we have seen exceptions at the same level. But, the objective of python nested try-catch is to find errors at different levels of code. See the figure below to understand how it works.

Python Nested Try-Catch-Else-Finally
Python Nested Try-Catch-Else-Finally

The program first checks the outer try-catch block and if there is no exception, continues with the inner try-catch block.

The inner try-catch block run independently and any exception or error is handled using inner catch block and all other blocks are executed sequentially.

Note that nested try block will not execute if outer try-catch has an error.

Example #1 : Python Nested Try-Catch

In this example, we will receive amount, rate, and year as inputs and compute simple interest and total amount.

The user will enter the value and we want to make sure that there is no Type Error. Therefore, we will get the correct input.

Only after we receive correct input we must do compute the simple interest.

# check the correct input 
try:
   amount = int(input("Enter the amount: "))
   rate = float(input("Enter rate in decimal, eg 0.12: "))
   year = int(input("Enter number of Years: "))
   simple_interest = 0.0
   total = 0.0
   # compute the simple interest 
   try:
      simple_interest = amount * rate * year
      total = amount + simple_interest 
      print("Simple Interest = ", simple_interest)
      print("Total amount", total)
   except Exception as err:
      print(err)
   else:
      print("Successfully Computed SI")
   finally:
      print("Completed!")
except ValueError as err:
   print("Wrong type! try again later")

In the above program, we check input types and if the input types are not correct there will be an error and the exception is caught.

For example, user input 15000.42 as amount which is a float value, however, the program is expecting an integer input. Therefore, it will cause a Value Error.

Enter the amount: 15000.42
Wrong type! try again later
>>> 

If the user put all values correctly, then the nested try-catch will be executed.

The output of the above is given below.

Enter the amount: 15000
Enter rate in decimal, eg 0.12: 0.9
Enter number of Years: 5
Simple Interest =  67500.0
Total amount 82500.0
Successfully Computed SI
Completed!
>>> 

Note that all the other blocks such as else and finally also executed from the nested try-catch.

Example #2: Python Nested Try-Catch

Here we take a real world example, of file handling. Whenever, you try to manipulate a file. The first try-catch block will try to catch any file opening exceptions. Only after that file is opened successfully, nested try-catch is executed and catch other errors.

First step is to create a file named testFile.txt and put some 4 or 5 lines of information.

Save the file in the same directory as the above program. Suppose the program name is file_m.py, then you must put testFile.txt in the same directory as file_m.py.

Here is the code for the file_m.py.

# File Exception Handling with Nested Try-Catch
try:
    file = open("testFile.txt","r")

    # print all file information to console
    try:
        for line in file:
            print(line)
    except Exception as error:
        print(error)
    else:
        print("Success")
    finally:
        file.close
        print("File closed")          
except (FileNotFoundError, PermissionError) as error:
    print(error)
    

The program above checks if there is a FileNotFoundError or a PermissionError happens. If file exists and there is no permission error. For example, suppose the file does not exist. Then you should receive error given below.

/File_Exception_Handling_With_Nested_try.py
[Errno 2] No such file or directory: 'test.txt'
>>> 

The output of the above program is given below.

Orange

Mango

Banana

Grapes
Success
File closed
>>> 

The nested try block will continue to manipulate the file and print contents of the file to the console. In the next article, we will discuss how exception handling is done with loops and control structures.