Python Question Paper Solved
Python Question Paper Solved
Python Question Paper Solved
Question 1.
a. How will you create an object in python explain it with a simple example
To create an object in Python, you can use the class statement to define a new class. Here is
an example of how you can define a simple class that represents a point in 2D space:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
To create an instance of this class (also known as an object), you can call the class name as if
it were a function, and pass in the required arguments (in this case, the x and y coordinates
of the point):
p = Point(0, 0)
This creates a new Point object with the specified x and y coordinates and assigns it to the
variable p. You can access the object's attributes (in this case, x and y) using the dot
notation:
print(p.x) # prints 0
print(p.y) # prints 0
To create an object in Python, you can use the class definition that represents the object
you want to create. Here is an example:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
In this example, we define a class called Point that has two attributes x and y. The __init__
method is a special method in Python that is used to initialize the attributes of an object
when it is created. It is called a constructor.
To create an object of this class, we call the class name followed by parentheses and pass the
required arguments. In this case, we pass the values 10 and 20 for x and y, respectively.
Finally, we print the values of the x and y attributes of the point object using dot notation.
This will print 10 and 20, respectively.
To create an object in Python, you can use the class keyword to define a new class. Here's an
example:
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
dog1 = Dog("Fido", 3)
dog2 = Dog("Buddy", 5)
In this example, we define a Dog class with a __init__ method that is called when a new Dog
object is created. The __init__ method takes in two arguments, name and age, and assigns
them to the object's name and age properties. We then create two Dog objects, dog1 and
dog2, and access their name and age properties using dot notation.
________________________________________________________________________________
b. What are regular expressions in python? How these expressions can be accessed explain
with simple example.
Regular expressions (also known as "regex") are a way to match patterns in strings. They are
often used in programs that require text processing, such as text editors and search engines.
In Python, you can use the re module to work with regular expressions. The module provides
functions for searching, replacing, and manipulating strings using regular expressions.
Here's a simple example of how you can use regular expressions in Python:
import re
In the second example, we use the sub function to replace all the vowels in the string with an
asterisk. The pattern argument is a regular expression that matches any vowel ([aeiou]).
Regular expressions can be quite complex, but they are a powerful tool for manipulating and
processing text.
________________________________________________________________________________
c. Is it possible to assign single value to more than one variable in python? if yes how it is
done explain with a simple example.
Yes, it is possible to assign a single value to multiple variables in Python. To do this, you can
use multiple assignment, which allows you to assign the same value to multiple variables at
the same time.
Here's an example of how you can use multiple assignment to assign a single value to
multiple variables:
x = y = z = 10
print(x) # Output: 10
print(y) # Output: 10
print(z) # Output: 10
In this example, we use multiple assignment to assign the value 10 to three variables, x, y,
and z, at the same time. Then we use print statements to verify that all three variables have
the same value.
You can also use multiple assignment to assign different values to multiple variables in a
single statement.
For example:
x, y, z = 1, 2, 3
print(x) # Output: 1
print(y) # Output: 2
print(z) # Output: 3
In this example, we use multiple assignment to assign the values 1, 2, and 3 to the variables x,
y, and z, respectively.
________________________________________________________________________________
Question 2.
In Python, the shift operators are the bitwise shift operators, which allow you to shift the
bits of an integer value to the left or the right. There are two shift operators in Python: <<,
which shifts the bits of a value to the left, and >>, which shifts the bits of a value to the
right.
Here are a few examples of how you can use the shift operators in Python:
# Shift left
x = 8 # Binary representation: 1000
y = x << 1 # Shift bits of x to the left by 1. Binary representation: 10000
print(y) # Output: 16
# Shift right
x = 16 # Binary representation: 10000
y = x >> 1 # Shift bits of x to the right by 1. Binary representation: 1000
print(y) # Output: 8
In these examples, we use the << operator to shift the bits of a value to the left, and the >>
operator to shift the bits of a value to the right. The number of places to shift the bits is
specified by an integer value following the operator.
For example, in the first example, we shift the bits of x (which has a value of 8) to the left
by 1 place, which has the effect of multiplying x by 2. The result is assigned to the variable y,
which has a value of 16.
Similarly, in the fourth example, we shift the bits of x (which has a value of 32) to the right
by 2 places, which has the effect of dividing x by 4. The result is assigned to the variable y,
which has a value of 8.
________________________________________________________________________________
b. What is set in python? How a set is created explain with a suitable example.
In python, a set is an unordered collection of unique elements and it does not allow duplicate
elements.
Sets are are not indexed, therefore we cannot change elements of a set after is declaration.
You can create a set in python using the set function or by enclosing a sequence of elements
in curly brackets { }.
Declaration syntax:
def function_name(parameters):
body...
For example:
def greet(name): ----> function definition
print("Hello, "+name+"good morning!")
greet("Aman ") ----> function call
Output: Hello, Aman good morning!
The function definition should always be present before the function call.
Multiple arguments:
Return statement:
Whenever the return statement is encountered inside a function then control of the program
goes back to the place from where the function has been called.
We can return result from the function and print the it where ever we want instead of
printing it inside the function, as we have done before.
Here:
def add_numbers(n1,n2):
result = n1 + n2
print("The sum is:",result)
add_numbers(10,10)
Remember if you are using return statement then always call a function by assigning it in a
variable so that we can use that variable to output the result.
For example:
def add_numbers(n1,n2):
result = n1 + n2
return result
sum = add_numbers(10,10)
print("The sum of the two numbers is:",sum)
Output: The sum of the two numbers is: 20
________________________________________________________________________________
Question 3.
The Python Standard Library is a collection of modules that are part of the Python runtime
environment and are available to all Python programs out of the box. These modules provide
a wide range of functionality, including string manipulation, data persistence, networking,
and more.
math: This module provides mathematical functions and constants, such as sqrt, pi, and e.
import math
x = math.sqrt(25)
print(x) # Output: 5.0
y = math.pi
print(y) # Output: 3.141592653589793
z = math.e
print(z) # Output: 2.718281828459045
datetime: This module provides classes for working with dates and times.
import datetime
now = datetime.datetime.now()
print(now) # Output: "2023-01-08 13:47:06.050129"
os: This module provides functions for interacting with the operating system, such as
creating and deleting files, changing directories, and more
import os
current_dir = os.getcwd()
print(current_dir) # Output: "/home/user/project"
os.chdir("/home/user")
new_dir = os.getcwd()
print(new_dir) # Output: "/home/user"
These are just a few examples of the many standard library modules available in Python. You
can find a full list of the Python Standard Library modules in the Python documentation.
________________________________________________________________________________
b. What are user defined exceptions in python explain with simple example
In Python, you can define your own exceptions by using raise keyword. This allows you to
create custom exceptions that can be raised and caught in your code.
Here's a simple example of how you can define and use a user-defined exception in Python:
y = “hello world”
if not type(y) == int:
raise Exception(“Please Enter Integer Value”)
User-defined exceptions can be useful when you want to create custom error handling logic
for specific scenarios in your code. You can define your own exception classes and raise
them as needed, and catch them using a try-except block or the raise keyword.
________________________________________________________________________________
c. How you can append data on to a file in python explain with simple example .
To append data to a file in Python, you can use the 'a' mode when opening the file, which
tells Python that you want to open the file in append mode. In append mode, any data you
write to the file will be added to the end of the file, rather than overwriting the existing
contents.
Here's a simple example of how you can append data to a file in Python:
In this example, we use a with statement to open the file 'myfile.txt' in append mode. Then
we use the write method to write some new data to the file. Finally, we open the file again
and read the contents, which includes the new data that we wrote to the file.
You can use the same approach to append multiple lines of data to a file. For example:
print(contents)
Output:
This is some new data.
This is some more new data.
This is even more new data.\n"
Keep in mind that when you open a file in append mode, any existing data in the file will not
be overwritten. Any data you write to the file will be added to the end of the file.
________________________________________________________________________________
Question 4.
In Python, character classes are used in regular expressions to match specific sets of
characters. A character class is represented as a set of characters enclosed in square
brackets ([]). For example, the character class [0123456789] matches any digit, and the
character class [a-z] matches any lowercase letter.
Here's an example of how you can use character classes in a regular expression in Python:
import re
string = "The quick brown fox jumps over the lazy dog."
In this example, we use the character class [aeiouAEIOU] to match any word that starts with
a vowel. The regular expression \b[aeiouAEIOU]\w+ searches for words that start with a
character in the set {a, e, i, o, u, A, E, I, O, U} and are followed by one or more word
characters (as indicated by \w+). The findall function returns a list of all the matches in the
string.
Character classes are a useful tool for creating more powerful and flexible regular
expressions in Python. They allow you to specify sets of characters that you want to match,
and can be combined with other regex elements to create more complex patterns.
b. What is data stream in python and how will you create your own data stream in python
explain with a simple example.
In Python, a data stream is an ordered sequence of data that can be read from or written to.
There are many types of data streams in Python, including file streams, network streams,
and in-memory streams.
To create your own data stream in Python, you can use the io module, which provides a set
of classes for working with data streams. For example, you can use the StringIO class to
create an in-memory data stream that you can read from or write to using the same
methods as a file object.
Here's a simple example of how you can create and use a data stream in Python:
import io
In this example, we use the StringIO class to create an in-memory data stream, and use the
write method to write some data to the stream. We then use the seek method to reset the
stream position to the beginning, and use the read method to read the data from the stream.
Finally, we close the stream using the close method.
You can use the same approach to create other types of data streams, such as file streams
and network streams, using the appropriate classes from the io module. Data streams are a
useful tool for working with data in a flexible and efficient way, and can be used in a wide
range of applications.
c. What is IDLE in python explain briefly in simple terms.
IDLE (Integrated Development and Learning Environment) is a built-in code editor for
Python. It is designed to be a simple and interactive environment for writing and executing
Python code, and is included with the standard Python distribution.
IDLE has a number of features that make it a useful tool for Python development, including:
A Python shell where you can enter and execute Python commands interactively.
A file browser that allows you to open and save Python files.
IDLE is a good choice for beginners who are just starting to learn Python, as it provides a
friendly and easy-to-use environment for experimenting with code and learning the
language. It is also useful for more advanced users who need a lightweight code editor for
Python development.
To start IDLE, you can open it from the Python interpreter or by running the idle command
from the command line. Once IDLE is open, you can create a new file or open an existing file
to edit and run your Python code. IDLE also includes a Python shell, where you can enter and
execute Python commands interactively.
IDLE is a cross-platform tool, which means that it is available for Windows, macOS, and
Linux. It is a convenient and user-friendly way to work with Python, and is especially well-
suited for beginners who are learning the language.
Overall, IDLE is a useful tool for writing and testing Python code, and is an important part of
the Python development environment.
________________________________________________________________________________
Question 5.
In Python, there are a set of naming conventions that are followed by most Python
developers to make code more readable and consistent. These conventions apply to variables,
functions, and other elements of Python code.
Constants should be written in all uppercase letters, with words separated by underscores.
For example: PI, MAX_VALUE, MIN_AGE.
Private variables, functions, and methods should be prefixed with an underscore (_). For
example: _private_var, _private_func, _private_method. This is a convention only, and does
not actually make the element private in Python.
Special methods, such as the __init__ method, should be written with double underscores
(__) on either side. For example: __init__, __str__, __repr__.
Following these naming conventions can help make your Python code more readable and
easier to understand for other developers. It is a good idea to get into the habit of following
these conventions from the start, as it will make your code more consistent and professional.
________________________________________________________________________________
b. What is dynamic type in python explain in simple terms with a suitable example.
In Python, variables do not have a fixed type, and the type of a variable can change at any
time during the execution of a program. This is known as dynamic typing, and it is one of the
key features of Python.
In this example, we first assign the integer value 10 to the variable x. When we check the
type of x, it is an int. However, we can then reassign a string value to x, and the type of x
becomes a str.
This demonstrates how the type of a variable in Python can change dynamically based on the
value it is assigned. This can be a useful feature, as it allows you to use a single variable for
different types of data without having to declare the type upfront.
However, it is important to be aware of the dynamic nature of variables in Python, as it can
sometimes lead to unexpected behavior if you are not careful. For example, you may
accidentally try to perform an operation on a variable that is not compatible with its current
type, which can cause an error.
c. What is environment variable in python explain in simple terms with a suitable example.
In Python, an environment variable is a value that can be passed to the operating system or
an application at runtime to configure system behavior or to provide additional information.
Environment variables are typically stored as key-value pairs, and can be accessed using the
os module in Python.
Here's a simple example of how you can set and access an environment variable in Python:
import os
In this example, we use the os.environ dictionary to set the value of the MY_VAR
environment variable to "hello". We can then access the value of the environment variable by
reading it from the os.
________________________________________________________________________________