You are on page 1of 18

1 What are mutable and immutable types?

Mutable is a fancy way of saying that the internal state of the object is changed/mutated. So, the simplest
definition is: An object whose internal state can be changed is mutable. On the other hand, immutable doesn’t
allow any change in the object once it has been created.
Mutable Definition
Mutable is when something is changeable or has the ability to change. In Python, ‘mutable’ is the ability
of objects to change their values. These are often the objects that store a collection of data.
Immutable Definition
Immutable is the when no change is possible over time. In Python, if the value of an object cannot be
changed over time, then it is known as immutable. Once created, the value of these objects is permanent.
List of Mutable and Immutable objects
Objects of built-in type that are mutable are:
 Lists
 Sets
 Dictionaries
 User-Defined Classes (It purely depends upon the user to define the characteristics) 
Objects of built-in type that are immutable are:
 Numbers (Integer, Rational, Float, Decimal, Complex & Booleans)
 Strings
 Tuples
 Frozen Sets
 User-Defined Classes (It purely depends upon the user to define the characteristics)
Object mutability is one of the characteristics that makes Python a dynamically typed language. Though
Mutable and Immutable in Python is a very basic concept, it can at times be a little confusing due to the
intransitive nature of immutability.

2 What is cloning of List?


If user want to modify a list and also keep a copy of the original, we need to be able to make a copy of the
list itself, not just the reference. This process is sometimes called cloning, to avoid the ambiguity of the word
copy.
To actually copy the list, you have various possibilities:
 use the builtin list.copy() method: new_list = old_list.copy()
 can slice it: new_list = old_list[:]
 use the built in list() function: new_list = list(old_list)

3 How to access values in a dictionary?


To access dictionary elements, you can use the familiar square brackets along with the key to obtain its
value. Following is a simple example −
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print "dict['Name']: ", dict['Name']
print "dict['Age']: ", dict['Age']
When the above code is executed, it produces the following result −
dict['Name']: Zara
dict['Age']: 7
If we attempt to access a data item with a key, which is not part of the dictionary, we get an error as
follows −
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print "dict['Alice']: ", dict['Alice']
When the above code is executed, it produces the following result −
dict['Alice']:
Traceback (most recent call last):
File "test.py", line 4, in <module>
print "dict['Alice']: ", dict['Alice'];
KeyError: 'A
4 How do you get command line arguments in Python?
Python provides a getopt module that helps you parse command-line options and arguments.
>>> python test.py arg1 arg2 arg3
The Python sys module provides access to any command-line arguments via the sys.argv. This serves
two purposes −
 sys.argv is the list of command-line arguments.
 len(sys.argv) is the number of command-line arguments.
