Pip QP
Pip QP
Ans:
Python defines type conversion functions to directly convert one data type to
another data type. There are two types of Type Conversion in Python:
-eg:-
x = 10 => int
z=x+y
print(z)
-eg:-
c = int(s)
e = float(s)
Ans:
x=int(input());
y=int(input());
else:
Ans:
LIST TUPLE
Lists are mutable Tuples are immutable
The implication of iterations is The implication of iterations is
Time-consuming comparatively faster.
Ans:
def main():
words = line.split()
if palindromes:
else:
if __name__ == "__main__":
main()
Ans:
-An event loop continuously monitors events and dispatches them to the
appropriate event handlers.
Ans:
import turtle
hexagon_turtle = turtle.Turtle()
hexagon_turtle.speed(1)
for _ in range(6):
hexagon_turtle.forward(100)
hexagon_turtle.right(60)
turtle.done()
Ans:
self.width = width
self.height = height
self.width = width
self.height = width
else:
self.width = 0
self.height = 0
def area(self):
rect2 = Rectangle(7)
rect3 = Rectangle()
Ans:
def make_sound(self):
class Dog(Animal):
def make_sound(self):
print("Woof!")
class Cat(Animal):
def make_sound(self):
print("Meow!")
dog = Dog()
cat = Cat()
dog.make_sound()
cat.make_sound()
Ans:
print("Array:", arr)
print("Shape:", arr.shape)
print("Size:", arr.size)
Output:
Array: [[1 2 3]
[4 5 6]]
Shape: (2, 3)
Size: 6
Number of Dimensions: 2
Ans:
Flask is a lightweight web framework for Python that simplifies web development
by providing tools and libraries for building web applications. Here's how Flask is
used in web development:
1. Routing: Flask allows developers to define URL routes and associate them
with specific functions, known as view functions.
2. Template Rendering: Flask supports template engines such as Jinja2, which
allows developers to create dynamic HTML templates.
3. Request Handling: Flask provides convenient ways to access and process
incoming HTTP requests.
4. Response Generation: Flask enables developers to generate HTTP
responses dynamically.
5. Middleware: Flask allows developers to plug in middleware components to
handle cross-cutting concerns such as authentication, logging, or error
handling.
6. Extension Ecosystem: Flask has a rich ecosystem of extensions that provide
additional functionality for common tasks such as user authentication,
database integration, caching, and more.
11 A)
Ans:
When used for a software development process, the waterfall methodology has seven
stages:
5. Testing. This is when quality assurance, unit, system and beta tests identify
issues that must be resolved. This may cause a forced repeat of the coding
stage for debugging. If the system passes integration and testing, the
waterfall continues forward.
Write a Python program to print all numbers between 100 and 1000 whose sum
of digits is divisible by 9.
Ans:
def main():
numbers = []
digit_sum = 0
digit_sum += int(digit)
if digit_sum % 9 == 0:
numbers.append(num)
divisible by 9:")
print(numbers)
if __name__ == "__main__":
main()
12 A)
Ans:
The range() function returns a sequence of numbers.
Default is 0
x = range(3, 6)
for n in x:
print(n) => 3 4 5
x = range(3, 20, 2)
for n in x:
print(n) => 3 5 7 9 11 13 15 17 19
12 B)
Ans:
def main():
# Input number from user
number = int(input("Enter a number: "))
factors = []
# Find and store factors of 2
while number % 2 == 0:
factors.append(2)
number //= 2
if __name__ == "__main__":
main()
13 A)
Ans:
import math
def main():
n=int(input())
x=9
sum = 1
term = 1
y=2
for i in range(1, n):
factorial = 1
factorial = factorial * j
term *= (-1)
m = term * (x ** y) / factorial
sum += m
y += 2
print(f"{sum:.4f}")
if __name__ == "__main__":
main()
13 B)
Ans:
i. get( ):
- Returns the value for a specified key in the dictionary.
- If the key is not found, it returns a default value (None by default).
ii. keys( ):
- Returns a view object that displays a list of all the keys in the dictionary.
iii. pop( ):
- Removes the item with the specified key from the dictionary
iv. update( ):
- Updates the dictionary with the elements from another dictionary
or iterable object.
v. values( ):
- Returns a view object that displays a list of all the values
in the dictionary.
vi. items( ):
- Returns a view object that displays a list of tuples containing
Example:
my_dict = {"name": "John", "age": 30, "city": "New York"}
print(my_dict.get("name")) # Output: John
print(my_dict.get("salary")) # Output: None
print(my_dict.keys()) # Output: dict_keys(['name', 'age', 'city'])
removed_value = my_dict.pop("age")
print(removed_value) # Output: 30
print(my_dict) # Output: {'name': 'John', 'city': 'New York'}
update_dict = {"age": 30, "salary": 50000}
my_dict.update(update_dict)
print(my_dict) # Output: {'name': 'John', 'city': 'New York', 'age': 30, 'salary':
50000}
print(my_dict.values()) # Output: dict_values(['John', 'New York',30,50000])
print(my_dict.items()) # Output: dict_items([('name', 'John'), ('city', 'New York'),
('age', 30),(‘salary’,50000)])
14 A)
Ans:
if num >= 1:
DecimalToBinary(num // 2)
DecimalToBinary(dec)
14 B)
Write a python program to read a text file and store the count of occurrences of
each character in a dictionary
Ans:
def main():
file_path = 'file.txt'
char_count = {}
if __name__ == "__main__":
main()
15 A)
Ans:
def grayscale(image):
for y in range(image.getHeight):
for x in rangeimage.get Width):
(r, g, b) = image.getPixel(x, y)
r = intr * 0.299)
g = int(g * 0.587)
b = int(b* 0.114)
lum = r +g+b
image.setPixel(x, y, (lum, lum, lum))
15 B)
Ans:
Turtle Graphics
The sheet of paper is a window on a display screen, and the turtle is an icon, such as an
arrowhead. At any given moment in time, the turtle is located at a specific position in
the window. This position is specified with (x, y) coordinates. The coordinate system for
Turtle graphics is the standard Cartesian system, with the origin (0, 0) at the center of a
window. The turtle's initial position is the origin which is also called the home. An
equally important attribute of a turtle is its heading, or the direction in which it currently
faces. The turtle's initial heading is 0 degrees, or due east on its map. The degrees of the
heading increase as it turns to the left, so 90 degrees is due north.
Turtle Attributes:
Heading -> Specified in degrees, the heading or direction increases in value as the turtle
turns to the left, or counterclockwise. Conversely, a negative quantity of degrees
indicates a right, or clockwise, turn. The turtle is initially facing east, or 0 degrees. North
is 90 degrees
Color -> Initially black, the color can be changed to any of more than 16 million other
colors.
Width -> This is the width of the line drawn when the turtle moves. The initial width is 1
pixel.
Down -> This attribute, which can be either true or false, controls whether the turtle's
pen is up or down. When true (that is, when the pen is down), the turtle draws a line
when it moves. When false (that is, when the pen is up), the turtle can move without
drawing a line
Turtle Methods :-
t = Turtle() -> Creates a new Turtle object and opens its window.
t.home () -> Moves t to the center of the window and then points t east.
t.left(degrees) t.right(degrees) -> Rotates t to the left or the right by the specified
degrees.
Write Python GUI program to input two strings and output a concatenated string
when a button is pressed.
Ans:
import tkinter as tk
def concatenate_strings():
string1 = entry1.get()
string2 = entry2.get()
root = tk.Tk()
root.title("String Concatenation")
entry1 = tk.Entry(root)
entry2 = tk.Entry(root)
16. b)
17. a)
Ans:
Abstract classes in Python are classes that cannot be instantiated on their own
and are meant to be subclassed. They typically contain one or more abstract
methods, which are methods without implementations. Abstract classes serve as
templates for concrete subclasses to implement their own versions of the
abstract methods. Here's an illustration of how abstract classes are used in
Python:
class Shape(ABC):
@abstractmethod
def area(self):
pass
@abstractmethod
def perimeter(self):
Pass
class Rectangle(Shape):
self.width = width
self.height = height
def area(self):
def perimeter(self):
class Circle(Shape):
self.radius = radius
def area(self):
def perimeter(self):
try:
except Exception as e:
print("Error:", e)
rectangle = Rectangle(5, 4)
circle = Circle(3)
17. b)
Define a class Student in Python with attributes to store the roll number, name
and marks of three subjects for each student. Define the following methods:
Ans:
class Student:
def __init__(self):
self.roll_number = None
self.name = None
def read_data(self):
for i in range(3):
def compute_total(self):
return sum(self.marks)
def print_details(self):
print("Roll Number:", self.roll_number)
print("Name:", self.name)
for i in range(3):
student1 = Student()
student1.read_data()
student1.print_details()
18. a)
Explain, with the help of suitable examples, the different types of inheritance.
Ans:
1. Single Inheritance
def speak(self):
print("Animal speaks")
class Dog(Animal):
def bark(self):
print("Dog barks")
dog = Dog()
dog.speak()
dog.bark()
2. Multiple Inheritance
Multiple inheritance occurs when a subclass inherits from more than one
superclass. In this type of inheritance, the subclass inherits attributes and
methods from all the superclasses.
Eg. class Flyable:
def fly(self):
print("Can fly")
class Swimmable:
def swim(self):
print("Can swim")
pass
duck = Duck()
duck.fly()
duck.swim()
3. Multilevel Inheritance
def speak(self):
print("Animal speaks")
class Dog(Animal):
def bark(self):
print("Dog barks")
class Labrador(Dog):
def color(self):
print("Labrador is brown")
labrador = Labrador()
4. Hierarchical Inheritance
def speak(self):
print("Animal speaks")
class Dog(Animal):
def bark(self):
print("Dog barks")
class Cat(Animal):
def meow(self):
print("Cat meows")
dog = Dog()
cat = Cat()
5. Hybrid Inheritance
def speak(self):
print("Animal speaks")
class Flyable:
def fly(self):
print("Can fly")
Pass
bird = Bird()
bird.speak()
bird.fly()
18. b)
Write a Python program to demonstrate the use of try, except and finally blocks.
Ans:
1. try: The `try` block is used to enclose the code that might raise an
exception. When an exception occurs within the `try` block, Python
searches for an associated `except` block to handle the exception.
2. except: The `except` block is used to handle exceptions that occur within
the corresponding `try` block. It allows you to specify how the program
should respond to different types of exceptions. If an exception occurs in
the `try` block, Python looks for a matching `except` block. If a match is
found, the code inside the `except` block is executed.
3. finally: The `finally` block is always executed regardless of whether an
exception occurs or not. It is typically used to perform cleanup actions,
such as closing files or releasing resources. The `finally` block is executed
even if there is an unhandled exception or a return statement within the
`try` or `except` block.
try:
result = x / y
except ZeroDivisionError:
print("Result:", result)
finally:
19. a)
Consider a CSV file ‘weather.csv’ with the following columns (date, temperature,
humidity, windSpeed, precipitationType, place, weather {Rainy, Cloudy, Sunny}).
Write commands to do the following using Pandas library.
Ans:
import pandas as pd
weather_data = pd.read_csv('weather.csv')
print(weather_data.head(10))
max_temp = weather_data['temperature'].max()
min_temp = weather_data['temperature'].min()
print(places_less_than_28)
cloudy_places = weather_data[weather_data['weather'] ==
'Cloudy']['place'].unique()
print(cloudy_places)
weather_frequency = weather_data['weather'].value_counts().sort_index()
print(weather_frequency)
plt.xlabel('Date')
plt.ylabel('Temperature (°C)')
plt.show()
19. b)
Ans:
1. Using Python Lists or Tuples: You can create a NumPy array from a Python
list or tuple using the `np.array()` function.
4. Using `np.zeros()` and `np.ones()`: These functions create arrays filled with
zeros or ones, respectively.
normal_random_arr = np.random.randn(3)
7. Using `np.diag()`: This function creates a diagonal array from a given array
or list of values.
8. Using Custom Functions: You can create arrays using custom functions like
`np.fromfunction()`, which constructs arrays by executing a function over
each coordinate.
return 3 * i + j
20. a)
Write Python program to write the data given below to a CSV file.
import csv
data = [
['Sl No.', 'Title', 'Author', 'Available', 'Count'],
filename = 'books.csv'
writer = csv.writer(file)
writer.writerows(data)
20. b)
Write a Python program to input two matrices and perform the following
operations using numpy and display the results:
Ans:
import numpy as np
matrix = []
for i in range(rows):
return np.array(matrix)
rows, cols = map(int, input("Enter dimensions (rows and columns) of the matrices:
").split())
transpose_matrix1 = np.transpose(matrix1)
transpose_matrix2 = np.transpose(matrix2)
print("\nResults:")
print(addition_result)
print(subtraction_result)
print(multiplication_result)
print(transpose_matrix1)
print(transpose_matrix2)