Python Winterr

Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

Python winter 23

01) Attempt any FIVE of the following :


A) Enlist applications for python programming
Ans)1. Web Applications.
2. Game Development.
3. Data Science and Machine Learning.
4. Image Processing.
5. Web Scraping.
6. Software Development.
7. Desktop GUI Applications.
8. Enterprise Applications.
B) Write the use of elif keyword in python
Ans) The elif keyword in Python is short for “else if”. It is used in conditional statements to check for
multiple conditions. For example, if the first condition is false, it moves on to the next “elif” statement to
check if that condition is true. This process continues until one of the conditions is true, or until all of the
conditions have been checked and found to be false.
C) Describe the Role of indentation in python
Ans) Indentation refers to the spaces at the beginning of a code line. Where in other programming languages
the indentation in code is for readability only, the indentation in Python is very important. Python uses
indentation to indicate a block of code.
D) Define Data Hiding concept? Write two advantages of Data Hiding.
Ans) Data hiding is a concept which underlines the hiding of data or information from the user. It is one of
the key aspects of Object-Oriented programming strategies. It includes object details such as data members,
internal work. Data hiding excludes full data entry to class members and defends object integrity by
preventing unintended changes.
Advantages: It helps to prevent damage or misuse of volatile data by hiding it from the public.
The class objects are disconnected from the irrelevant data.
It isolates objects as the basic concept of OOP.
It increases the security against hackers that are unable to access important data.
E) State use of namespace in python.
Ans) Namespaces in Python are used to organize and manage names (variables, functions, classes) within a
program to avoid naming conflicts. They include:
• Global Namespace
• Local Namespace
• Built-in Namespace
• Namespace Creation
F) State the use of read ( ) and readline ( ) functions in python file handling.
Ans) In Python file handling, the read() and readline() functions are used to read data from a file.
1. read() Function:
• The read() function reads a specified number of bytes from the file.
• If no size is specified, it reads the entire file.
• After reading, the file pointer advances to the end of the data read.
• It returns the data read as a string.

2. readline() Function:
• The readline() function reads a single line from the file.
• If called again, it reads the next line, and so on.
• It stops reading when it encounters a newline character ('\n') or reaches the end of the file.
• It returns the line read as a string, including the newline character at the end.
G) Explain two ways to add objects / elements to list.
Ans) Using the append() Method: The append() method is used to add a single element to the end of a list.It
modifies the original list in place.
Syntax: list_name.append(element)
Using the extend() Method or Concatenation: The extend() method is used to add multiple elements to the
end of a list by extending it with another iterable (like another list). It modifies the original list in place.
Syntax: list_name.extend(iterable)

Q2) Attempt any THREE of the following :


A) Explain membership and Identity operators in Python.
Ans) In Python, membership and identity operators are used to check for membership and identity
relationships between objects.
• Membership Operators:
in: The in operator is used to check if a value exists in a sequence (such as a list, tuple, string, or dictionary).
Example: my_list = [1, 2, 3, 4, 5]
# Check if 3 is in my_list
if 3 in my_list:
print("3 is present in the list")
not in: The not in operator is used to check if a value does not exist in a sequence.
Example: my_tuple = (10, 20, 30)
# Check if 40 is not in my_tuple
if 40 not in my_tuple:
print("40 is not present in the tuple")
• Identity Operators:
is: The is operator checks if two variables refer to the same object in memory. It evaluates to True if the
variables point to the same object, and False otherwise.
Example: x = [1, 2, 3]
y = [1, 2, 3]
z=x
print(x is y) # Output: False (x and y point to different objects)
print(x is z) # Output: True (x and z point to the same object)
is not: The is not operator checks if two variables do not refer to the same object in memory. It evaluates to
True if the variables do not point to the same object, and False otherwise.
Example: a = 10
b = 20
print(a is not b) # Output: True (a and b do not point to the same object)
B) Write python program to display output like.
2
468
10 12 14 16 18
Ans) def generate_output(rows):
start = 2
for i in range(rows):
row_numbers = [str(start + j * 2) for j in range(i + 1)]
print(' '.join(row_numbers))
start += 1
rows_to_generate = 3
generate_output(rows_to_generate)
C) Explain four built-in list functions
Ans) a) append(): The append() function is used to add an element to the end of a list.
Syntax: list_name.append(element)
Example: my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # Output: [1, 2, 3, 4]
b) extend(): The extend() function is used to add multiple elements (from an iterable like another list) to the
end of a list.
Syntax: list_name.extend(iterable)
Example: my_list = [1, 2, 3]
my_list.extend([4, 5, 6])
print(my_list) # Output: [1, 2, 3, 4, 5, 6]
c) insert(): The insert() function is used to insert an element at a specified index in a list.
Syntax: list_name.insert(index, element)
Example: my_list = [1, 2, 3]
my_list.insert(1, 'a')
print(my_list) # Output: [1, 'a', 2, 3]
d) remove(): The remove() function is used to remove the first occurrence of a specified element from a list.
Syntax: list_name.remove(element)
Example: my_list = [1, 2, 3, 2]
my_list.remove(2)
print(my_list) # Output: [1, 3, 2]
D) Write python program using module, show how to write and use module by importing it.
Ans) Example: Let’s create a simple module named GFG.
''' GFG.py '''
# Python program to create
# a module
# Defining a function
def Geeks():
print("GeeksforGeeks")
# Defining a variable
location = "Noida"
The above example shows the creation of a simple module named GFG as the name of the above Python file
is GFG.py. When this code is executed it does nothing because the function created is not invoked. To use
the above created module, create a new Python file in the same directory and import GFG module using the
import statement.
Example:# Python program to demonstrate
# modules
import GFG
# Use the function created
GFG.Geeks()
# Print the variable declared
print(GFG.location)
Output:
GeeksforGeeks
Noida