Here sys.argv[0] is the program ie. script name.
Example
Consider the following script test.py −
import sys
print 'Number of arguments:', len(sys.argv), 'arguments.'
print 'Argument List:', str(sys.argv)
Now run above script as follows −
>>> python test.py arg1 arg2 arg3
This produce following result −
Number of arguments: 4 arguments.
Argument List: ['test.py', 'arg1', 'arg2', 'arg3

5 Explain user defined exceptions with examples


Python 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 the exception as follows −
try:
raise Networkerror("Bad hostname")
except Networkerror,e:
print e.args

6a Explain the different string formats available in Python with examples.


Strings are amongst the most popular types in Python. We can create them simply by enclosing characters in
quotes. Python treats single quotes the same as double quotes. Creating strings is as simple as assigning a value
to a variable. For example −
var1 = 'Hello World!'
var2 = "Python Programming"
Accessing Values in Strings
Python does not support a character type; these are treated as strings of length one, thus also considered a
substring.
To access substrings, use the square brackets for slicing along with the index or indices to obtain your substring.
For example −
var1 = 'Hello World!'
var2 = "Python Programming"

print "var1[0]: ", var1[0]


print "var2[1:5]: ", var2[1:5]
When the above code is executed, it produces the following result −
var1[0]: H
var2[1:5]: ytho
Triple Quotes
Python's triple quotes comes to the rescue by allowing strings to span multiple lines, including verbatim
NEWLINEs, TABs, and any other special characters.
The syntax for triple quotes consists of three consecutive single or double quotes.
String Formatting Operator
One of Python's coolest features is the string format operator %. This operator is unique to strings and
makes up for the pack of having functions from C's printf() family. Following is a simple example −
print "My name is %s and weight is %d kg!" % ('Zara', 21)
When the above code is executed, it produces the following result −
My name is Zara and weight is 21 kg!
Here is the list of complete set of symbols which can be used along with % −
Format Symbol Conversion

%c character

%s string conversion via str() prior to formatting

%i signed decimal integer

%d signed decimal integer

%u unsigned decimal integer

%o octal integer

%x hexadecimal integer (lowercase letters)

%X hexadecimal integer (UPPERcase letters)

%e exponential notation (with lowercase 'e')

%E exponential notation (with UPPERcase 'E')

%f floating point real number

%g the shorter of %f and %e

%G the shorter of %f and %E


6b What is list? Explain the concept of slicing and indexing with proper examples.
The list is a most versatile datatype available in Python which can be written as a list of comma-separated
values (items) between square brackets. Important thing about a list is that items in a list need not be of the same
type.
Creating a list is as simple as putting different comma-separated values between square brackets.
For example −
list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5 ];
list3 = ["a", "b", "c", "d"]
Similar to string indices, list indices start at 0, and lists can be sliced, concatenated and so on.
Slicing in Python list
Lets see slicing in python list.
In this example, we have used “(my_list[-4::1])” for slicing in the list. So, the start is “-4” and we have
not specified any value for the end so, by default it will take till last and “1” is step.
Example:
my_list = [10, 20, 30, 40, 50, 60]
print(my_list[-4::1])
In this output, we can see slicing in the python list. Here, we get the list in the output. You can refer to the below
screenshot.

Python List indexing 


Python List indexing can be done by accessing the list value by referring to its index number. Here, we
have used “(list[2])” and it returns “Horse”.
Example:
list = ['Dog', 'Cat', 'Horse', 'Bear']
print(list[2])
In this output, we can see indexing in python list. You can refer to the below screenshot.

7a Explain any 5 string functions with example.


1. format() Method
It’s used to create a formatted string from the template string and the supplied values.
Example
Insert the price inside the placeholder, the price should be in fixed point, two-decimal format:
txt = "For only {price:.2f} dollars!"
print(txt.format(price = 49))
Definition and Usage
The format() method formats the specified value(s) and insert them inside the string's placeholder.
The placeholder is defined using curly brackets: {}. Read more about the placeholders in the Placeholder
section below.
The format() method returns the formatted string.
Syntax
string.format(value1, value2...)
Parameter Values
Parameter Description
value1, value2... Required. One or more values that should be formatted and inserted in the string.
The values are either a list of values separated by commas, a key=value list, or a
combination of both.
The values can be of any data type.

2. upper()method
Python string method upper() returns a copy of the string in which all case-based characters have been
uppercased.
Syntax
Following is the syntax for upper() method −
str.upper()
Parameters
NA
Return Value
This method returns a copy of the string in which all case-based characters have been uppercased.
Example
The following example shows the usage of upper() method.
str = "this is string example....wow!!!";
print "str.capitalize() : ", str.upper()
When we run above program, it produces following result −
str.capitalize() : THIS IS STRING EXAMPLE....WOW!!!
3. lower() Method
Python string method lower() returns a copy of the string in which all case-based characters have been
lowercased.
Syntax
Following is the syntax for lower() method −
str.lower()
Parameters
 NA
Return Value
This method returns a copy of the string in which all case-based characters have been lowercased.
Example
The following example shows the usage of lower() method.
str = "THIS IS STRING EXAMPLE....WOW!!!";
print str.lower()
When we run above program, it produces following result –
this is string example....wow!!!

