VTU exam Question Paper with Solution of BPLCK205B Introduction to Python Programming July-2024-Deepa H, Manasa C H, Saba Tahseen, Apurva Chaudhari
VTU exam Question Paper with Solution of BPLCK205B Introduction to Python Programming July-2024-Deepa H, Manasa C H, Saba Tahseen, Apurva Chaudhari
Examples of while
# Prints "Hello, world." to the console five times:
spam = 0
while spam < 5:
print('Hello, world.')
spam = spam + 1
Q 1 c Develop a program to genratë Fibonacci sequence of Length(N). Read N from the
console. [8 Marks]
Full Program- [5 Marks]
Logic-[3 Marks]
Program:
n=int(input("enter the number"))
a=0
b=1
sum=0
i=0
print("fibonacci series")
while(i<=n):
print(sum)
a=b
b=sum
sum=a+b
i=i+1
Output:
N=5
Fibonacci sequence =0 1 1 2 3
Q 2 a What are functions? Explain python function with parameters and return statement.
[6 Marks]
A function is like a mini-program within a program.
def Statements with Parameters:
def hello(name):
print('Hello ' + name)
hello('Alice')
hello('Bob')
Output:
Hello Alice
Hello Bob
Return Values and return Statements:
When you call the len() function and pass it an argument such as 'Hello', the function
call evaluates to the integer value 5, which is the length of the string you passed it. In
general, the value that a function call evaluates to is called the return value of the
function.
When creating a function using the def statement, you can specify what the return value
should be with a return statement. A return statement con- sists of the following:
• The return keyword
• The value or expression that the function should return
print(spam(12))
print(spam(0))
print(spam(1))
We’ve defined a function called spam, given it a parameter, and then printed the value of that
function with various parameters to see what hap- pens. This is the output you get when you
run the previous code:
21.0
3.5
A ZeroDivisionError happens whenever you try to divide a number by zero. From the line
number given in the error message, you know that the return statement in spam() is causing an
error.
Errors can be handled with try and except statements. The code that could potentially have an
error is put in a try clause. The program execu- tion moves to the start of a following except
clause if an error happens.
You can put the previous divide-by-zero code in a try clause and have an except clause contain
code to handle what happens when this error occurs.
def spam(divideBy):
try:
return 42 / divideBy
except ZeroDivisionError:
print('Error: Invalid argument.')
print(spam(2))
print(spam(12))
print(spam(0))
print(spam(1))
Q 2 c Explain Local and Global scope with variables for each [8 Marks]
Parameters and variables that are assigned in a called function are said
to exist in that function’s local scope. Variables that are assigned outside all functions are said
to exist in the global scope. A variable that exists in a local scope is called a local variable,
while a variable that exists in the global scope is called a global variable. A variable must be
one or the other; it cannot be both local and global.
A local scope is created whenever a function is called. Any variables assigned in this function
exist within the local scope. When the function returns, the local scope is destroyed, and these
variables are forgotten. The next time you call this function, the local variables will not
remember the values stored in them from the last time the function was called.
Scopes matter for several reasons:
• Code in the global scope cannot use any local variables.
• However, a local scope can access global variables.
• Code in a function’s local scope cannot use variables in any other local scope.
• You can use the same name for different variables if they are in dif- ferent scopes. That
is, there can be a local variable named spam and a global variable also named spam.
Global Variables Can Be Read from a Local Scope
Consider the following program:
def spam():
print(eggs)
eggs = 42
spam()
print(eggs)
Local Variables Cannot Be Used in the Global Scope
Consider this program, which will cause an error when you run it:
def spam():
eggs = 31337
spam()
print(eggs)
If you run this program, the output will look like this:
Traceback (most recent call last):
File "C:/test3784.py", line 4, in <module>
print(eggs)
NameError: name 'eggs' is not defined
Q 3 a Explain the use of in and not in operator in list with examples. [ 6 Marks]
Explanation - [ 3 Marks]
Example - [ 3 Marks]
Example:
● The following program lets the user type in a pet name and then checks to see whether
the name is in a list of pets
Output:
Enter a pet name:
Muffin
I do not have a pet named Muffin
Q 3 b Explain negative Indexing, slicing, index( ), åppend( ), remove( ). pop( ), insert( ) and
sort() with suitable examples. [8 Marks]
Explanation - [ 4 Marks]
Example - [ 4 Marks]
Negative Indexing
•Indexes start at 0
•Negative index:
•-1 refers to the last index in a list
•-2 refers to the second-to-last index in a list
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[-1]
'elephant'
>>> spam[-3]
'bat'
Slicing:
•Slice can get several values from a list, in the form of a new list.
•Has two integers separated by a colon.
•First integer is the index where the slice starts.
•Second integer is the index where the slice ends.
•A slice evaluates to a new list value.
index():
append():
append() method call adds the argument to the end of
the list.
>>> spam = ['cat', 'dog', 'bat']
>>> spam.append('moose')
>>> spam
['cat', 'dog', 'bat', 'moose']
remove():
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam.remove('bat')
>>> spam
['cat', 'rat', 'elephant']
● Attempting to delete a value that does not exist in the list will result in a ValueError error.
● If the value appears multiple times in the list, only the first instance of the value will be
removed.
pop():
The pop() method removes the element at the specified position.
example:
fruits = ['apple', 'banana', 'cherry']
fruits.pop(1)
insert():
The insert() method can insert a value at any index in the list.
>>> spam = ['cat', 'dog', 'bat']
>>> spam.insert(1, 'chicken')
>>> spam
['cat', 'chicken', 'dog', 'bat']
sort():
>>> spam = [2, 5, 3.14, 1, -7]
>>> spam.sort()
>>> spam
[-7, 1, 2, 3.14, 5]
>>> spam = ['ants', 'cats', 'dogs', 'badgers', 'elephants']
>>> spam.sort()
>>> spam
['ants', 'badgers', 'cats', 'dogs', 'elephants']
Q 3 c Write about Mutable and Immutable data type in list [6 Marks]
Explanation - [ 4 Marks]
Example - [ 2 Marks]
● A mutable object is an entity whose value can be altered post its creation. Imagine it as a
whiteboard: you can write on it, erase your inscriptions, and jot something new. This
characteristic epitomizes mutable Python variables.
● Conversely, an immutable object is an entity whose value remains constant post its
creation. Visualize it as a printed book: once printed, you cannot simply erase a paragraph
and overwrite it. The words are permanent and unalterable.
● Python, being a dynamically-typed language, offers a variety of mutable and immutable
objects. Lists, dictionaries, and sets are instances of mutable objects, while numbers,
strings, and tuples are instances of immutable objects.
Lists Numbers
Dictionaries Strings
Sets Tuples
# Dictionary
my_dict = {'name': 'John', 'age': 30}
my_dict['age'] = 31 # The dictionary now becomes {'name': 'John', 'age': 31}
# Set
my_set = {1, 2, 3}
my_set.add(4) # The set now becomes {1, 2, 3, 4}
Q 4 a Explain the following list methods with examples:
i) index () ii) append( ) iii) insert() iv) sort() v) reverse() vi) List concatenation and
Replication [10 Marks]
Explanation - [ 6 Marks]
Example - [ 4 Marks]
i) index():
The index() method returns the position at the first occurrence of the specified value.
ii) append():
append() method call adds the argument to the end of
the list.
>>> spam = ['cat', 'dog', 'bat']
>>> spam.append('moose')
>>> spam
['cat', 'dog', 'bat', 'moose']
iii) insert():
The insert() method can insert a value at any index in the list.
>>> spam = ['cat', 'dog', 'bat']
>>> spam.insert(1, 'chicken')
>>> spam
['cat', 'chicken', 'dog', 'bat']
iv) sort():
>>> spam = [2, 5, 3.14, 1, -7]
>>> spam.sort()
>>> spam
[-7, 1, 2, 3.14, 5]
>>> spam = ['ants', 'cats', 'dogs', 'badgers', 'elephants']
>>> spam.sort()
>>> spam
['ants', 'badgers', 'cats', 'dogs', 'elephants']
v) reverse():
The reverse() method reverses the sorting order of the elements.
Q 4 b : Develop a program to read the student details like Name, USN and Marks in three
subjects: Display the student details, total marks and percentage with suitable messages.
[ 10 Marks]
Full Program- [7 Marks]
Logic-[3 Marks]
total = sub01+sub02+sub03
per = (total/300)*100
Q 5 a Illustrate with example opening of a life with open( ) function, reading the contents of
the file with read() and writing to files with write (). [10 Marks]
Q5 b Explain how to save våriable with the shelve module. [10 Marks]
Q 6 a Explain the following string methods with examples
i) isalpha() ii) isalnum() iii)isdecimal() iv)isspace() v) istitle() [10 Marks]
➢ These expressions test whether the first string (the exact string, case sensitive) can be
found within the second string.
➢ Of course, if something outside of your program changes the clipboard contents, the
paste() function will return it.
Q 7 a What are Assertions? Write the conteñts of an assert statement. Explain them with
examples. [10 Marks]
Assertions
An assertion is a sanity check to make sure your code isn’t doing something
obviously wrong. These sanity checks are performed by assert statements. If
the sanity check fails, then an AssertionError exception is raised. In code, an
assert statement consists of the following:
• The assert keyword
• A condition (that is, an expression that evaluates to True or False)
• A comma
• A string to display when the condition is False
For example, enter the following into the interactive shell:
Q 7b Develop a program with a function named DivExp which takes Two parameters a, b
and return_ a, vàlde c(c = a/b), write suitable ássertion for a >0 in function DivExp and
/raise an exception for when b =0. Develop a suitable program which reads two values from
the console and calls a function DivExp. [10 Marks]
def DivExp(a, b):
# Assertion to ensure a > 0
assert a > 0, "Value of 'a' must be greater than 0"
# Main program
def main():
a, b = read_values()
try:
result = DivExp(a, b)
print(f"The result of a/b is: {result}")
except AssertionError as e:
print(e)
except ValueError as e:
print(e)
The shutil (or shell utilities) module has functions to let you copy, move, rename, and delete files
in your Python programs. To use the shutil functions, you will first need to use import shutil. The
shutil module provides functions for copying files, as well as entire folders. Calling
shutil.copy(source, destination) will copy the file at the path source to the folder at the path
destination. (Both source and destination are strings.) If destination is a filename, it will be used
as the new name of the copied file. This function returns a string of the path of the copied file.
While shutil.copy() will copy a single file, shutil.copytree() will copy an entire folder and every
folder and file contained in it. Calling shutil.copytree(source ,destination) will copy the folder at
the path source, along with all of its files and subfolders, to the folder at the path destination.
>>> import shutil, os
>>> os.chdir('C:\\')
>>> shutil.copy('C:\\spam.txt', 'C:\\delicious')
'C:\\delicious\\spam.txt'
>>> shutil.copy('eggs.txt', 'C:\\delicious\\eggs2.txt')
'C:\\delicious\\eggs2.txt'
>>> shutil.copytree('C:\\bacon', 'C:\\bacon_backup')
'C:\\bacon_backup'
>>>import shutil
>>>shutil.move('C:\\bacon.txt', 'C:\\eggs')
'C:\\eggs\\bacon.txt'
iii) Permanently deleting file & Folders
You can delete a single file or a single empty folder with functions in the os module, whereas to
delete a folder and all of its contents, you use the shutil module.
• Calling os.unlink(path) will delete the file at path.
• Calling os.rmdir(path) will delete the folder at path. This folder must be empty of any files or
folders.
• Calling shutil.rmtree(path) will remove the folder at path, and all files and folders it contains
will also be deleted.
Code:
import os
for filename in os.listdir():
if filename.endswith('.txt'):
os.unlink(filename)
The program will stay paused until you press one of the five buttons in the Debug
Control window: Go, Step, Over, Out, or Quit.
Go Clicking the Go button will cause the program to execute normally until it terminates or
reaches a breakpoint. If you are done debugging and want the program to continue normally,
click the Go button.
Step Clicking the Step button will cause the debugger to execute the next line of code and then
pause again. The Debug Control window’s list of global and local variables will be updated if
their values change. If the next line of code is a function call, the debugger will “step into” that
function and jump to the first line of code of that function.
Over Clicking the Over button will execute the next line of code, similar to the Step button.
However, if the next line of code is a function call, the Over button will “step over” the code in
the function. The function’s code will be executed at full speed, and the debugger will pause as
soon as the function call returns.
Out Clicking the Out button will cause the debugger to execute lines of code at full speed until it
returns from the current function. If you have stepped into a function call with the Step button
and now simply want to keep executing instructions until you get back out, click the Out button
to “step out” of the current function call.
Quit If you want to stop debugging entirely and not bother to continue executing the rest of the
program, click the Quit button. The Quit button will immediately terminate the program. If you
want to run your program normally again, select Debug 4 Debugger again to disable the
debugger.
Q 9 a Explain about class and objects [ 10 Marks]
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.
Defining a class named Point creates a class object.
>>> Point
<class __main__.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
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). Every object is an instance of some
class, so “object” and “instance” are interchangeable.
You can assign values to an instance using dot notation:
>>> blank.x = 3.0
>>> blank.y = 4.0
though, we are assigning values to named elements of an object. These elements are called
attributes. A state diagram that shows an object and its attributes is called an object diagram.
The variable blank refers to a Point object, which contains two attributes. Each attribute refers to
a floating-point number. You can read the value of an attribute using the same syntax
The development plan I am demonstrating is called “prototype and patch”. For each function, I
wrote a prototype that performed the basic calculation and then tested it, patching errors along
the way.
This approach can be effective, especially if you don’t yet have a deep understanding of the
problem. But incremental corrections can generate code that is unnecessarily complicated—since
it deals with many special cases—and unreliable—since it is hard to know if you have found all
the errors.
An alternative is designed development, in which high-level insight into the problem can make
the programming much easier. In this case, the insight is that a Time object is really a three-digit
number in base 60 (see http://en.wikipedia.org/wiki/Sexagesimal.)! The second attribute is the
“ones column”, the minute attribute is the “sixties column”, and the hour attribute is the
“thirty-six hundreds column”.
When we wrote add_time and increment, we were effectively doing addition in base 60, which is
why we had to carry from one column to the next.
This observation suggests another approach to the whole problem—we can convert Time objects
to integers and take advantage of the fact that the computer knows how to do integer arithmetic.
Here is a function that converts Times to integers:
def time_to_int(time):
minutes = time.hour * 60 + time.minute
seconds = minutes * 60 + time.second
return seconds
And here is a function that converts an integer to a Time (recall that divmod divides the first
argument by the second and returns the quotient and remainder as a tuple).
def int_to_time(seconds):
time = Time()
minutes, time.second = divmod(seconds, 60)
time.hour, time.minute = divmod(minutes, 60)
return time
You might have to think a bit, and run some tests, to convince yourself that these functions are
correct. One way to test them is to check that time_to_int(int_to_time(x)) == x for many values
of x. This is an example of a consistency check.
Once you are convinced they are correct, you can use them to rewrite add_time:
def add_time(t1, t2):
seconds = time_to_int(t1) + time_to_int(t2)
return int_to_time(seconds)
This version is shorter than the original, and easier to verify. As an exercise, rewrite increment
using time_to_int and int_to_time.
In some ways, converting from base 60 to base 10 and back is harder than just dealing with
times. Base conversion is more abstract; our intuition for dealing with time values is better.
But if we have the insight to treat times as base 60 numbers and make the investment of writing
the conversion functions (time_to_int and int_to_time), we get a program that is shorter, easier to
read and debug, and more reliable.
It is also easier to add features later. For example, imagine subtracting two Times to find the
duration between them. The naive approach would be to implement subtraction with borrowing.
Using the conversion functions would be easier and more likely to be correct. Ironically,
sometimes making a problem harder (or more general) makes it easier (because there are fewer
special cases and fewer opportunities for error).
_ _init_ _ ( ) method:
The init method (“initialization”) is a special method that gets invoked when an object is
instantiated. Its full name is _ _init_ _ (two underscore characters, followed by init, and then two
more underscores).
_ _str_ _ ( ) method
__str__ is a special method, like __init__, that is supposed to return a string representation of an
object. When you print an object, Python invokes the str method