Q3)Attempt any THREE of the following :


A) Describe various modes of file object ? Explain any two in detail.
Ans) In Python, file objects are used to interact with files on the system. The open() function is used to
create a file object, and it supports various modes that define how the file should be opened and used.
Read Modes:
'r': Opens the file for reading only. The file pointer is placed at the beginning of the file. If the file does not
exist, it raises a FileNotFoundError.
'rb': Opens the file for reading in binary mode. Similar to 'r' mode, but it reads the file in binary format.
Write Modes:
'w': Opens the file for writing only. If the file exists, it truncates it to zero length. If the file does not exist, it
creates a new file.
'wb': Opens the file for writing in binary mode. Similar to 'w' mode, but it writes data in binary format.
Append Modes:
'a': Opens the file for appending. The file pointer is placed at the end of the file. If the file does not exist, it
creates a new file.
'ab': Opens the file for appending in binary mode. Similar to 'a' mode, but it appends data in binary format.
Read and Write Modes:
'r+': Opens the file for both reading and writing. The file pointer is placed at the beginning of the file.
'rb+': Opens the file for both reading and writing in binary mode. Similar to 'r+' mode, but it reads and writes
data in binary format.
B) Explain use of Pass and Else keyword with for loops in python
Ans) pass Keyword with for Loops: The pass keyword is used as a placeholder when a statement is
syntactically required but you want to do nothing. It is commonly used within loops, including for loops, to
indicate that no action should be taken at a particular point.
Example: for i in range(5):
if i == 2:
pass # Do nothing when i is 2
else:
print(i)
else Statement with for Loops: The else statement in a for loop is executed when the loop completes all
iterations without encountering a break statement. It is often used to execute a block of code after the loop
finishes successfully, such as when no break condition is met.
Example: for i in range(5):
print(i)
if i == 2:
break
else:
print("Loop completed successfully")
C) T = (‘spam’, ‘Spam’, ‘SPAM!’, ‘SaPm’)
print (T [2] )
print (T [-2] )
print (T [2:] )
print (List (T)
Ans) SPAM!
SPAM!
('SPAM!', 'SaPm')
['spam', 'Spam', 'SPAM!', 'SaPm']
D) Explain method overloading and overriding in python
Ans) Method overloading: it refers to the ability to define multiple methods in a class with the same name
but different parameters or different types of parameters. Python does not support method overloading
directly as some other languages like Java or C++ do, where you can have multiple methods with the same
name but different parameter lists. However, in Python, you can achieve a form of method overloading using
default parameter values and variable-length arguments (*args and **kwargs). By defining a single method
with default parameters or variable-length arguments, you can mimic the behavior of method overloading.
Method Overriding: Method overriding refers to the ability to define a method in a subclass that has the
same name and signature (parameters) as a method in its superclass. When you override a method, the
method in the subclass replaces the method with the same name in the superclass. This concept is essential
in inheritance, where subclasses can provide a specific implementation of a method defined in their
superclass.