4. replace() method
Python string method replace() returns a copy of the string in which the occurrences of old have been
replaced with new, optionally restricting the number of replacements to max.
Syntax
Following is the syntax for replace() method −
str.replace(old, new[, max])
Parameters
old − This is old substring to be replaced.
new − This is new substring, which would replace old substring.
max − If this optional argument max is given, only the first count occurrences are replaced.
Return Value
This method returns a copy of the string with all occurrences of substring old replaced by new. If the
optional argument max is given, only the first count occurrences are replaced.
Example
The following example shows the usage of replace() method.
str = "this is string example....wow!!! this is really string"
print str.replace("is", "was")
print str.replace("is", "was", 3)
When we run above program, it produces following result −
thwas was string example....wow!!! thwas was really string
thwas was string example....wow!!! thwas is really string

5. find() method
Python string method find() determines if string str occurs in string, or in a substring of string if starting
index beg and ending index end are given.

Syntax
str.find(str, beg=0, end=len(string))
Parameters
str − This specifies the string to be searched.
beg − This is the starting index, by default its 0.
end − This is the ending index, by default its equal to the length of the string.

Return Value
Index if found and -1 otherwise.
Example
str1 = "this is string example....wow!!!";
str2 = "exam";
print str1.find(str2)
print str1.find(str2, 10)
print str1.find(str2, 40)
Result
15
15
-1

6. translate() method
Python string method translate() returns a copy of the string in which all characters have been translated
using table (constructed with the maketrans() function in the string module), optionally deleting all characters
found in the string deletechars.

Syntax
Following is the syntax for translate() method −
str.translate(table[, deletechars]);
Parameters
table − You can use the maketrans() helper function in the string module to create a translation table.
deletechars − The list of characters to be removed from the source string.
Return Value
This method returns a translated copy of the string.
Example
The following example shows the usage of translate() method. Under this every vowel in a string is
replaced by its vowel position −
from string import maketrans # Required to call maketrans function.
intab = "aeiou"
outtab = "12345"
trantab = maketrans(intab, outtab)
str = "this is string example....wow!!!";
print str.translate(trantab)
When we run above program, it produces following result −
th3s 3s str3ng 2x1mpl2....w4w!!!
Following is the example to delete 'x' and 'm' characters from the string −
from string import maketrans # Required to call maketrans function.
intab = "aeiou"
outtab = "12345"
trantab = maketrans(intab, outtab)
str = "this is string example....wow!!!";
print str.translate(trantab, 'xm')
This will produce following result −
th3s 3s str3ng 21pl2....w4w!!!

7b Compare List and Tuple


List and Tuple in Python are the class of data structure. The list is dynamic, whereas the tuple
has static characteristics. 
List is just like the arrays, declared in other languages. Lists need not be homogeneous always which
makes it the most powerful tool in Python. In Python, the list is a type of container in Data Structures,
which is used to store multiple data at the same time. Lists are a useful tool for preserving a sequence
of data and further iterating over it. 
Syntax:  list_data = ['an', 'example', 'of', 'a', 'list']
Tuple is also a sequence data type that can contain elements of different data types, but these are
immutable in nature. In other words, a tuple is a collection of Python objects separated by commas.
The tuple is faster than the list because of static in nature. 
Syntax:   tuple_data = ('this', 'is', 'an', 'example', 'of', 'tuple')
Difference Between List and Tuple in Python:    
S.NO
. LIST TUPLE

1 Lists are mutable Tuples are immutable

Implication of iterations is Time-


2 consuming The implication of iterations is comparatively Faster

The list is better for performing


operations, such as insertion and Tuple data type is appropriate for accessing the
3 deletion. elements

4 Lists consume more memory Tuple consume less memory as compared to the list

Lists have several built-in


5 methods Tuple does not have many built-in methods.

The unexpected changes and


6 errors are more likely to occur In tuple, it is hard to take place.

