VTU Exam Question Paper With Solution of BPLCK205B Introduction to Python Programming Sep-2023-Dr.M.farida Begam
VTU Exam Question Paper With Solution of BPLCK205B Introduction to Python Programming Sep-2023-Dr.M.farida Begam
input (): -The input () function waits for the user to type some text on the keyboard
and press enter.
Code: -
String replication (): - The * operator is used for multiplication when it operates on two inte-
ger or floating-point values. But when the * operator is used on one string value and one integer
value, it becomes the string replication operator.
Code: -
Q 1 b Develop a program to generate Fibonacci sequences of length (N). Read N from the
console. [ 6 Marks]
Full Program- [4 Marks]
Logic- [2 Marks]
A 1 b Code: -
Q 1 c Explain elif, for, while, break and continue statements in python with examples for
each. [8 Marks]
Explanation - [ 5 Marks]
Example & Code- [3 Marks]
A 1 c elif: - In Python, elif is short for "else if" and is used when the first if statement isn't true,
but you want to check for another condition. An else statement can be combined with an if
statement. An else statement contains the block of code that executes if the conditional expression
in the if statement resolves to 0 or a FALSE value.
while Loop Statements: - Python While Loop is used to execute a block of statements repeatedly
until a given condition is satisfied. And when the condition becomes false, the line immediately
after the loop in the program is executed.
Code: -
break Statements: -There is a shortcut to getting the program execution to break out of a while
loop’s clause early. If the execution reaches a break statement, it immediately exits the while
loop’s clause. In code, a break statement simply contains the break keyword.
Code: -
continue Statements: - Like break statements, continue statements are used inside loops. When
the program execution reaches a continue statement, the program execution immediately jumps
back to the start of the loop and reevaluates the loop’s condition. (This is also what happens
when the execution reaches the end of the loop.)
Code: -
for loop:-
A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or
a string). This is less like the for keyword in other programming languages, and works more like
an iterator method as found in other object-orientated programming languages. With the for loop
we can execute a set of statements, once for each item in a list, tuple, set etc.In code, a for statement
looks something like for i in range(5): and always includes the following:
• The for keyword
• A variable name
• The in keyword
• A call to the range () method with up to three integers passed to it
• A colon
• Starting on the next line, an indented block of code (called the for
clause)
Code: -
Q 2 a What are user defined functions? How can we pass parameters in user defined
functions? Explain with suitable examples [5 Marks]
Explanation & Example - [ 2 Marks]
Method & Code- [3 Marks]
A 2 a Python User-defined functions: -All the functions that are written by any of us come under
the category of user-defined functions. Below are the steps for writing user-defined functions
in Python.
• In Python, a def keyword is used to declare user-defined functions.
• An indented block of statements follows the function name and arguments which
contains the body of the function.
Syntax:
def function_name():
statements
.
.
Here we have created the fun function and then called the fun() function to print the statement.
# Declaring a function
def fun():
print("Inside function")
# Driver's code
# Calling function
fun()
Output:
Inside function
How to pass a parameter to a function
The purpose of function parameters in Python is to allow a programmer using the function to define
variables dynamically within the function.
It’s important to note that after passing a parameter to a function, an argument should be passed to
the parameter of the function whenever you call the key function in your program.
Note: An argument is a value that is supplied to the parameter whenever the function is called.
Now, let’s pass a parameter to a function that will help us store the name of our customers by
returning the argument (real name) we pass to that function.
Code
# defining a funtion and passing the name parameter to it
def greet_customer(name):
print (f'Hi {name} welcome aboard to the home of delicacies!')
# calling the function and passing Theophilus as the argument
greet_customer('Theophilus')
# calling the function and passing Chidalu as the argument
greet_customer('Chidalu')
Output
Hi Theophilus welcome aboard to the home of delicacies!
Hi Chidalu welcome aboard to the home of delicacies!
Explanation
• In the code above, we use the def keyword to show that we are defining a function.
• The name of our function is greet_customer(name). (name) is the parameter of the
function.
• The double line breaks must be included after defining a function.
• (Theophilus) and (Chidalu) are the arguments passed to
the greet_customer(name) function whenever it is called.
• greet_custumer(Theophilus) and greet_customer('Chidalu) are used to called the key
function, greet_customer(name). Without calling the key function, the program will not
execute the defined function.
Q 2b Explain local & Global scope with variables for each [8 Marks]
Explanation- [ 4 Marks]
Example & Code-[4=2*2 Marks]
A 2b A variable is only available from inside the region it is created. This is called scope.A
variable created inside a function belongs to the local scope of that function, and can only be used
inside that function.
Eg: def myfunc():
x = 300
print(x)
myfunc()
• Local Variables Cannot Be Used in the Global Scope
• This code results in an error.
def spam():
eggs = 31337
spam()
print(eggs)
• Local Scopes Cannot Use Variables in Other Local Scopes
• Global Variables Can Be Read from a Local Scope-Example
def spam():
print(eggs)
eggs = 42
spam()
print(eggs)
• It is acceptable to use the same variable name for a global variable and local variables in
different scopes in Python
Q 2 c Develop a program to read the name and year of birth of a person. Display whether
the person is a senior citizen or not. [7 Marks]
Full Program- [4 Marks]
Logic-[3 Marks]
A2c
Code:-
from datetime import date
def calculateAge(birthDate):
today = date.today()
age = today.year - birthDate.year -
((today.month, today.day) <
(birthDate.month, birthDate.day))
return age
# Driver code
print(calculateAge(date(1997, 2, 3)), "years")
Or
Code:-
age = int (input (“Enter the age of the person: “) )
#Condition to check whether the person is senior citizenship or not:
if age >= 60:
status = "Senior citizenship "
else:
status = "Not a senior citizenship "
print (“The person is ", status)
Q 3 a What is List? Explain append (), insert () and remove () methods with examples. [ 8
Marks]
Explanation- [ 2 Marks]
Method & Code- [6=2*3 Marks]
A3a
Lists are just like dynamically sized arrays, declared in other languages (vector in C++ and
ArrayList in Java). Lists need not be homogeneous always which makes it the most powerful tool
in Python. A single list may contain DataTypes like Integers, Strings, as well as Objects.
Lists are mutable, and hence, they can be altered even after their creation. Lists have various
methods, the most commonly used list method are append(), insert (), extend(), etc.
Append
It adds an element at the end of the list. The argument passed in the append function is added as a
single element at end of the list and the length of the list is increased by 1.
Syntax:
list_name.append(element)
The element can be a string, integer, tuple, or another list.
Example:
Output:
['geeks', 'for', 'geeks']
Insert
This method can be used to insert a value at any desired position. It takes two arguments-element
and the index at which the element has to be inserted.
Syntax:
list_name(index,element)
The element can be a string, object, or integer.
Example:
Output:
['geeks', 'for', 'geeks']
remove (item):
This method is used to remove particular item from the list.
Create a python file with the following script to see the use remove () method. If the item value
that is used as the argument value of remove () method exists in the list the item will be removed.
Here, the value, ‘Juice’ exists in the list and it will be removed after running the script.
# Define the list
list = ['Cake', 'Pizza', 'Juice', 'Pasta', 'Burger']
# Remove an item
list.remove('Juice')
dictionary.items()
Example
print(marks.items())
Values()
The values() method returns a view object. The view object contains the values of the dictionary, as a
list.The view object will reflect any changes done to the dictionary, see example below.
Syntax
dictionary.values()
Example:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
x = car.values()
print(x)
output:
Keys():
The keys() method returns a view object. The view object contains the keys of the dictionary, as a list.The
view object will reflect any changes done to the dictionary, see example below
Syntax
dictionary.keys()
Example:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
x = car.keys()
print(x)
output:
Q 4 a How is a tuple different from a list and what function is used to convert list to tuple?
Explain. [ 6 Marks]
Explanation- [ 4 Marks]
Example code- [2 Marks]
A4a
Sno LIST TUPLE
The list is better for performing operations, such A Tuple data type is appropriate for
3
as insertion and deletion. accessing the elements
print(sample_list)
Output
Dictionary in Python Dictionary is a default python data structure used to store the data collection in the
form of key-value pairs. Dictionaries are written inside the curly brackets ({}), separated by commas.
However, the key and value of the data are separated by placing a semi-colon between them (:). Dictionary
elements are ordered, changeable, and do not allow duplicates. Remember that the key name of every data
value should be unique and are case-sensitive. Later, you can access the dictionary elements by simply
using the key name and retrieving its corresponding data value.
For Example:
sample_dict = {
"vegetable": "potato",
"fruit": "banana",
"chocolate": "gems"
print(sample_dict)
Output
Creation We can create a list by placing We can create a dictionary by placing all the
all the available elements into a available elements into a { } in the form of a
[ ] and separating them using “,” key:vale. Here, we have to separate each pair of
commas. available key-values using the “,” commas.
Data Type The indices in the case of a list The keys present in a dictionary can easily be of
are basically integers that start any given data type.
from the value 0.
Mode of We can access the elements in a We can access the elements present in a
Accessing key using indices. dictionary using the key-values.
Order of The entered order of elements is We don’t have any guarantee of maintaining the
Elements always maintained. order of the available elements.
Q 4 c Read N numbers from the console and create a list. Develop a program to compute
and print mean, variance and standard deviation with messages. [10 Marks]
Full Program- [6 Marks]
Logic- [4 Marks]
A4c
Q 5 a Explain the following methods with suitable examples. [8 Marks]
Explanation- [ 4 Marks]
Example code- [4 Marks]
i) upper()
ii) lower()
iii) is_upper()
iv) is_lower()
A 5 a i) upper ()
i) The upper () and lower () string methods return a new string where all the letters in the original
string have been converted to uppercase or lower- case, respectively. Non-Letter characters in the
string remain unchanged.
Code: -
If you want to change the original string, you have to call upper () or lower () on the string and
then assign the new string to the variable where the original was stored. The upper() and lower()
methods are helpful if you need to make a case-insensitive comparison.
ii) lower ()
ii) Code: -
iii) is_upper()
iii) Code: -
iv) is_lower()
iv) Code: -
Q5 b Illustrate with examples opening of a file with open () function, reading the contents
of the file with read () and writing to files with write () [12 Marks]
Explanation- [ 4 Marks]
Example code- [4 Marks]
Logic- [4 Marks]
A5 b Text files with the .txt extension or Python script files with the .py extension are examples
of plaintext files. These can be opened with Windows’s Notepad or OS X’s TextEdit application.
Programs can easily read the contents of plaintext files and treat them as an ordinary string value.
Binary files are all other file types, such as word processing documents, PDFs, images,
spreadsheets, and executable programs.
Code: -
Writing to Files
Python allows you to write content to a file in a way similar to how the print () function “writes”
strings to the screen. You can’t write to a file you’ve opened in read mode, though. Instead, you
need to open it in “write plaintext” mode or “append plaintext” mode, or write mode and append
mode for short. Write mode will overwrite the existing file and start from scratch, just like when
you overwrite a variable’s value with a new value. Pass 'w' as the second argument to open () to
open the file in write mode. Append mode, on the other hand, will append text to the end of the
existing file.
If the filename passed to open () does not exist, both write and append mode will create a new,
blank file. After reading or writing a file, call the close () method before opening the file again.
Code: -
Q 6a Explain the steps involved in adding bullets to Wiki, Markup, Support with appropriate
code (10 Marks)
Explanation – [4 Marks]
Example code– [6 Marks]
A 6 a When editing a Wikipedia article, you can create a bulleted list by putting each list item on
its own line and placing a star in front. The bulletPointAdder.py script will get the text from the
clipboard, add a star and space to the beginning of each line, and then paste this new text to the
clipboard. For example: -
Lists of animals
Lists of aquarium life
Lists of biologists by author abbreviation
Lists of cultivars
and then ran the bulletPointAdder.py program, the clipboard would then contain the following:
* Lists of animals
* Lists of aquarium life
* Lists of biologists by author abbreviation
* Lists of cultivars
Q 6 b Develop a program to sort the content of a text file and write the sorted contents into
a separate text file. [Use strip (), len (), list methods sort (), append & file methods open(),
readlines() & write()]. [10 Marks]
Full Program- [6 Marks]
Logic- [4 Marks]
A 6 b To sort the contents of a file, firstly we need to open the file in ‘read’ mode. After this, we
will open the specific file using statement given below-
file = open(“filename.extension”)
Q 7 a How do you copy files and folders using the Shutil module. Explain in detail.
[6 Marks]
Explanation – [3 Marks]
Example code– [3 Marks]
A 7 a The shutil module in Python provides functions for working with files and directories. You
can useshutil to copy, move, and rename files
i) Copying files: To copy a file from one location to another, use the shutil.copy(src, dst) method.
The src argument is the path of the source file, and the dst argument is the path of the destination
file. If dst is a directory, the file is copied with the same name to that directory
ii) Moving files: To move a file from one location to another, use the shutil.move(src, dst) method.
The src argument is the path of the source file, and the st argument is the path of the destination
file. If dst is a directory, the file is moved with the same name to that directory
iii) Renaming files: To rename a file, use the os.rename(src, dst) method. The src argument is
the path of the source file, and the dst argument is the new name of the file import os
Q 7b What are assertions? Write the contents of an assert statement. Explain them with
examples. [8 Marks]
Explanation – [4 Marks]
Example code– [4 Marks]
7 b Assertions are statements in Python that can be used to check if a condition is true. They are
often used as a debugging aid to ensure that the assumptions made by the programmer about the
state of the program are correct. If the assertion is false, an AssertError is raised, indicating that
there is a bug in the program. An assert statement consists of the assert keyword, followed by a
condition that is expected to be true.
Example.
x=5
assert x == 5, "x is not 5"
Here, we use the assert statement to check that the variable x has the value 5. If the condition x ==
5 is false, an AssertionError is raised with the message "x is not 5"
Assertions can be used to add automated tests in codes to catch bugs early in the development
process. For example, we can use assertions to check that the output of a function is correct for a
given input.
Code Snippet:
def square(x):
return x ** 2
assert square(2) == 4, "square(2) should be 4"
assert square(3) == 9, "square(3) should be 9"
assert square(-2) == 4, "square(-2) should be 4"
Here, we define a function square that returns the square of a number. We then use assert
statements to check that the output of the function is correct for different input values.
Q 7 c Illustrate the logging levels in python. [6 Marks]
Explanation – [3 Marks]
Example code– [3 Marks]
A 7 c Logging is a great way to understand what’s happening in your program and in what order
it's happening. Python’s logging module makes it easy to create a record of custom messages that
you write. These log messages will describe when the program execution has reached the logging
function call and list any variables you have specified at that point in time. On the other hand, a
missing log message indicates a part of the code was skipped and never executed. Logging levels
provide a way to categorize your log messages by importance. There are five logging levels,
described in Table from least to most important. Messages can be logged at each level using a
different logging function.
The benefit of logging levels is that you can change what priority of logging message you want to
see. Passing logging.DEBUG to the basicConfig() function’s level keyword argument will show
messages from all the logging levels (DEBUG being the lowest level).
Q 8 a With suitable code, explain Backing up a folder into a Zip File. Clearly mention the
step involved [12 Marks]
Explanation- [3 Marks]
Full Program- [5 Marks]
Logic- [4 Marks]
A 8 a Python can be used to extract all files and folders within a zip file. This can be done through
the zipfile module. The zipfile module allows us to work with zip files, doing things such as
creating zip files, reading zip files, extracting all files and folders from the zip file, and adding files
to zip files. So, if you want an example of a zip file if you don't have your own, you can use this
basic zip file here: documents.zip.This is a simple zip file composed of 4 files: document1.txt,
document2.txt, document3.txt, and document4.txtThis is a zip file, meaning it is compressed.
Code Snippet
>>>import zipfile
>>> import os
>>> os.getcwd()
'C:\\Users\\dlhyl\\AppData\\Local\\Programs\\Python\\Python38-32'
>>> myzipfile= zipfile. ZipFile('documents.zip')
>>> myzipfile.extractall()
>>> myzipfile.close()
Step involved
Step 1: Figure Out the ZIP File’s Name
Step 2: Create the New ZIP File
Step 3: Walk the Directory Tree and Add to the ZIP File
Q 8 b Explain the logging module and debug the factorial of number program [8 Marks]
Explanation – [3 Marks]
Example code– [3 Marks]
Logic- [2 Marks]
A 8 b To enable the logging module to display log messages on your screen as your program runs,
copy the following to the top of your program (but under
the #! python shebang line):
Code: -
Code: -
Q 9 a What is a class? How to define a class in python? How to initiate a class and how the
class members are accessed [ 8 Marks]
Explanation – [5 Marks]
Example code– [3 Marks]
A 9 a A Class is like an object constructor, or a "blueprint" for creating objects.
Example
To create a class, use the keyword class:
class MyClass:
x=5
class Point: """Represents a point in 2-D space."""
The header indicates that the new class is called Point. The body is a docstring that explains what
the class is for. You can define variables and methods inside a class definition, but we will get
back to that later. Defining a class named Point creates a class object. >>> Point Because Point is
defined at the top level, its “full name” is __main__.Point. The class object is like a factory for
creating objects. To create a Point, you call Point as if it were a function. >>> blank = Point()
>>> blank <__main__.Point object at 0xb7e9d3ac> The return value is a reference to a Point
object, which we assign to blank. Creating a new object is called instantiation, and the object is
an instance of the class. When you print an instance, Python tells you what class it belongs to and
where it is stored in memory (the prefix 0x means that the following number is in hexadecimal)
The function creates a new Time object, initializes its attributes, and returns a reference to the new
object. This is called a pure function because it does not modify any of the objects passed to it as
arguments and it has no side effects, such as displaying a value or getting user input.
We'll create two Time objects: currentTime, which contains the current time; and breadTime,
which contains the amount of time it takes for a breadmaker to make bread. The output of this
program is 12:49:30, which is correct.
9 c Explain Printing objects. [ 4 Marks]
Explanation- [2 Marks]
Example- [2 Marks]
A 9 c An Object is an instance of a Class. A class is like a blueprint while an instance is a copy of
the class with actual values. When an object of a class is created, the class is said to be instantiated.
All the instances share the attributes and the behavior of the class. But the values of those attributes,
i.e., the state are unique for each object. A single class may have any number of instances.
Printing objects give us information about the objects we are working with
Code:-
# Defining a class
class Test:
def __init__(self, a, b):
self.a = a
self.b = b
def __repr__(self):
return "Test a:% s b:% s" % (self.a, self.b)
def __str__(self):
return "From str method of Test: a is % s, " \
"b is % s" % (self.a, self.b)
# Driver Code
t = Test(1234, 5678)
Q 10 b Write Deck methods to add, remove, shuffle & sort cards, with illustrating the
problems. [10 Marks]
Explanation – [4 Marks]
Example code– [3 Marks]
Logic- [3 Marks]
A 10 bClass definition for Deck.
The init method creates the attribute cards and generates the standard set of fifty-two cards:
Code:-
Deck: -
Add: -