Q4) Attempt any THREE of the following :


A) Explain different functions or ways to remove key : value pair from Dictionary
Ans) Using the ‘del’ keyword: You can use the del keyword followed by the key to remove a key-value
pair from a dictionary.
Example: my_dict = {'a': 1, 'b': 2, 'c': 3}
del my_dict['b']
print(my_dict) # Output: {'a': 1, 'c': 3}
Using the pop() method: The pop() method removes a key-value pair from a dictionary and returns the
corresponding value.
Syntax: dictionary_name.pop(key[, default])
If the key is found, pop() removes the key-value pair. If the key is not found and a default value is provided,
it returns the default value. If the key is not found and no default value is provided, it raises a KeyError.
Example: my_dict = {'a': 1, 'b': 2, 'c': 3}
value = my_dict.pop('b')
print(my_dict) # Output: {'a': 1, 'c': 3}
print(value) # Output: 2
Using the popitem() method: The popitem() method removes and returns the last key-value pair (as a
tuple) from the dictionary.
Example:
my_dict = {'a': 1, 'b': 2, 'c': 3}
item = my_dict.popitem()
print(my_dict) # Output: {'a': 1, 'b': 2}
print(item) # Output: ('c', 3)
B) Explain Numpy package in detail
Ans) NumPy (Numerical Python) is a Python package that provides a high-performance multidimensional
array object and tools for working with these arrays. It is the core library for scientific computing in Python.
NumPy arrays are used in a wide variety of scientific and engineering applications, including machine
learning, data science, image processing, and signal processing. Refer textbook 4.25
C) Explain seek ( ) and tell ( ) function for file pointer manipulation in python with example.
Ans) The seek() and tell() functions in Python are used to manipulate the file pointer. The file pointer is a
cursor that indicates the current position in a file. The seek() function moves the file pointer to a specified
location, while the tell() function returns the current position of the file pointer.
Here is an example of how to use the seek() and tell() functions:
f = open("myfile.txt", "r")
print(f.tell())
f.seek(0)
line = f.readline()
print(line)
f.close()
D) WAP to read contents of first.txt file and write same content in second.txt file.
Ans) # Open the first.txt file in read mode
with open('first.txt', 'r') as file1:
content = file1.read()
# Open the second.txt file in write mode
with open('second.txt', 'w') as file2:
file2.write(content)
print("Contents copied from first.txt to second.txt successfully.")
Q5) Attempt any TWO of the following :
A)Explain any four set operations with example.
Ans)1) Union: The union of two sets is the set of all elements in either set. In Python, you can use the |
operator or the union() method to find the union of two sets.
For example: set1 = {1, 2, 3}
set2 = {4, 5, 6}
union = set1 | set2
print(union)
output: {1, 2, 3, 4, 5, 6}
2)Intersection: The intersection of two sets is the set of all elements that are in both sets. In Python, you can
use the & operator or the intersection() method to find the intersection of two sets.
For example: set1 = {1, 2, 3}
set2 = {4, 5, 6}
intersection = set1 & set2
print(intersection)
output: set()
3) Difference: The difference of two sets is the set of all elements that are in the first set but not in the
second set. In Python, you can use the - operator or the difference() method to find the difference of two
sets.
For example: set1 = {1, 2, 3}
set2 = {4, 5, 6}
difference = set1 - set2
print(difference)
output: {1, 2, 3}
4) Symmetric difference: The symmetric difference of two sets is the set of all elements that are in either set
but not in both sets. In Python, you can use the ^ operator or the symmetric_difference() method to find the
symmetric difference of two sets.
For example: set1 = {1, 2, 3}
set2 = {4, 5, 6}
symmetric_difference = set1 ^ set2
print(symmetric_difference)
output: {1, 2, 3, 4, 5, 6}
B) Explain building blocks of python.
Ans) The building blocks of Python refer to the fundamental components and concepts that form the core of
the Python programming language. These building blocks enable developers to write code, create programs,
and solve various problems efficiently. Here are the key building blocks of Python:
Variables and Data Types: Variables are used to store data values. In Python, you don't need to explicitly
declare the data type of a variable. Python automatically determines the data type based on the value
assigned to it. Common data types in Python include integers, floats, strings, booleans, lists, tuples, sets,
dictionaries, etc.
Operators: Python supports various operators such as arithmetic operators (+, -, *, /), assignment operators
(=, +=, -=, *=, /=), comparison operators (==, !=, <, >, <=, >=), logical operators (and, or, not), bitwise
operators (&, |, ^), etc.
Control Structures: Control structures are used to control the flow of execution in a program. Examples of
control structures include if statements, else statements, elif statements, loops (for loop, while loop), break
and continue statements, etc.
Functions: Functions are blocks of reusable code that perform a specific task. They help in modularizing
code and making it more organized and easier to understand. Python allows defining functions using the def
keyword.
Modules and Packages: Modules are files containing Python code that can be imported into other Python
scripts. They help in organizing code into separate files for better manageability. Packages are directories
containing multiple modules and an __init__.py file. They provide a way to structure and distribute Python
projects.
Classes and Objects: Python is an object-oriented programming (OOP) language, meaning it supports
classes and objects. Classes are blueprints for creating objects. They encapsulate data and behaviour into a
single unit. Objects are instances of classes that have attributes (variables) and methods (functions).
Exception Handling: Exception handling is used to handle errors and exceptions that may occur during
program execution. Python provides a try-except block for catching and handling exceptions gracefully.
File I/O: Python allows reading from and writing to files using built-in functions like open(), read(), write(),
close(), etc. File I/O operations are essential for working with external files and data.
C) Write a program illustrating use of user defined package in python.
Ans) # Create a directory named mypackage.
import mypackage
# Inside mypackage, create two Python files: module1.py and module2.py.
# Create an __init__.py file inside mypackage (it can be empty).
# Add some code to the modules.
# module1.py
def add_numbers(x, y):
"""Adds two numbers and returns the result."""
return x + y
# module2.py
def subtract_numbers(x, y):
"""Subtracts two numbers and returns the result."""
return x - y
# Finally, demonstrate how to import and use the modules from the package.
# Import the package.
import mypackage
# Use the functions from the package.
print(mypackage.add_numbers(5, 6)) # Prints 11
print(mypackage.subtract_numbers(10, 5)) # Prints 5
In this example, we create a directory named mypackage and add two Python files to it: module1.py and
module2.py. We also create an empty __init__.py file in the directory. This tells Python that the directory is a
package.
The module1.py file defines a function called add_numbers(), which adds two numbers and returns the
result. The module2.py file defines a function called subtract_numbers(), which subtracts two numbers and
returns the result.
Q6) Attempt any TWO of the following :
A)Write a program to create class student with Roll no. and Name and display its contents.
Ans) class Student:
def __init__(self, roll_number, name):
self.roll_number = roll_number
self.name = name
# Create an instance of the Student class
student1 = Student(1, 'John Doe')
# Display the contents of the student object
print(f"Roll Number: {student1.roll_number}")
print(f"Name: {student1.name}")
output: Roll Number: 1
Name: John Doe
B) Write program to implement concept of inheritance in python.
Ans) # Parent class
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def display_info(self):
print(f"Name: {self.name}")
print(f"Age: {self.age}")
# Child class inheriting from Person
class Student(Person):
def __init__(self, name, age, roll_number):
super().__init__(name, age)
self.roll_number = roll_number
def display_info(self):
super().display_info() # Call display_info method of the parent class
print(f"Roll Number: {self.roll_number}")
# Creating an instance of the Student class
student1 = Student("John Doe", 20, 101)
# Displaying information using the inherited methods
student1.display_info()
C) List and explain any four built-in functions on set
Ans)1) add(): This function is used to add an element to a set. If the element is already present in the set, the
set remains unchanged.
Example: my_set = {1, 2, 3}
my_set.add(4)
print(my_set)
Output: {1, 2, 3, 4}
2) remove(): This function is used to remove a specific element from a set. If the element is not present in
the set, it raises a KeyError.
Example: my_set = {1, 2, 3}
my_set.remove(2)
print(my_set)
Output: {1, 3}
3) intersection(): This function returns a new set containing elements that are present in both sets. It is
equivalent to using the & operator.
Example: set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
intersection_set = set1.intersection(set2)
print(intersection_set)
Output: {3, 4}
4)difference(): This function returns a new set containing elements that are present in the first set but not in
the second set. It is equivalent to using the - operator.
Example: set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
difference_set = set1.difference(set2)
print(difference_set)
Output: {1, 2}

You might also like