8a Describe the different access modes of the files with an example


Python too supports file handling and allows users to handle files i.e., to read and write files,
along with many other file handling options, to operate on files. Each line of code includes a
sequence of characters and they form text file. Each line of a file is terminated with a special
character, called the EOL or End of Line characters like comma {,} or newline character. It ends the
current line and tells the interpreter a new one has begun. Let’s start with Reading and Writing files.
Working of open() function
We use open () function in Python to open a file in read or write mode. As explained above,
open ( ) will return a file object. To return a file object we use  open() function along with two
arguments, that accepts file name and the mode, whether to read or write. So, the syntax
being: open(filename, mode). There are three kinds of mode, that Python provides and how files can
be opened:
 “ r “, for reading.
 “ w “, for writing.
 “ a “, for appending.
 “ r+ “, for both reading and writing
One must keep in mind that the mode argument is not mandatory. If not passed, then Python
will assume it to be “ r ” by default. Let’s look at this program and try to analyze how the read mode
works:
# a file named "geek", will be opened with the reading mode.
file = open('geek.txt', 'r')
# This will print every line one by one in the file
for each in file:
    print (each)
The open command will open the file in the read mode and the for loop will print each line
present in the file.
Working of read() mode
There is more than one way to read a file in Python. If you need to extract a string that
contains all characters in the file then we can use file.read(). The full code would work like this:
# Python code to illustrate read() mode
file = open("file.text", "r") 
print (file.read())
Another way to read a file is to call a certain number of characters like in the following code
the interpreter will read the first five characters of stored data and return it as a string:
# Python code to illustrate read() mode character wise
file = open("file.txt", "r")
print (file.read(5))
Creating a file using write() mode
Let’s see how to create a file and how write mode works: To manipulate the file, write the
following in your Python environment:
# Python code to create a file
file = open('geek.txt','w')
file.write("This is the write command")
file.write("It allows us to write in a particular file")
file.close()
The close() command terminates all the resources in use and frees the system of this particular
program.
Working of append() mode
Let’s see how the append mode works:
# Python code to illustrate append() mode
file = open('geek.txt','a')
file.write("This will add this line")
file.close()
There are also various other commands in file handling that is used to handle various tasks
like:
rstrip(): This function strips each line of a file off spaces from the right-hand side.
lstrip(): This function strips each line of a file off spaces from the left-hand side.
It is designed to provide much cleaner syntax and exceptions handling when you are
working with code. That explains why it’s good practice to use them with a statement where
applicable. This is helpful because using this method any files opened will be closed automatically
after one is done, so auto-cleanup.
Example:
# Python code to illustrate with()
with open("file.txt") as file:  
    data = file.read() 
# do something with data 
Using write along with with() function
We can also use write function along with with() function:
# Python code to illustrate with() alongwith write()
with open("file.txt", "w") as f: 
    f.write("Hello World!!!") 
split() using file handling
We can also split lines using file handling in Python. This splits the variable when space is
encountered. You can also split using any characters as we wish. Here is the code:
# Python code to illustrate split() function
with open("file.text", "r") as file:
    data = file.readlines()
    for line in data:
        word = line.split()
        print (word)

8b Explain the features of a dictionary


The Python dictionary makes it easier to read and change data, thereby rendering it more actionable for
predictive modeling. A Python dictionary is an unordered collection of data values. Unlike other data types that
hold only one value as an element, a Python dictionary holds a key: value pair.
Dictionaries in Python are a list of items that are unordered and can be changed by use of built in
methods. Dictionaries are used to create a map of unique keys to values.
Writing out Python dictionary keys along with values adds a layer of documentation to the code. If the
code is more streamlined, it is a lot easier to debug. There are 4 must-know features of Python dictionaries. They
are essential for using dictionaries efficiently and appropriately.
 Dictionaries are unordered
 Keys are unique
 Keys must be immutable
 Dictionary comprehension.
