0% found this document useful (0 votes)
14 views9 pages

Python - Unit - V - QB

Uploaded by

sakthivelv.eec
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
14 views9 pages

Python - Unit - V - QB

Uploaded by

sakthivelv.eec
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 9

EXCEL ENGINEERING COLLEGE

(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

Department of Electronics and Communication Engineering


23CS102 - Problem solving using Python
Regulation 2023

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).

Quote the python dictionaries.


 Dictionary is an unordered collection of key-value pairs. In Python, dictionaries are defined
3 within braces {} with each item being a pair in the form key : value.
 Key and value can be of any type.
 Syntax - dict={}
Create a dictionary in python.
Fruits={1:‘Apple’, 2:’Orange’, 3:’Mango’, 4:’Grapes’, 5:’Guava’}
4
print(Fruits)
Output:-
{1:‘Apple’, 2:’Orange’, 3:’Mango’, 4:’Grapes’, 5:’Guava’}
Write a python program for tuples.
Tuple = (‘apple’,’mango’,’banana’)
5 print(tuple)
output:-
(‘apple’,’mango’,’banana’)
Infer the method to add elements in list.
The append () method is used to add elements to a list.
List=[123,‘VRB‘]
List.append(2017)
6
print(“Updated List”,List)
Output:
Updated List:[123,‘VRB‘,2017]
List out few methods that are used in Python Lists.
7  append()-add an element to end of list
 insert()-insert an item at the defined index
 remove()-removes an item from the list
 clear()-removes all items from the list
Give two dictionary operations.
8  Del -removes
 key-value pairs from a dictionary
 Len - returns the number of key-value pairs
Define tuple assignment.
9  Unpacking or tuple assignment is the process that assigns the values on the right- hand
side to the left-hand side variables.
 E.g.,tuple=(‘apple’,’mango’,’banana’)
What is the output of print tuple [1:3] if tuple = ('abcd', 786, 2.23,'john', 70.2)?
10  In the given command, tuple [1:3] is accessing the items in tuple using indexing.
 It will print elements starting from 2nd till 3rd.
 Output will be (786, 2.23).
Identify the key-value pairs in dictionary.
11  The elements of a dictionary appear in a comma-separated list. Each entry contains an
index and a value separated by a colon.
 In a dictionary, the indices are called keys, so the elements are called key-value pairs.
Quote about form keys() and items() in dictionary.
12  Form keys()–Creates a dictionary from the given sequence
 items()-Return the list with all dictionary keys with values
List out the methods that are used in python tuple.
 len()-returns the length in the tuple
13  max()-returns the largest item in tuple
 min()-returns the smallest item in tuple
 sum()-returns the sum of all elements in tuple
Recall an exception with examples.
14  Whenever a runtime error occurs, it creates an exception. The program stops execution
and prints an error message.
 For example, Zero Division Error: dividing by zero creates an exception: print 55/0
Label the error messages that are displayed for the following exceptions.
a. Accessing a non-existent list item b. Accessing a key that isn’t in the dictionary c. Trying to
open a non-existent file.
15
Answer
a. Index Error: list index out of range b. Key Error: Key not found c. IO Error: No such file or
directory: 'filename
State about try and execute in exception handling.
 The try statement executes the statements in the first block. If no exception occurs, then
16 except statement is ignored.
 If an exception of type IO Error occurs, it executes the statements in the except branch and
then continues.
Write a python program that writes “Hello world” into a file.
 f=open("ex88.txt",'w')
17  f.write("hello world")
 f.close()
18 Create a python program that counts the letters of words in a file.
 def countLetters(word):
 return len([x for x in word if x.isalpha()])
 print(countLetters("Word."))
 print(countLetters("Word.with.non-letters1"))
Output
4
18
19 Mention a method to open a new file in python.
 The open function takes two arguments. The first is the name of the file and the second is the
mode.
 Mode "r" means that we are opening the file for reading.
 Eg., f = open(“text.txt”,”r”)
20 Restate a text file in python.
 A text file is a file that contains printable characters and whitespace, organized in to lines
separated by newline characters.
 Eg., f.write("line one\nline two\nline three\n")

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

Fruits = { 1: "Apple", 2: "Orange", 3: “Mango”}


print(Fruits[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

# Input the seconds & get the hours minutes &


second sec = 4234
minutes,seconds= mod_div(sec,60)
hours,minutes=mod_div(minutes,60)
print("%d seconds=%d hrs:: %d min:: %d sec"%(sec,hours,minutes,seconds))
Output:
4234onds=1 hrs:: 10 min:: 34 sec
3(b) Illustrate in detail about dictionary methods with example programs.
 Python dictionary is an unordered collection of items.
 While other compound data types have only value as an element, a dictionary has a key:
value pair.
Syntax:-
d = dict([
(<key>, <value>),
(<key>, <value),
.
(<key>, <value>)])

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)

Deleting and updating tuple:


 Tuple are immutable, hence the elements in tuple cannot be updated / modified.
 But we can delete the entire tuple by using keyword 'del'

Eg :
a = (' programming', 200, 16.54, 'c', 'd')
#Try changing an element.
a[ 0 ] = 'python' <-------- Error, modifying not possible in tuple
print (a [0])

Eg: # Deletion of tuple


a = ('a','b','c','d')
del (a) :-------- delete entire tuple
del a [1] <--------- error, deleting one element in tuple not possible

Eg: # replacing one tuple with another


a = ('a','b','c','d')
t = ('A',) + a[1: ]
print (t) <------ ('a','b','c','d') in tuple replace the value ‘a’ replace ‘A’
4(b) Explain file mode in python and write a function that copies a file reading and writing up to
50 characters at a time.
 File handle is like a cursor, which defines from where the data has to be read or written in
the file. There are 6 access modes in python.
1. Read Only (‘r’) : Open text file for reading.
2. Read and Write (‘r+’): Open the file for reading and writing.
3. Write Only (‘w’) : Open the file for writing.
4. Write and Read (‘w+’) : Open the file for reading and writing. For an existing file, data is
truncated and over-written.
5. Append Only (‘a’): Open the file for writing. The file is created if it does not exist. The data
being written will be inserted at the end, after the existing data.

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)

#%r - raw data


print ('Variable as raw data = %r' %(var))

#%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.

You might also like