QP-2025
QP-2025
1.a Explain basic datatypes like int, float, double and string with an example [6 Marks]
Ans:
Explanation - [ 3 Marks]
Example & Code-[3 Marks]
Example:
num = 10
print(type(num)) # Output: <class 'int'>
○
2. Floating-Point (float)
○ Represents numbers with decimal points, including fractions.
○ Floats (and doubles) are used for precise calculations.
Example:
num = 10.5
print(type(num)) # Output: <class 'float'>
○
3. Double (double)
○ Similar to float but with more precision.
○ Note: In Python, float acts as double since Python dynamically allocates
precision.
Example:
num = 10.123456789012345
print(type(num)) # Output: <class 'float'>
○
4. String (str)
○ Represents a sequence of characters, enclosed in single or double quotes.
○ Strings store and manipulate textual data.
Example:
python
CopyEdit
text = "Hello, World!"
PROGRAM:
def factorial(n):
if n == 0 or n==1:
return 1
return n * factorial(n-1)
N = int(input("Enter N"))
R=int(input("Enter R"))
if N>R:
bin=factorial(N)/(factorial(R)*factorial(N-R))
OUTPUT:
Enter N 3
Enter R 5
Factorial of 5 is 120
Factorial of 3 is 6
Binomial of 3 5 is 10.0
2. a. Define Functions. Explain how to pass parameters through the function with return statement. [6
Marks]
Ans:
Explanation - [ 3 Marks]
Example & Code-[3 Marks]
b. What is exception? How exception are handled in python? Write a program to solve divide by zero
exception [6 Marks]
Ans:
Explanation - [ 3 Marks]
Example & Code-[3 Marks]
Getting an error, or exception, in your Python program means the entire program will crash.
You don’t want this to happen in real-world pro- grams. Instead, you want the program to
detect errors, handle them, and then continue to run.
For example, consider the following program, which has a “divide-by-zero” error. Open a new
file editor window and enter the following code, saving it as zeroDivide.py:
def spam(divideBy):
return 42 / divideBy
print(spam(2))
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))
c. Develop a program to generate Fibonacci sequence of length (N). Read N from the console.
[8 Marks]
Ans:
Full Program- [5 Marks]
Logic-[3 Marks]
Program:
while(i<=n):
sum=a+b
print(a)
a=b
b=sum
i=i+1
OUTPUT:
enter the number 5
fibonacci series
0
1
1
2
3
● Augmented shorthand assignment operators are a concise way to update the value of a
variable by applying an operation and assigning the result back to the same variable.
● These operators combine arithmetic or bitwise operations with assignment, reducing
redundancy in code.
● Example:
variable op= expression
+= a=a+b a+=b
-= a=a-b a-=b
*= a=a*b a*=b
/= a=a/b a/=b
%= a=a%b a%=b
^= a=a^b a^=b
a=8
a *= 2 # Equivalent to a = a * 2
print(a) # Output: 16
b = 20
b //= 3 # Equivalent to b = b // 3
print(b) # Output: 6
b. Explain different type of methods like append(), remove(), sort(), pop() in python programming
list. [7 Marks]
Ans:
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.
sort(): The sort() method will sort the items inside the list in ascending order
>>> 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']
pop():
The pop() method removes the element at the specified position.
example:
fruits = ['apple', 'banana', 'cherry']
fruits.pop(1)
PROGRAM:
OUTPUT:
Dictionaries have a get() method that takes two arguments: the key of the value to
retrieve and a fallback value to return if that key does not exist.
The setdefault() method offers a way to do this in one line of code. The first argument
passed to the method is the key to check for, and the second argument is the value to set at
that key if the key does not exist. If the key does exist, the setdefault() method returns the
key’s value.
The first time setdefault() is called, the dictionary in spam changes to {'color':
'black', 'age': 5, 'name': 'Pooka'}. The method returns the value 'black' because this
is now the value set for the key 'color'. When spam.setdefault('color', 'white') is
called next, the value for that key is not changed to 'white' because spam already
has a key named 'color'.
program that counts the number of occurrences of each let- ter in a string.
message = 'It was a bright cold day in April, and the clocks were striking thirteen.'
count = {}
for character in message:
count.setdefault(character, 0)
count[character] = count[character] + 1
print(count)
Output:
{' ': 13, ',': 1, '.': 1, 'A': 1, 'I': 1, 'a': 4, 'c': 3, 'b': 1, 'e': 5, 'd': 3, 'g': 2, 'i':
6, 'h': 3, 'k': 2, 'l': 3, 'o': 2, 'n': 4, 'p': 1, 's': 3, 'r': 5, 't': 6, 'w': 2, 'y': 1}
Ans 4b.Develop a python to print area of Rectangle?
import numpy as np
x = np.array(5) # length
y = np.array(8) # width
area = np.multiply(x, y)
print(area)
Output:
40
Ans 4C:Define Pretty printing.How does pretty print work in python with an example?
Ans:Pretty Printing
If you import the pprint module into your programs, you’ll have access to the pprint()
and pformat() functions that will “pretty print” a dictionary’s values. This is helpful
when you want a cleaner display of the items in a dictionary than what print()
provides.
program that counts the number of occurrences of each let- ter in a string.
import pprint
message = 'It was a bright cold day in April, and the clocks were striking
thirteen.' count = {}
for character in message:
count.setdefault(character, 0)
count[character] = count[character] + 1
pprint.pprint(count)
This time, when the program is run, the output looks much cleaner,
with the keys sorted.
pprint.pprint(someDictionaryValue)
print(pprint.pformat(someDictionaryValue))
Module-3
5a.Explain useful string functions like:
i.capitalize
The capitalize() method returns a string where the first character is upper case, and the rest is
lower case.
Syntax
string.capitalize()
ii.count
The count() method returns the number of elements with the specified value.
Syntax
list.count(value)
Iii.find
The find() method finds the first occurrence of the specified value.
Syntax
Iv.lower
The lower() method returns a string where all characters are lower case.
Syntax
string.lower()
V.upper
The upper() method returns a string where all characters are in upper case.
Syntax
string.upper()
Vii.repalce
The replace() method replaces a specified phrase with another specified phrase.
Syntax
Ans:
s = "malayalam" # string
if s == s[::-1]:
print("Yes")
else:
print("No")
OUTPUT:yes
5c.Explain: isapla,isalnum,isspace
isalpha:
The isalpha() method returns True if all the characters are alphabet letters (a-z).
txt = "Company10"
x = txt.isalpha()
print(x)
OUTPUT:
False
Isalnum
The isalnum() method returns True if all the characters are alphanumeric, meaning alphabet letter
(a-z) and numbers (0-9).
x = txt.isalnum()
print(x)
OUTPUT:
Yes
isspace:
The isspace() method returns True if all the characters in a string are whitespaces, otherwise False.
txt = " s "
x = txt.isspace()
print(x)
OUTPUT:
Yes
Ans:
The os.path module also has some useful functions related to absolute and relative paths:
Calling os.path.abspath(path) will return a string of the absolute path of the argument. This is an easy
way to convert a relative path into an absolute one.
Calling os.path.isabs(path) will return True if the argument is an absolute path and False if it is a
relative path.
Calling os.path.relpath(path, start) will return a string of a relative path from the start path to path.
If start is not provided, the current working directory is used as the start path.
Try these functions in the interactive shell:
>>> os.path.abspath('.')
'C:\\Users\\Al\\AppData\\Local\\Programs\\Python\\Python37'
>>> os.path.abspath('.\\Scripts')
'C:\\Users\\Al\\AppData\\Local\\Programs\\Python\\Python37\\Scripts'
>>> os.path.isabs('.')
False
>>> os.path.isabs(os.path.abspath('.'))
True
6b.Explain the concept of file path. And also explain the Difference between absolute and relative
path.
A file has two key properties: a filename and a path. The path specifies the location of a file on
the computer. For example, there is a file on my Windows laptop with the filename project.docx
in the path C:\Users\Al\Documents. The part of the filename after the last period is called the
file’s extension and a file’s type. The filename project.docx is a Word document, and Users, Al,
and Documents all refer to folders(also called directories). Folders can contain files and other
folders. For example, project.docx is in the Documents folder, which is inside the Al folder,
which is inside the Users folder
The C:\ part of the path is the root folder, which contains all other folders. On Windows, the root
folder is named C:\ and is also called the C: drive.
There are also the dot (.) and dot-dot (..) folders. These are not real folders
but special names that can be used in a path. A single period (“dot”)
for a folder name is shorthand for “this directory.” Two periods (“dot-dot”)
Below is an example of some folders and files. When the current working
directory is set to C:\bacon, the relative paths for the other folders and files are
Ans 7(a) Python program for backing up a folder into a zip file
import os
import shutil
if not os.path.exists(source_folder):
return
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
backup_filename = f"backup_{timestamp}.zip"
try:
except Exception as e:
# Example usage
backup_location = "path/to/backup/location" # Change this to where you want to store the backup
backup_folder(source_folder, backup_location)
Ans 7(b) In Python's shutil module, shutil.copy() and shutil.copytree() serve
distinct purposes for copying files and directories:
● shutil.copy():
○ Purpose: Copies a single file from a source to a destination.
○ Usage: shutil.copy(src,
dst)stackoverflow.com+2blog.csdn.net+2realpython.com+2
■ src: Path to the source file.
■ dst: Destination path or directory.
○ Behavior:
■ If dst is a directory, the source file is copied into this directory with its
original name.
■ If dst is a filename, the source file is copied and renamed to the specified
filename.
○ Metadata: Copies the file's content and permissions but does not preserve other
metadata like timestamps.sopriza.com+2realpython.com+2designgurus.io+2
● shutil.copytree():
○ Purpose: Recursively copies an entire directory tree (a directory and all its
subdirectories and files) to a new
location.tracedynamics.com+1realpython.com+1tracedynamics.com+1
○ Usage: shutil.copytree(src, dst,
dirs_exist_ok=False)designgurus.io+5blog.csdn.net+5techgeekbuzz.com+5
■ src: Path to the source directory.
■ dst: Destination directory path.
■ dirs_exist_ok: If set to True, allows copying into an existing directory;
defaults to False, which raises an error if the destination exists.
○ Behavior:
■ Creates the destination directory and recursively copies all files and
subdirectories from the source to the destination.
■ Raises an error if the destination directory already exists and
dirs_exist_ok is False.
○ Metadata: Attempts to preserve the metadata of files and directories, such as
timestamps and permissions.
Key Differences:
● Scope:
○ shutil.copy(): Designed for copying individual
files.scribd.com+1coderslegacy.com+1scribd.com+1
○ shutil.copytree(): Intended for copying entire directories, including all nested
files and subdirectories.
● Destination Requirements:
○ shutil.copy(): The destination can be an existing directory or a new filename.
○ shutil.copytree(): The destination directory must not already exist unless
dirs_exist_ok=True is
specified.designgurus.io+1coderslegacy.com+1designgurus.io+1
● Metadata Handling:
○ shutil.copy(): Does not preserve all metadata; for full metadata preservation,
use shutil.copy2().
○ shutil.copytree(): Preserves metadata by default, using shutil.copy2()
for copying files.
Example;
import shutil
shutil.copytree("source_folder", "destination_folder")
● The shutil.move() function moves files or directories from one location to another
● Example:
import shutil
# Move a file
shutil.move("file.txt", "new_directory/file.txt")
# Move a folder
shutil.move("source_folder", "destination_folder")
● The os and shutil modules provide methods to delete files and folders permanently.
● os.remove() is used to delete a file.
● shutil.rmtree() is used to delete a folder along with its contents
Example:
import os
import shutil
# Delete a file
os.remove("file.txt")
os.rmdir("empty_folder")
shutil.rmtree("folder_to_delete")
Ans- 8(a) Assertion (assert statement)
Example: x = 10
assert x < 5, "x should be less than 5" # Fails and raises AssertionError
Example:
def check_age(age):
print("Access granted.")
ANs- 8(b)
The logging module in Python provides a flexible framework for emitting log messages from
applications. Here are some benefits of using it:
Example:
import logging
# Configure logging
logging.basicConfig(
try:
result = 10 / 0
except ZeroDivisionError:
Ans 8 (c )
if b == 0:
return a / b
try:
result = DivExp(a, b)
print(f"Result: {result}")
except ZeroDivisionError as e:
print(f"Error: {e}")
except AssertionError as e:
except ValueError:
class Complex:
self.real = real
self.imag = imag
def __str__(self):
def add_complex_numbers(complex_list):
result = Complex(0, 0)
for c in complex_list:
result += c
return result
complex_numbers = []
for i in range(N):
complex_numbers.append(Complex(real, imag))
sum_result = add_complex_numbers(complex_numbers)
Types of Inheritance
1. Single Inheritance – One child class inherits from a single parent class.
2. Multiple Inheritance – A child class inherits from multiple parent classes.
3. Multilevel Inheritance – A child class inherits from another child class.
4. Hierarchical Inheritance – Multiple child classes inherit from a single parent class.
5. Hybrid Inheritance – A combination of two or more types of inheritance.
# Parent Class
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return "I make a sound"
# Creating objects
animal = Animal("Generic Animal")
dog = Dog("Buddy")
# Accessing methods
print(f"{animal.name}: {animal.speak()}") # Generic Animal: I make a sound
print(f"{dog.name}: {dog.speak()}") # Buddy: Bark! Bark!
Explanation
Ans 9 c
class Person:
def __init__(self, name, age):
"""Constructor to initialize name and age"""
self.name = name
self.age = age
def __str__(self):
"""Returns a readable string representation of the object"""
return f"Person(Name: {self.name}, Age: {self.age})"
# Creating an object
person1 = Person("Alice", 25)
Output:
Person(Name: Alice, Age: 25)
Ans 10 (a)
class Rectangle:
"""Class to represent a rectangle."""
def get_center(self):
"""Method to calculate the center coordinates of the rectangle."""
center_x = self.x + (self.width / 2)
center_y = self.y + (self.height / 2)
return (center_x, center_y)
Ans 10 (b) When an object is printed using the print() function, Python looks for a __str__()
method in the class. If it is defined, it returns a user-friendly string representation of the object. If
__str__() is not defined, Python falls back to __repr__() or prints the default memory
address.
class Person:
def __init__(self, name, age):
"""Constructor to initialize name and age"""
self.name = name
self.age = age
def __str__(self):
"""Returns a user-friendly string representation"""
return f"Person(Name: {self.name}, Age: {self.age})"
# Creating an object
person1 = Person("Alice", 25)
# Printing the object
print(person1) # Calls __str__() method automatically
OUTPUT:
Person(Name: Alice, Age: 25)
Ans 10 (c )
class ComplexNumber:
def __init__(self, real, imag):
self.real = real
self.imag = imag
def __str__(self):
return f"{self.real} + {self.imag}i"
# Creating objects
c1 = ComplexNumber(2, 3)
c2 = ComplexNumber(1, 4)
# Using overloaded '+' operator
c3 = c1 + c2 # Calls __add__()
print(c3) # Output: 3 + 7i
Operator riding
class Parent:
def show(self):
print("Parent class method")
class Child(Parent):
def show(self):
print("Child class method (Overriding Parent)")
# Creating objects
p = Parent()
c = Child()
Key Takeaways