1. Dictionaries are unordered
A dictionary contains key-value pairs but does not possess an order for the pairs. Thus, a more precise
definition is that a dictionary is an unordered collection of key-value pairs.
As a result, we cannot perform typical operations associated with the order of items. For instance, it is not
possible to get the first or last item in a dictionary.
Another common operation done with numeric indices is slicing. It can be performed on a Python list:
mylist = ["John", "Jane", "Emily"]print(mylist[0])
Johnprint(mylist[1:])
['Jane', 'Emily']
Unlike lists, dictionaries are indexed by keys. Thus, it is not possible to do these operations on
dictionaries due to not having an order. We can access a value by passing its key in square brackets or the get
method.
members = {1001: "John", 1002: "Jane", 1003: "Emily"}members[1001]
'John'members.get(1001)
'John'
It is important to note that lacking an order is not a deficiency of Python dictionaries. In fact, it can be
considered as a strength. They allow for quickly accessing and retrieving information associated with a particular
key.
2. Keys are unique
Dictionary keys must be unique. It makes sense because we use them for accessing values. Having
duplicated keys defeats the purpose of using a dictionary to store information.
Although a dictionary does not allow for creating duplicated keys, it does not warn you if you use the
same key multiple times. Thus, you need to be extra careful not to cause any unexpected behavior.
Let’s go over a few examples to make it more clear.
members = {1001: "John", 1002: "Jane", 1003: "Emily", 1001: "Max"}
print(members)
{1001: 'Max', 1002: 'Jane', 1003: 'Emily'}
We use the same key (1001) twice but does not get any error. Instead, Python overwrites the previous
value with the new one.
The same behavior is observed when updating a dictionary. We can add a new item to a dictionary as
below:
members[1004] = "Ashley"print(members)
{1001: 'Max', 1002: 'Jane', 1003: 'Emily', 1004: 'Ashley'}
The key 1004 was not in the members dictionary so it is added with the given value. If we use the same
method and pass a key that is already in the dictionary, its value is updated.
members[1001] = "AAAAA"print(members)
{1001: 'AAAAA', 1002: 'Jane', 1003: 'Emily', 1004: 'Ashley'}
Thus, it is more like updating the value of a key rather than creating a new key-value pair.
3. Keys must be immutable
Dictionary keys must be of an immutable type. Strings and numbers are the two most commonly used
data types as dictionary keys. We can also use tuples as keys but they must contain only strings, integers, or other
tuples.
We have already created a dictionary with integer keys. Let’s create a couple of more with string and
tuple keys.
# string keys
dict_a = {"Param1": "value1", "Param2": "value2"}
print(dict_a)
{'Param1': 'value1', 'Param2': 'value2'}
# tuple keys
dict_b = {(1, 10): "value1", (1,20): "value2"}
print(dict_b)
{(1, 10): 'value1', (1, 20): 'value2'}
If we try to create a key of a mutable (i.e. unhashable) type, a type error is
raised.
dict_c = {[1, 2] : "value1", [1,4]: "value2"}
TypeError: unhashable type: 'list'dict_d = {(1, [1,2]): "value1"}
TypeError: unhashable type: 'list'
4. Dictionary comprehension
There are several methods to create a dictionary in Python. One method is writing key-value pairs in
curly braces like we have done up to this point.
Another option is the dict constructor which creates a dictionary from a sequence of key-value pairs.
sequence = [[1, "John"], [2, "Jane"]]dict(sequence)
{1: 'John', 2: 'Jane'}
Dictionary comprehension is similar to the concept of list comprehension. It is more practical way of
creating dictionaries that contain a structured set of values.
Consider we have the following text.
text = "By 1908, Einstein was recognized as a leading scientist and was appointed lecturer at the University
of Bern"
We want to get an overview of the length of the words in this text. We can create a dictionary that
contains both the words and their lengths. Dictionary comprehension accomplishes this task simply as follows:
dict_a = {x: len(x) for x in text.split(" ")}
We split the text at the space characters and use each word as a key. The values are calculated calling the
built-in len function on the words.
It is worth emphasizing that we do not get any information as to the number of occurrences of the words
in the text. The dictionary consists of unique words

