Python Long Question Answer
Python Long Question Answer
1. (a)List various types of operators in Python and write any 4 types of operators.
Arithmetic Operators: Arithmetic operators are used to perform mathematical operations like
addition, subtraction, multiplication, division, etc.
• Example
x = 10
y=3 OUTPUT:
print(x + y) # Addition 13
print(x - y) # Subtraction 7
print(x * y) # Multiplication 30
print(x / y) # Division 3.3333333333333335
Comparison (Relational) Operators: Comparison operators are used to compare two values or
operands and return True or False based on the comparison.
• Example:
a = 10
b = 20 OUTPUT:
print(a == b) # Equal to False
print(a != b) # Not equal to True
print(a > b) # Greater than False
print(a < b) # Less than True
• Example:
x = 10 # Assigns 10 to x
y += 5 # Equivalent to y = y + 5
z *= 2 # Equivalent to z = z * 2
Logical Operators: Logical operators are used to combine conditional statements and return True
or False.
• Example:
a = True
b = False OUTPUT:
print(a and b) #Logical AND False
True
print(a or b) # Logical OR
False
print(not a) # Logical NOT
Bitwise Operators: Bitwise operators perform operations on binary representations of integers.
• Example:
Identity Operators: Identity operators are used to compare the memory locations of two objects.
• Example:
x = [1, 2, 3] OUTPUT:
y = [1, 2, 3] False
print(x is y) # False True
print(x is not y) # True
Unary Operators: Unary operators are used to perform operations on a single operand.
• Example:
x = 10
print(-x) # Unary minus OUTPUT:
print(+x) # Unary plus -10
10
z *= 4 # Equivalent to z = z * 4
Bitwise Operators:
Bitwise AND (&):
• Performs a bitwise AND operation on the binary representations of two integers.
• Example
Addition:
def addition(x,
y): return x + y
Subtraction:
def subtraction(x,
y): return x – y
Multiplication:
def multiplication(x, y):
return x * y
Division:
def division(x, y):
if y != 0:
return x / y
else:
return "Error: Division by zero"
Floor Division:
def floor_division(x, y):
if y != 0:
return x // y
else:
return "Error: Division by zero"
Modulus (Remainder):
def modulus(x, y):
if y != 0:
return x % y
else:
return "Error: Division by zero"
Exponentiation:
def exponentiation(x, y):
return x ** y
These functions can be used to perform various arithmetic operations by passing
appropriate arguments. For example:
• Syntax: len(iterable)
• Description: Returns the number of items (length) in an iterable object such as a list, tuple,
string, dictionary, or set.
• Example
my_list = [1, 2, 3, 4, 5]
length = len(my_list)
print("Length of the list:", length)
# Output: Length of the list: 5
max()function:
• Example:
x = 10
if x > 0:
print("x is
positive") elif x == 0:
print("x is
zero") else:
print("x is negative")
Looping Statements:
• Looping statements allow you to execute a block of code repeatedly as long as a
certain condition is met.
• Python provides two main types of loops: forloops and whileloops.
• forloops iterate over a sequence (such as lists, tuples, strings, or ranges) and
execute a block of code for each element in the sequence.
• Example of a forloop
for i in range(5):
print(i)
• whileloops continue to execute a block of code as long as a specified condition
is true.
• Example of a whileloop
x=0
while x < 5:
print(x)
x += 1
Control Statements:
• Control statements allow you to alter the flow of execution within loops and conditional
statements.
• Python provides break, continue, and passstatements for this purpose.
• The breakstatement terminates the loop it is contained within prematurely.
• The continuestatement skips the rest of the loop's body for the current iteration and
continues with the next iteration.
• The continuestatement skips the rest of the loop's body for the current iteration and continues with
the next iteration.
• The passstatement is a no-operation placeholder that is used when a statement is syntactically
required but you want to do nothing.
Example
for i in
range(10):
if i == 3:
continue
elif i == 7:
break
else:
pass
print(i)
Exception Handling:
• Exception handling allows you to handle errors and exceptions that may occur
during the execution of a program.
• Python provides try, except, else, and finallyblocks for exception handling.
• Example:
try:
result = 10 / 0
except ZeroDivisionError:
print("Error: Division by
zero")
else:
print("No exception occurred")
finally:
print("Cleanup code")
(b)Describe the syntax and semantics of any two loop structures provided by Python.
forloop:
• Syntax:
for item in iterable:
# Code block to be executed for each item
• Semantics:
• The forloop iterates over each item in the given iterable (such as lists, tuples, strings, or
ranges).
• In each iteration, the loop variable itemis assigned the value of the current item in the iterable.
• The code block inside the loop is executed for each item in the iterable.
• After processing all items in the iterable, the loop terminates.
• Example:
numbers = [1, 2, 3, 4, 5]
for num in
numbers:
print(num)
Output:
1
2
3
4
whileloop:
• Syntax
while condition:
# Code block to be executed as long as condition is true
• Semantics:
• The whileloop repeatedly executes a block of code as long as the specified condition is
true.
• Before each iteration, the condition is evaluated. If it evaluates to True, the code block
inside the loop is executed. If it evaluates to False, the loop terminates.
• The code block inside the loop may contain statements that modify the variables involved in
the loop condition.
• If the loop condition never becomes False, the loop continues indefinitely, resulting in
an infinite loop.
• Example:
count = 0
while count
< 5:
print(coun
t)
count += 1
Output:
0
1
2
3
4
(c)Write a python program to print the sum of the series: 1+1/2 2 +1/3 3 +……+1/n n
def series_sum(n):
sum_series = 0
for i in range(1, n + 1):
sum_series += 1 / (i * i)
return sum_series
# Input: value of n
n = int(input("Enter the value of n: "))
2. Recursive Case: A set of instructions that break down the problem into smaller, similar
subproblems and make recursive calls to solve them. Each recursive call works on a smaller
instance of the original problem until it reaches the base case.
3. Indirect Recursion: When a function calls another function, which in turn calls the original
function, it forms indirect recursion. This pattern can be used to solve problems that cannot be
easily solved using direct recursion alone
Recursive functions are commonly used to solve problems that exhibit a recursive structure, such as
tree traversal, factorial computation, Fibonacci sequence generation, and sorting algorithms like
quicksort and mergesort.
Here's an example of a recursive function to compute the factorial of a non-negative integer:
def factorial(n):
if n == 0:
return 1 # Base case:
factorial of 0 is 1 else:
return n * factorial(n - 1) # Recursive case: n! = n * (n-1)!
Lambda functions are typically used when you need a simple function for a short period of time,
often as an argument to higher-order functions (functions that take other functions as arguments),
such as map(), filter(), and sorted().
Here's an example of a lambda function that calculates the square of a number
square = lambda x: x ** 2
You can then use this lambda function just like any other function:.
print(square(5)) # Output: 25
Lambda functions can also take multiple arguments:
add = lambda x, y: x + y
print(add(3, 5)) #
Output: 8
# Example usage:
num1 =2
num2 =4
print("GCD of", num1, "and", num2, "is:", gcd(num1, num2))
6. (a) Write a Python program that counts the number of occurrences of the character
in the given string. Provide two implementations: recursive and iterative.
1. Recursive Implementation:
def count_occurrences_recursive(string, char):
(b) Write a python program to retrieve strings starting with m and having 5 characters
def retrieve_strings(strings): result = []
for s in strings:
if len(s) == 5 and s.startswith('m'):
result.append(s)
return result
Interface:
•Python does not have a built-in interface keyword like some other programming
languages. However, interfaces can be simulated using abstract classes with all methods
declared as abstract. In Python, interfaces are essentially abstract classes that contain only
abstract methods (i.e., methods with no implementation).
• Interfaces define a contract that classes must adhere to. Any class that implements
an interface must provide concrete implementations for all the methods declared in
the interface.
• Example
from abc import ABC, abstractmethod
class Printable(ABC): # Interface (abstract class with abstract methods only)
@abstractmethod
def print_info(self): # Abstract method pass
class
Document(Printable
): def init (self,
content):
self.content = content
def print_info(self): # Implementation of abstract
method print("Document content:",
self.content)
3. module : This attribute contains the name of the module in which the class is defined. It is
useful for obtaining information about the module containing the class.
4. bases : This attribute contains a tuple of the base classes (parent classes) of the class. It
provides information about the inheritance hierarchy of the class.
5. dict : This attribute contains a dictionary that holds the namespace of the class. It stores all the
attributes (both class attributes and instance attributes) defined in the class.
6. class : This attribute contains a reference to the class itself. It is used to access class methods
and class attributes from within the class.
Importing Specific Items from a Module: If you only need certain items from a module, you
can import them explicitly using the from ... import syntax.
from math import sqrt
print(sqrt(25)) # Output: 5.0
Importing with Alias: You can import a module with an alias to simplify its usage in your code.
import math as m
print(m.sqrt(25)) # Output: 5.0
Importing All Items from a Module: You can import all items from a module into the current
namespace using the from ... import * syntax. However, it's generally not recommended
because it can lead to namespace pollution and make your code less readable.
from math import *
print(sqrt(25)) # Output: 5.0
Conditional Import: You can conditionally import a module based on certain conditions using
the import statement inside a conditional block.
if condition:
import module_name
Importing Submodules: If a module contains submodules, you can import them using dot
notation.
import package.submodule
print(package.submodule.function())
Importing Packages: Packages are collections of modules. You can import a package and its
modules similarly to importing modules.
import package_name.module_name
print(package_name.module_name.function())
8. (a) Write a python program that shows the concept of Inheritance.
class Animal:
def init (self, name):
self.name = name
def speak(self):
pass # Abstract method, to be overridden in subclasses
class Dog(Animal): def speak(self):
return f"{self.name} says Woof!"
class
Cat(Animal):
def
speak(self):
return f"{self.name} says Meow!"
# Creating instances of
subclasses dog =
Dog("Buddy")
cat = Cat("Whiskers")
# Calling methods of base
class print("Base class
method:")
print("dog.name:", dog.name) # Output:
Buddy print("cat.name:", cat.name) #
Output: Whiskers
# Calling methods of
subclasses
print("\nSubclass
method:")
print(dog.speak()) # Output: Buddy says
Woof! print(cat.speak()) # Output:
Whiskers says Meow!
(b) Create a class Employee with data members: name, department and salary.
Create suitable methods for reading and printing employee information.
class Employee:
def init (self, name, department,
salary): self.name = name
self.department =
department self.salary =
salary
def read_employee_info(self):
self.name = input("Enter employee name: ")
self.department = input("Enter employee
department: ") self.salary = float(input("Enter
employee salary: "))
def print_employee_info(self):
print("Employee Name:",
self.name)
print("Department:",
self.department)
print("Salary:", self.salary)
# Creating an instance of the Employee class
employee1 = Employee("John Doe", "Engineering", 5000)
# Printing employee
information print("Employee
Information:")
employee1.print_employee_inf
o()
# Reading employee information employee1.read_employee_info()
# Printing updated employee information
print("\nUpdated Employee Information:")
employee1.print_employee_info()
(c) What are the differences between abstract class and interface? Write a python
program in which Maruti and Santro sub classes implement the abstract methods
of the super class Car.
1. Abstract Class:
• An abstract class can have both abstract methods (methods without implementation) and
concrete methods (methods with implementation).
• An abstract class can have instance variables.
• A class can inherit from only one abstract class.
• Abstract classes can provide a partial implementation of a class and allow subclasses to
override some methods while inheriting others.
• Abstract classes are declared using the abstract keyword.
• In Python, abstract classes are implemented using the abc module.
2. Interface:
• An interface contains only method declarations, without implementations.
• An interface cannot have instance variables.
• A class can implement multiple interfaces.
• Interfaces provide a contract that classes must adhere to, but they do not provide any
implementation.
• Interfaces are declared using normal class syntax in some languages, while in Python, they
are simulated using abstract classes with all methods declared as abstract.
• Interfaces are used to achieve abstraction and enforce polymorphism.
Now, let's see an example in Python where we have an abstract class Carwith abstract methods
start()and stop(), and two subclasses Marutiand Santro implementing these methods:
@abstractmeth
od def
stop(self):
pass
class Maruti(Car): # Subclass implementing abstract methods
def start(self):
print("Maruti car started")
def stop(self):
print("Maruti car stopped")
class Santro(Car): # Subclass implementing abstract methods
def start(self):
print("Santro car started")
def stop(self):
print("Santro car stopped")
# Creating instances of
subclasses maruti = Maruti()
santro = Santro()
# Calling methods of
subclasses print("Maruti
car:") maruti.start()
maruti.stop()
print("\nSantro
car:")
santro.start()
santro.stop()
Python implements namespaces as dictionaries where the keys are the names of objects
(variables, functions, classes) and the values are references to the objects themselves.
• Each namespace is associated with a specific scope or context in which the names are defined and
can be accessed.
• Global Namespace: A namespace associated with a module. It contains names defined at the top
level of the module file.
• Built-in Namespace: A namespace containing built-in names provided by the Python interpreter.
These names are available globally in all modules.
• Namespaces allow the same name to be used for different purposes in different contexts without
causing conflicts.
2. Scoping:
a. Scoping refers to the rules that determine where and how names are looked up in a program. It
defines the visibility and accessibility of names in different parts of the code.
b. Python follows the LEGB rule to determine the order in which namespaces are searched for names:
k. nonlocal: Allows a variable to be assigned a value in an enclosing (non-local) scope from within a
nested function.
l. Scoping ensures that variables are properly encapsulated and that changes made to variables in
one part of the program do not affect variables with the same name in other parts.
if condition:
import module_name
Importing Packages:
Packages are collections of modules. You can import a package and its modules similarly to
importing modules.
import package_name.module_name
def rightmost_digit(number):
return number % 10
# Test the function
num = int(input("Enter a number: "))
print("Rightmost digit:",
rightmost_digit(num))
10. (a) Explain the significance of xrange() function in for loop with a help of a program.
return fib_series
# Function to print the Fibonacci
series def
print_fibonacci_series(series):
print("Fibonacci
Series:") for num in
series:
print(num, end=" ")
# Number of terms in the Fibonacci series
terms = int(input("Enter the number of terms in the Fibonacci series: "))
# Generate and print the Fibonacci
series fib_series =
fibonacci_series(terms)
print_fibonacci_series(fib_series)
1. fibonacci_series(n): This function takes the number of terms nas input and returns a list
containing the Fibonacci series up to n terms. It uses a for loop to generate the Fibonacci numbers
iteratively, starting from the initial values a = 0 and b = 1. In each iteration, it appends the current
Fibonacci number (a) to the fib_series list and updates the values of a and b for the next Fibonacci
number.
2. print_fibonacci_series(series): This function takes a list seriescontaining the Fibonacci
series as input and prints it to the console.
• Move n-1disks from the source rod to the auxiliary rod, using the destination rod as the temporary
rod.
• Move the nthdisk from the source rod to the destination rod.
• Move the n-1disks from the auxiliary rod to the destination rod, using the source rod as the
temporary rod.
In this program:
• The tower_of_hanoi() function takes four arguments: n (the number of disks), source(the rod
from which to move the disks), auxiliary(the temporary rod to use), and destination (the rod to
which to move the disks).
• The function follows the recursive steps described above to solve the Tower of Hanoi
problem.
• The user inputs the number of disks, and the function is called with the initial parameters
to solve the problem.
(b) Write a Python program to find the factorial of the given number with and
without recursion with comparison.
In this program:
my_tuple = (1, 2, 3)
print(my_tuple[0]) # Output: 1
# Attempting to modify a tuple will raise
an error # my_tuple[0] = 10 # This will
raise a TypeError
3. Concatenating Tuples: You can concatenate tuples to create a new tuple, but this operation does
not modify the original tuples.
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
concatenated_tuple = tuple1 + tuple2
print(concatenated_tuple) # Output: (1, 2, 3, 4, 5, 6)
4. Slicing Tuples: You can slice tuples to create new tuples containing subsets of the original elements.
Again, this operation does not modify the original tuple.
my_tuple = (1, 2, 3, 4, 5)
sliced_tuple = my_tuple[1:4]
print(sliced_tuple) # Output:
(2, 3, 4)
5. Deleting a Tuple: While you cannot modify individual elements of a tuple, you can delete the entire
tuple.
my_tuple = (1, 2, 3)
del my_tuple
# print(my_tuple) # This will raise a NameError because the tuple no longer exists
In summary, immutability in tuples means that you cannot change the elements of a tuple after it has
been created. This property makes tuples useful for representing fixed collections of items, such as
coordinates, database records, or function arguments, where you want to ensure that the data remains
unchanged throughout the program execution.
(b)Illustrate the ways of creating the tuple and the tuple assignment with suitable
programs.
1. Creating Tuples:
• Using parentheses ():
my_tuple = (1, 2, 3)
(c)What are the accessing elements in a tuple? Explain with suitable Programs.
1. Accessing Elements by Index:
• You can access individual elements of a tuple by specifying their index position within square
brackets []. Indexing starts from 0 for the first element and increases by 1 for each subsequent
element
# Define a tuple
my_tuple = (10, 20, 30, 40, 50)
Empty list: []
List with elements: [1, 2, 3, 4, 5]
Mixed list: [1, 'apple', True, 3.14]
Nested list: [[1, 2], [3, 4], [5, 6]]
List created using list() constructor: [1, 2, 3, 4, 5]
List created using list comprehension: [1, 4, 9, 16, 25]
# Define a list
my_list = [10, 20, 30, 40, 50]
# Modify an
element
my_list[2] = 35
# Define a list
my_list = [10, 20, 30]
# Add an element to the end
my_list.append(40)
print("List after appending:", my_list) # Output: [10, 20, 30, 40]
# Insert an element at a specific position
my_list.insert(1, 15)
print("List after inserting:", my_list) # Output: [10, 15, 20, 30, 40]
3. Removing Elements:
• You can remove elements from a list using the remove()method to remove a specific value, or
the pop()method to remove an element by index. You can also use the delstatement to remove
an element or a slice of elements by index.
# Define a list
my_list = [10, 15, 20, 30, 40]
# Remove a specific element
my_list.remove(20)
print("List after removing element:", my_list) # Output: [10, 15, 30, 40]
# Remove an element by index
removed_element = my_list.pop(1)
print("Removed element:", removed_element)
print("List after popping element:", my_list) # Output: [10, 30, 40]
# Original list
original_list = [1, 2, 3, 4, 5]
# Creating a shallow copy using list
slicing copied_list = original_list[:]
# Modifying the original
list original_list[0] = 10
# Printing both lists
print("Original list:", original_list) # Output: [10, 2, 3, 4, 5]
print("Copied list:", copied_list) # Output: [1, 2, 3, 4, 5]
3. Using the list()constructor:
• You can use the list() constructor to create a shallow copy of a list. This method creates a new
list containing all elements from the original list. Changes made to the original list will not
affect the copied list, and vice versa.
# Original list
original_list = [1, 2, 3, 4, 5]
# Creating a shallow copy using the list()
constructor copied_list = list(original_list)
# Modifying the original
list original_list[0] = 10
# Printing both lists
print("Original list:", original_list) # Output: [10, 2, 3, 4, 5]
print("Copied list:", copied_list) # Output: [1, 2, 3, 4, 5]
# Define a list
my_list = [1, 2, 3, 4, 5]
# Remove and return an element by index
removed_element = my_list.pop(2)
print("Removed element:", removed_element)
print("List after popping element by index:", my_list) # Output: [1, 2, 4, 5]
# Remove and return the last element
last_element = my_list.pop()
print("Last element:", last_element)
print("List after popping last element:", my_list) # Output: [1, 2, 4]
# Define a list
my_list = [1, 2, 3, 4, 5]
# Remove and return an element by
index removed_element =
my_list.pop(2) print("Removed
element:", removed_element)
print("List after popping element by index:", my_list) # Output: [1, 2, 4, 5]
# Remove and return the last
element last_element =
my_list.pop() print("Last
element:", last_element)
print("List after popping last element:", my_list) # Output: [1, 2, 4]
self.width = width
def area(self):
return self.length * self.width
def perimeter(self):
return 2 * (self.length + self.width)
rect = Rectangle(5, 4)
print("Area:", rect.area()) # Output: Area: 20
print("Perimeter:", rect.perimeter()) # Output: Perimeter: 18
2. Interface:
• In Python, interfaces are not explicitly defined as a language construct like in some other
programming languages. Instead, interfaces are usually represented using abstract classes
that contain only abstract methods (methods without implementations). Classes that
implement these methods are considered to implement the interface.
• Interfaces are more of a conceptual idea rather than a language feature, and adherence to
interfaces relies on developers following conventions.
class Animal:
def speak(self):
pass
class
Dog(Animal)
: def
speak(self):
return "Woof!"
class
Cat(Animal):
def
speak(self):
return "Meow!"
dog = Dog()
print(dog.speak()) # Output: Woof!
cat = Cat()
print(cat.speak()) # Output: Meow!
In this example:
Animalclass is an abstract class with an abstract method speak().
Dogand Catclasses are concrete subclasses of Animaland provide implementations for the
speak() method.
Although Python does not have a built-in interface construct, the Animalclass serves as
an interface, and Dog and Cat classes can be said to implement the Animal interface by
providing implementations for the speak() method.
(c)Write a python program that shows the concept of Inheritance.
# Define a
superclass class
Animal:
def init (self, name):
self.name = name
def speak(self):
raise NotImplementedError("Subclasses must implement this method")
# Define a subclass inheriting from Animal
class Dog(Animal):
def speak(self):
return "Woof!"
# Define another subclass inheriting from Animal
class Cat(Animal):
def speak(self):
return "Meow!"
# Create instances of subclasses
dog = Dog("Buddy")
cat = Cat("Whiskers")
# Access superclass attribute
print("Dog's name:", dog.name) # Output: Dog's name: Buddy
print("Cat's name:", cat.name) # Output: Cat's name: Whiskers
# Call superclass method
print("Dog says:", dog.speak()) # Output: Dog says: Woof!
print("Cat says:", cat.speak()) # Output: Cat says: Meow!
In this program:
We define a superclass Animalwith an init ()method to initialize the name attribute and a
speak() method. The speak() method raises a NotImplementedErrorsince subclasses must
provide their own implementation.
We define two subclasses Dogand Catthat inherit from the Animalsuperclass. Each subclass
provides its own implementation of the speak() method.
We create instances of the Dogand Catsubclasses, passing the names of the animals as
arguments.
We access the nameattribute of each instance to demonstrate inheritance of attributes.
We call the speak()method of each instance to demonstrate inheritance of methods, with
each subclass providing its own implementation.
15. (a) Write a python program in which Maruti and Santro sub classes implement
the abstract methods of the super class Car.
from abc import ABC, abstractmethod
# Define abstract class
Car class Car(ABC):
def init (self, model):
self.model = model
@abstractmethod
def start(self):
pass
@abstractmethod
def stop(self):
pass
# Define Maruti subclass implementing Car
class Maruti(Car):
def start(self):
return "Maruti {} started".format(self.model)
def stop(self):
return "Maruti {} stopped".format(self.model)
# Define Santro subclass implementing Car
class Santro(Car):
def start(self):
return "Santro {} started".format(self.model)
def stop(self):
return "Santro {} stopped".format(self.model)
# Create instances of Maruti and
Santro maruti_car = Maruti("Swift")
santro_car = Santro("Xing")
# Test the methods
print(maruti_car.start()) # Output: Maruti Swift started
print(maruti_car.stop()) # Output: Maruti Swift stopped
print(santro_car.start()) # Output: Santro Xing started
print(santro_car.stop()) # Output: Santro Xing stopped
In this program:
• We define an abstract class Carwith two abstract methods start()and stop().
• The Marutiand Santrosubclasses inherit from the Carsuperclass and implement their
own versions of the abstract methods.
• Instances of Marutiand Santroclasses are created with specific models.
• We test the start()and stop()methods of both subclasses to demonstrate that each subclass
provides its own implementation of these methods.
(b) Write a program to implement a student class with five-member variables and
with at least two methods to get and set values.
class Student:
def init (self):
self.name = " "
self.roll_number = " "
self.age = 0 self.grade = " "
self.department = " "
16. (a) Explain the concept of stack frame in python with an appropriate example.
In Python, a stack frame (also known as an activation record or activation frame) is a data structure
that represents a function call. Each time a function is called, a new stack frame is created to store
information such as local variables, function arguments, return address, and other execution-related
data. These stack frames are organized in a stack- like manner, where each frame corresponds to a
particular function call, with the most recent call at the top of the stack.
Let's illustrate the concept of a stack frame with an example:
# Example usage
arr = [10, 20, 30, 40, 50]
target = 30
index = linear_search(arr,
target) if index != -1:
print(f"Element {target} found at index {index}.")
else:
print(f"Element {target} not found in the list.")
17. (a) Write a python program to display the sum of the given series: x+1/x 2 -1/x 3
+1/x 4 ………..(-1) n /x n
def series_sum(x, n):
sum = 0
for i in range(1, n + 1):
term = ((-1) ** i) / (x ** i)
sum += term
return sum
Output:
Enter the value of x: 4
Enter the value of n: 2
The sum of the series is: -0.1875
(b) Create a program to print the following pattern
1
121
12321
1234321
def print_pattern(rows):
"""
Print the given pattern:
1
121
12321
1 234321
"""
# Loop through each row
for i in range(1, rows + 1):
# Print leading spaces
print(" " * (rows - i) * 2, end="")
# Print numbers in increasing order
for j in range(1, i + 1):
print(j, end=" ")
Output:
# Print numbers in decreasing order 1
for k in range(i - 1, 0, -1): 121
print(k, end=" ") 12321
1234321
# Move to the next line print()
# Example usage rows = 4 print_pattern(rows)
18. (a) Write a python program named Weather that is passed a dictionary of daily
temperatures, and returns the average temperature over the Weekend for the
weekly temperatures given.
def calculate_weekend_average(weekly_temperatures):
"""
Calculate the average temperature over the weekend (Saturday and Sunday) for the given
weekly temperatures.
Parameters:
weekly_temperatures (dict): A dictionary containing daily temperatures for the week.
Returns:
float: The average temperature over the weekend.
"""
weekend_temperatures = [temperature for day, temperature in weekly _ temperatures
items() if day.lower() in ['saturday', 'sunday']]
if not weekend_temperatures:
return 0 # No weekend temperatures found
return sum(weekend_temperatures) / len(weekend_temperatures)
# Example
usage weekly_temperatures = {
'Monday': 20,
'Tuesday': 22,
'Wednesday': 25,
'Thursday': 24,
'Friday': 23,
'Saturday': 28,
'Sunday': 29
}
average_weekend_temperature = calculate_weekend_average(weekly_temperatures)
print("Average temperature over the weekend:", average_weekend_temperature)
In this program:
• We define a function calculate_weekend_averagethat takes a dictionary
weekly_temperaturescontaining daily temperatures for the week as input.
• We extract the temperatures for Saturday and Sunday from the dictionary using list
comprehension and filtering by the day names.
• We calculate the average temperature over the weekend by summing up the temperatures and
dividing by the number of days in the weekend.
• If no temperatures are found for the weekend, we return 0.
• We provide an example usage of the function with a sample
weekly_temperatures dictionary.
• We print the average temperature over the weekend.
(b) Write a Python program to create a histogram from a given list of integers.
def create_histogram(numbers):
"""
Create a histogram from a given list of integers.
Parameters:
numbers (list): A list of integers.
Returns:
str: The histogram representation as a string.
"""
histogram = ""
for num in numbers:
histogram += "*" * num + "\n"
return histogram
# Example usage
numbers = [3, 7, 2, 5, 8]
histogram = create_histogram(numbers)
print("Histogram:")
print(histogram)
In this program:
We define a function create_histogramthat takes a list of integers numbersas input.
We iterate through each integer in the list and create a string of asterisks (*) representing the
histogram bar for that integer.
We concatenate these strings to form the complete histogram.
• We return the histogram string.
• We provide an example usage of the function with a sample list of integers numbers.
• We print the histogram.
19. (a) Write a python program that creates a class Student having attributes
{Enrollement_No, Name} and methods set_data that takes the values from the
user and assigns them to attributes of the class and an operator overloading
function that converts Student object to string. Also create an Class variable
student_count that will maintain the count of Student Instances and a method
that will display this count.
class Student:
# Class variable to maintain count of Student instances
student_count = 0
def init (self, enrollment_no, name):
self.enrollment_no = enrollment_no
self.name = name
# Increment student count when a new instance is created
Student.student_count += 1
def set_data(self):
"""
Method to set data (enrollment number and name) for a Student object.
"""
self.enrollment_no = input("Enter Enrollment No: ")
self.name = input("Enter Name: ")
def str (self):
"""
Operator overloading function to convert Student object to string.
"""
return f"Enrollment No: {self.enrollment_no}, Name: {self.name}"
@classmethod
def display_student_count(cls):
"""
Method to display the count of Student instances.
"""
print(f"Total number of students: {cls.student_count}")
# Example usage
student1 = Student("2021001", "Alice")
student2 = Student("2021002", "Bob")
print("Student 1:", student1)
print("Student 2:", student2)
# Set data for a student object
student3 = Student("", "")
student3.set_data()
print("Student 3:", student3)
(b) Create a class student with following member attributes: roll no, name, age
and total marks. Create suitable methods for reading and printing member
variables. Write a python program to overload ‘==’operator to print the details of
students having same marks.
class Student:
def init (self, roll_no, name, age, total_marks):
self.roll_no = roll_no
self.name = name
self.age = age
self.total_marks = total_marks
def read_data(self):
"""
Method to read member variables of Student.
"""
self.roll_no = input("Enter Roll No:
") self.name = input("Enter Name:
") self.age = int(input("Enter Age:
"))
self.total_marks = float(input("Enter Total Marks: "))
def display(self):
"""
Method to display member variables of Student.
"""
print(f"Roll No: {self.roll_no}")
print(f"Name: {self.name}")
print(f"Age: {self.age}")
def get(self):
"""
Method to get properties of the flower.
"""
return {
"Name": self.name,
"Price": self.price,
"Color": self.color,
"Smell": self.smell
}
def display(self):
"""
Method to display properties of the
flower. """
print(f"Name: {self.name}")
print(f"Price: {self.price}")
print(f"Color: {self.color}")
print(f"Smell: {self.smell}")
# Create instances of Flower
lilly = Flower("Lilly", 5, "White", "Fragrant")
rose = Flower("Rose", 3, "Red", "Sweet")
hibiscus = Flower("Hibiscus", 4, "Pink", "Mild")
# Example usage
print("Details of Lilly:") lilly.display()
print("\nDetails of
Rose:") rose.display()
print("\nDetails of Hibiscus:") hibiscus.display()
(b) Write a Python program to create class GTU with attributes like class variable
cnt, instance variables x and y,instance methods get_value and print_value.
class GTU:
cnt = 0 # Class variable
def print_value(self):
"""
Method to print the values of instance variables x and y.
"""
print(f"Value of x: {self.x}")
print(f"Value of y: {self.y}")
# Example usage
gtu1 = GTU(5, 10)
gtu2 = GTU(15, 20)
# Print the number of instances created
print("Number of instances created:", GTU.cnt)
# Get and print values of instance variables for gtu1
x1, y1 = gtu1.get_value()
print("\nValues of instance variables for gtu1:")
print("x:", x1)
print("y:", y1)
# Print values of instance variables for gtu2
print("\nValues of instance variables for gtu2:")
gtu2.print_value()