Python - Unit - V - QB
Python - Unit - V - QB
(Autonomous)
Approved by AICTE, New Delhi & Affiliated to Anna University, Chennai
Accredited by NBA, NAAC with “A+” and Recognized by UGC (2f &12B)
KOMARAPALAYAM – 637303
PART-A
Q.No Questions
Define tuples in Python.
A tuple is another sequence data type that is similar to the list.
1
A tuple consists of a number of values, enclosed within parentheses and separated by
commas.
Differentiate tuple and list in python.
2 Lists are enclosed in brackets ([ ]) and their elements and size can be changed (Mutable).
While tuples are enclosed in parentheses (()) and cannot be updated (Immutable).
PART-B
Q.No Questions
1 Summarize tuple assignment with suitable example.
Tuple assignment is the process that assigns the values on the right-hand side to the left-hand
side variables.
Python uses the commas (,) to define a tuple, not parentheses.
Unpacking a tuple means splitting the tuple’s elements into individual variables.
Ex:-
Num=(1,2)
print(“The no is”,Num)
Output:-
The no is (1, 2)
The left side is a tuple of variables Num. The right side is also a tuple of two integers 1 and 2.
The expression assigns the tuple elements on the right side (1, 2) to each variable on the left
side based on the relative position of each element.
Ex:-
x ,y =(10, 20)
print(x, y)
tmp = x
x=y
y = tmp
print(x,y)
Output:-
10 20
20 10
The * operator use to assign remaining elements of an unpacking assignment into a list and
assign it to a variable.
Ex:-
odd_numbers = (1, 3, 5)
even_numbers = (2, 4, 6)
numbers = (*odd_numbers, *even_numbers)
print(numbers)
Output:
(1,3,5,2,4,6)
x, *y= (10, 20, 30)
numbers = (x, *y)
print(numbers)
Output:-
(10,20,30)
2 Explain in detail about dictionaries and its operations.
Dictionary is an unordered collection of key-value pairs. In Python, dictionaries are defined
within braces {} with each item being a pair in the form key:value.
Key and value can be of any type. Syntax dict = {}
Ex:-
Fruits={1:‘Apple’,2:’Orange’,3:’Mango’,4:’Grapes’,5:’Guava’}
print(Fruits)
Output:-
{1:‘Apple’,2:’Orange’,3:’Mango’,4:’Grapes’,5:’Guava’}
Dictionary items are ordered, changeable, and does not allow duplicates.
Unordered means that the item does not have a defined order, you cannot refer to an item by
using an index.
Dictionaries are change, add or remove items after the dictionary has been created.
It cannot have two items with the same key.
Ex:- 1
Output:- Apple
Ex:- 2
Fruits = {}
print("Empty Dictionary: ")
print(Fruits)
# Creating a Dictionary
# with dict() method
Fruits = dict({1: 'Apple', 2: 'orange', 3:'Mango'})
print("\nDictionary with the use of dict(): ")
print(Fruits)
# Creating a Dictionary
# with each item as a Pair
Fruits = dict([(1, 'Apple'), (2, 'Mango'),(3,’Mango’)])
print("\nDictionary with each item as a pair: ")
print(Fruits)
Output:-
Empty Dictionary:
{}
Dictionary with the use of dict():
{1: 'Apple', 2: 'orange', 3: 'Mango'}
Dictionary with each item as a pair:
{1: 'Apple', 2: 'Mango', 3: 'Mango'}
3(a) Discuss in detail about tuples as return values and write a Python program to find quotient
and remainder using function.
The function can only return one value but if the value is tuple the same as returning the
multiple value.
Function can return tuple as return value.
Eg:-
# the value of quotient & remainder are returned as tuple
def mod_div(x,y):
quotient = x/y
remainder= x%y
return quotient, remainder
For example
y = {}x = {1: "one", 2: "two", 3: "three"}
y={ }
x={ 1: “one”, 2: ”two”, 3: ”three”}
print(“display”,x)
Output:-
{ 1: “one”, 2: ”two”, 3: ”three”}
Methods:-
Methods that are available with dictionary
Clear() - Remove all items form the dictionary.
copy() - Return a shallow copy of the dictionary.
Update()-Update the dictionary with the key/value pairs from other, overwriting
values() Return a new view of the dictionary's values
Ex:-
Clear()
car = { "brand": "Ford", "model": "Mustang", "year": 1964 }
car.clear()
print(car)
Copy()
car = { "brand": "Ford", "model": "Mustang", "year": 1964 }
x = car.copy()
print(x)
4(a) Describe various operations of tuple with sample program(create, delete, access, replace).
A tuple is a sequence of value which can be of any type and they are indexed by integers.
Values in tuple are enclosed in parentheses and separated by comma.
The elements in the tuple cannot be modified as in list (i.e) tuple are immutable.
Creating tuple:
Tuple can be created by enclosing the element in parentheses separated by comma.
t = ('a','b','c','d')
Alternative way to create a tuple is the built-in function tuple which mean, it creates an empty
tuple.
>>> t = tuple ()
>>> t
>>> ( )
Accessing element in tuple:
If the argument in sequence, the result is a tuple with the elements of sequence.
t = ('a','b',100,8.02)
print (t[0]) = 'a'
print (t[1:3]) = ('b', 100 , 8.02)
Eg :
a = (' programming', 200, 16.54, 'c', 'd')
#Try changing an element.
a[ 0 ] = 'python' <-------- Error, modifying not possible in tuple
print (a [0])
Ex:-
def copyFile(oldFile, newFile):
f1 = open(oldFile, “r”)
f2 = open(newFile, “w”)
while True:
text = f1.read(50)
if text == “”:
break
f2.write(text)
f1.close()
f2.close()
return
5(a) Write a program to perform exception handling and multiple exceptions Exception handling:
def exists(filename):
try:
f = open(filename)
f.close()
return True
except IOError:
return False
Multiple exceptions:
try:
x = float(raw_input(“Your number”))
inverse = 1.0 / x
except ValueError:
print (“You should have given either an int or a float”)
except ZeroDivisionError:
print (”Infinity”)
5(b) Write a python program to explain various types of string format.
# %s - string
var = '27' #as string
string = 'Variable as string = %s' %(var)
print(string)
#%i - Integer
print('Variable as integer = %i' %(int(var)))
#%f – float
print('Variable as float = %f' %(float(var)))
#%x - hexadecimal
print('Variable as hexadecimal = %x'%(int(var)))
#%o - octal
print('Variable as octal = %o' %(int(var)))
Output:-
Variable as string = 27
Variable as raw data = '27'
Variable as integer = 27
Variable as float = 27.000000
Variable as hexadecimal = 1b
Variable as octal = 33
6(a) Discuss in detail about the concepts of format and string format with example.
Format:-
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.
Ex:-
a = "My name is {fname}, I'm {age}".format(fname = "John", age = 36)
b = "My name is {0}, I'm {1}".format("John",36)
c = "My name is {}, I'm {}".format("John",36)
print(a)
print(b)
print(c)
Output:-
My name is John, I'm 36
My name is John, I'm 36
My name is John, I'm 36
String format:-
String formatting using % Operator
It is the oldest method of string formatting. Here we use the modulo % operator. The
modulo % is also known as the “string-formatting operator”.
Example:
print("The dog is %animal." %'good')
Output:
The dog is good animal.
Multiple strings at a time and can also use variables to insert objects in the string.
Example: multiple strings using % operator
x = 'looked'
print("Misha %s and %s around"%('walked',x))
Output:
Misha walked and looked around.
6(b) Explain in detail about concepts of exception handling with suitable example.
Whenever a runtime error occurs, it creates an exception. The program stops execution and prints an
error message.
For example,
Dividing by zero creates an exception: print 55/0
There are mainly three kinds of errors in Python
syntax errors
exceptions
logical errors.
Syntax errors
Missing symbols (such as comma, bracket, colon), misspelling a keyword, having incorrect
indentation are common syntax errors in Python.
Exceptions
It may occur in syntactically correct code blocks at run time.
When Python cannot execute the requested action, it terminates the code and raises an error
message.
Logical errors
If you have logical errors, your code does not run as you expected.
Using incorrect variable names, code that is not reflecting the algorithm logic properly,
making mistakes on boolean operators will result in logical errors.
Ex:-
a=3
try:
div = a /2
print( div )
except ZeroDivisionError:
print( "Atepting to divide by zero" )
finally:
print( 'This is code of finally clause' )
Output:-
Attempting to divide by zero
This is code of finally clause
The try statement executes the statements in the first block.
If no exception occurs, then except statement is ignored.
If an exception of type IOError occurs, it executes the statements in the except branch and
then continues.