9a What are template engines in python and Mention its types.


Template engines take in tokenized strings and produce rendered strings with values in place of the tokens as
output. Templates are typically used as an intermediate format written by developers to programmatically
produce one or more desired output formats, commonly HTML, XML or PDF.
Template engines allow developers to generate desired content types, such as HTML, while using some of the
data and programming constructs such as conditionals and for loops to manipulate the output. Template files that
are created by developers and then processed by the template engine consist of prewritten markup and template
tag blocks where data is inserted.
There are many, many different HTML/XML templating packages and modules for Python that provide
different feature sets and syntaxes. These libraries usually assume that you know how to write HTML or XML.
A rough visual of the code in template spectrum can be seen below for four of the major Python template engines.

Jinja (Jinja2), Django templating, Mako template engine.

There are numerous Python template engine implementations that range from weekend hacks to
actively developed mature libraries. These template engines are listed alphabetically:
Chameleon is an HTML and XML template engine that supports both Python 2 and 3.
Cheetah
Diazo
evoque
Genshi
Juno
Myghty
pyratemp
pystache

9b Write a program to sort a list using bubble sort


a = []
number = int(input("Please Enter the Total Number of Elements : "))
for i in range(number):
value = int(input("Please enter the %d Element of List1 : " %i))
a.append(value)

for i in range(number -1):


for j in range(number - i - 1):
if(a[j] > a[j + 1]):
temp = a[j]
a[j] = a[j + 1]
a[j + 1] = temp

print("The Sorted List in Ascending Order : ", a)

10 a Explain about methods in Lists of Python with appropriate examples.

Python has a set of built-in methods that you can use on lists
append() : Adds an element at the end of the list
clear() : Removes all the elements from the list
copy() : Returns a copy of the list
count() : Returns the number of elements with the specified value
extend() : Add the elements of a list (or any iterable), to the end of the current list
index() : Returns the index of the first element with the specified value
insert() : Adds an element at the specified position
pop() : Removes the element at the specified position
remove() : Removes the first item with the specified value
reverse() : Reverses the order of the list
sort() : Sorts the list

10 b Write a program to implement linear search on lists.


# python program for linear search using for loop

#define list
lst = []

#take input list size


num = int(input("Enter size of list :- "))

for n in range(num):
#append element in list/array
numbers = int(input("Enter the array of %d element :- " %n))
lst.append(numbers)

#take input number to be find in list


x = int(input("Enter number to search in list :- "))

i=0
flag = False

for i in range(len(lst)):
if lst[i] == x:
flag = True
break

if flag == 1:
print('{} was found at index {}.'.format(x, i))
else:
print('{} was not found.'.format(x))

output:
After executing the program, the output will be:
Enter size of list :- 6
Enter the array of 0 element :- 25
Enter the array of 1 element :- 50
Enter the array of 2 element :- 100
Enter the array of 3 element :- 200
Enter the array of 4 element :- 250
Enter the array of 5 element :- 650
Enter number to search in list :- 200
200 was found at index 3.

11 a What is Dictionary? Explain Python dictionaries in detail discussing its operations and methods.
Dictionary operations

Dictionaries are Python’s implementation of a data structure that is more generally known as an
associative array. A dictionary consists of a collection of key-value pairs. Each key-value pair maps the
key to its associated value.

You can define a dictionary by enclosing a comma-separated list of key-value pairs in curly
braces ({}). A colon (:) separates each key from its associated value:

1. Definition operations
These operations allow us to define or create a dictionary.
{}

Creates an empty dictionary or a dictionary with some initial values.


y = {}
x = {1: "one", 2: "two", 3: "three"}

2. Mutable operations
These operations allow us to work with dictionaries, but altering or modifying their previous definition.

[]
Adds a new pair of key and value to the dictionary, but in case that the key already exists in the
dictionary, we can update the value.
y = {}
y['one'] = 1
y['two'] = 2
print(y)

Output:
{'one': 1, 'two': 2}

y['two'] = 'dos'
print(y)
Output:
{'one': 1, 'two': 'dos'}

As I told you before, the key value should be an immutable data type, for that reason if you try to define a
dictionary with a mutable data type, Python will raise a TypeError: unhashable type exception.

del
Del statement can be used to remove an entry (key-value pair) from a dictionary.
y = {'one': 1, 'two': 2}
print(y)

Output:
{'one': 1, 'two': 2}
del y['two']
print(y)

Output:
{'one': 1}

update
This method updates a first dictionary with all the key-value pairs of a second dictionary. Keys
that are common to both dictionaries, the values from the second dictionary override those of the first.
x = {'one': 0, 'two': 2}
y = {'one': 1, 'three': 3}
x.update(y)
print(x)

Output:
{'one': 1, 'two': 2, 'three': 3}

3. Immutable operations
These operations allow us to work with dictionaries without altering or modifying their previous
definition.

len
Returns the number of entries (key-value pairs) in a dictionary.
x = {'one': 0, 'two': 2}
print(len(x))

Output:
2

keys
This method allows you to get all the keys in the dictionary. It is often used in a “for loop” to
iterate over the content of a dictionary.
x = {'one': 1, 'two': 2}
print(x.keys())
Output:
dict_keys(['one', 'two'])

values
This method allows you to obtain all the values stored in a dictionary.
x = {'one': 1, 'two': 2}
print(x.values())

Output:
dict_values([1, 2])

items
Returns all the keys and their associated values as a sequence of tuples.
x = {'one': 1, 'two': 2}
print(x.items())
Output:
dict_items([('one', 1), ('two', 2)])

in
Attempting to access a key that is not in a dictionary will raise an exception. To handle this
exception, you can use the in method that test whether a key exists in a dictionary, returns True if a
dictionary has a value stored under the given key and False otherwise.
y = {'one': 1, 'two': 2}
del y['three']

Output:
KeyError: 'three'y = {'one': 1, 'two': 2}

if 'three' in y:
del y['three']
print(y)

Output:
{'one': 1, 'two': 2}

get
Returns the value associated with a key if the dictionary contains that key, in case that the
dictionary does not contain the key, you can specified a second optional argument to return a default
value, if the argument is not included get method will return None.
y = {'one': 1, 'two': 2}
print(y.get('one'))
print(y.get('three'))
print(y.get('three', 'The key does not exist.'))

Output:
1 None The key does not exist.

setdefault
This method is similar to get method, it returns the value associated with a key if the dictionary
contains that key, but in case that the dictionary does not contain the key, this method will create a new
element in the dictionary (key-value pair), where the first argument in this method is the key, and the
second argument is the value. The second argument is optional, but if this is not included, the value will
be None.
y = {'one': 1, 'two': 2}
print(y.setdefault('three', '3'))
print(y.setdefault('two', 'dos'))
print(y)

Output:
32{'one': 1, 'two': 2, 'three': '3'}

These are some of the most common and important operations related to Python dictionaries, and
this is one of the main reasons to know them in detail.
I invite you to comment on any detail that has not been mentioned. I am sure that your
contribution will be very valuable.

11 b Describe the need for catching exceptions using try and except statements.
In Python, exceptions can be handled using a try statement.
The critical operation which can raise an exception is placed inside the try clause. The code that handles the
exceptions is written in the except clause.
We can thus choose what operations to perform once we have caught the exception. Here is a simple
example.

# import module sys to get the type of exception


import sys
randomList = ['a', 0, 2]
for entry in randomList:
try:
print("The entry is", entry)
r = 1/int(entry)
break
except:
print("Oops!", sys.exc_info()[0], "occurred.")
print("Next entry.")
print()
print("The reciprocal of", entry, "is", r)

Output:
The entry is a
Oops! <class 'ValueError'> occurred.
Next entry.

The entry is 0
Oops! <class 'ZeroDivisionError'> occured.
Next entry.

The entry is 2
The reciprocal of 2 is 0.5

In this program, we loop through the values of the randomList list. As previously mentioned, the portion that can
cause an exception is placed inside the try block.

If no exception occurs, the except block is skipped and normal flow continues(for last value). But if any
exception occurs, it is caught by the except block (first and second values).

Here, we print the name of the exception using the exc_info() function inside sys module. We can see that a
causes ValueError and 0 causes ZeroDivisionError.

Since every exception in Python inherits from the base Exception class, we can also perform the above task in the
following way:

# import module sys to get the type of exception


import sys
randomList = ['a', 0, 2]
for entry in randomList:
try:
print("The entry is", entry)
r = 1/int(entry)
break
except Exception as e:
print("Oops!", e.__class__, "occurred.")
print("Next entry.")
print()
print("The reciprocal of", entry, "is", r)
This program has the same output as the above program. Catching Specific Exceptions in Python
In the above example, we did not mention any specific exception in the except clause.
This is not a good programming practice as it will catch all exceptions and handle every case in the same
way. We can specify which exceptions an except clause should catch.
A try clause can have any number of except clauses to handle different exceptions, however, only one will
be executed in case an exception occurs.

We can use a tuple of values to specify multiple exceptions in an except clause. Here is an example pseudo
code.
try:
# do something
pass
except ValueError:
# handle ValueError exception
pass
except (TypeError, ZeroDivisionError):
# handle multiple exceptions
# TypeError and ZeroDivisionError
pass
except:
# handle all other exceptions
pass

Raising Exceptions in Python


In Python programming, exceptions are raised when errors occur at runtime. We can also manually raise
exceptions using the raise keyword.

We can optionally pass values to the exception to clarify why that exception was raised.
>>> raise KeyboardInterrupt
Traceback (most recent call last):
...
KeyboardInterrupt
>>> raise MemoryError("This is an argument")
Traceback (most recent call last):
...
MemoryError: This is an argument

>>> try:
... a = int(input("Enter a positive integer: "))
... if a <= 0:
... raise ValueError("That is not a positive number!")
... except ValueError as ve:
... print(ve)
...
Enter a positive integer: -2
That is not a positive number!
Python try with else clause
In some situations, you might want to run a certain block of code if the code block inside try ran without any
errors. For these cases, you can use the optional else keyword with the try statement.
Note: Exceptions in the else clause are not handled by the preceding except clauses.

Let's look at an example:

# program to print the reciprocal of even numbers


try:
num = int(input("Enter a number: "))
assert num % 2 == 0
except:
print("Not an even number!")
else:
reciprocal = 1/num
print(reciprocal)
Output:
If we pass an odd number:
Enter a number: 1
Not an even number!
If we pass an even number, the reciprocal is computed and displayed.
Enter a number: 4
0.25
However, if we pass 0, we get ZeroDivisionError as the code block inside else is not handled by preceding
except.
Enter a number: 0
Traceback (most recent call last):
File "<string>", line 7, in <module>
reciprocal = 1/num
ZeroDivisionError: division by zero
Python try...finally
The try statement in Python can have an optional finally clause. This clause is executed no matter what, and
is generally used to release external resources.
For example, we may be connected to a remote data center through the network or working with a file or a
Graphical User Interface (GUI).
In all these circumstances, we must clean up the resource before the program comes to a halt whether it
successfully ran or not. These actions (closing a file, GUI or disconnecting from network) are performed in the
finally clause to guarantee the execution.
Here is an example of file operations to illustrate this.
try:
f = open("test.txt",encoding = 'utf-8')
# perform file operations
finally:
f.close()
This type of construct makes sure that the file is closed even if an exception occurs during the program execution.

You might also like