Python Que Bank Answers
Python Que Bank Answers
Python Que Bank Answers
Introduction to Python:
• Question: What is Python and why is it popular?
• Answer: Python is a high-level, interpreted programming
language known for its simplicity and readability. Its versatility
allows developers to use it in various domains, such as web
development, data science, artificial intelligence, and more.
Python's syntax emphasizes code readability, making it an
excellent choice for beginners and experienced developers
alike.
2. Defining a Variable and Assigning a Value:
• Question: How do you create a variable and assign a value in
Python?
• Answer: To create a variable in Python, you simply choose a
name and use the assignment operator (=) to associate it with
a value. For example, x = 10 creates a variable named x and
assigns the value 10 to it. Python is dynamically typed,
meaning you don't need to explicitly declare the variable's
type.
3. Supported Comment Lines in Python:
• Question: What types of comments does Python support?
• Answer: Python supports two types of comments: single-line
comments, indicated by the # symbol, and multi-line
comments enclosed in triple quotes (''' or """). Single-line
comments are used for brief explanations, while multi-line
comments are typically used for more extensive documentation
or commenting out multiple lines of code.
4. Inbuilt Data Types:
• Question: What are the built-in data types in Python?
• Answer: Python has several built-in data types, including
integers (int), floating-point numbers (float), strings (str),
booleans (bool), lists (list), tuples (tuple), sets (set),
dictionaries (dict), and more. Each data type serves specific
purposes and allows for versatile programming.
5. Input/Output Functions in Python:
• Question: What are the input/output functions in Python, and
how are they used?
• Answer: Two commonly used functions for input in Python are
input() and raw_input() (in Python 2). input() reads user
input as a string, and raw_input() (Python 2) is used
similarly. For output, print() is widely used to display
information. Python 3 does not have raw_input(), and
input() functions handle both string and numerical input.
print() can display variables, strings, or expressions. The
ᴇɴɢɪɴᴇᴇʀ
combination of these functions facilitates interactive and
informative programs.
List:
Tuple:
Set:
Dictionary:
Types of Operators:
ᴇɴɢɪɴᴇᴇʀ
• Bitwise Operators: Manipulate individual bits in binary
representation.
• Usage: x in sequence
• Example: 5 in [1, 2, 3, 4, 5] returns True.
• Explanation: Checks if the value on the left is present in the
sequence on the right.
Bitwise Operators:
String:
String Functions:
ᴇɴɢɪɴᴇᴇʀ
3. insert(): Inserts an element at a specified position.
4. remove(): Removes the first occurrence of a specified element.
5. pop(): Removes and returns the element at a specified index.
6. index(): Returns the index of the first occurrence of a specified
element.
7. count(): Returns the number of occurrences of a specified element.
8. sort(): Sorts the elements of the list in ascending order.
9. reverse(): Reverses the order of the list.
Types of Functions:
Explanation:
ᴇɴɢɪɴᴇᴇʀ
• Pure vs. Impure Functions: Relate to the predictability and
reliability of functions.
pythonCopy code
for i in range(5):
print(i)
This loop will iterate over the numbers 0 to 4, making it easier to control
and iterate through a specific range of values.
pythonCopy code
x = 10 if x > 10 : print ( "x is greater than 10" ) elif x == 10: print ("x is
equal to 10" ) else : print ("x is less than 10" ) x = 10
if x > 10:
print("x is greater than 10")
elif x == 10:
print("x is equal to 10")
else:
print("x is less than 10")
ᴇɴɢɪɴᴇᴇʀ
In this example, the program checks the value of x and executes
different blocks of code based on whether it's greater than, equal to, or
less than 10.
for i in range(5):
if i == 3:
break
print(i)
This loop will print values 0, 1, and 2. The break statement is used to
exit the loop when i is equal to 3.
Answer:
def is_prime(num):
if num < 2:
return False
if num % i == 0:
return False
return True
ᴇɴɢɪɴᴇᴇʀ
print(f"Prime numbers till {N}:")
if is_prime(i):
print(i)
def is_palindrome(word):
if is_palindrome(input_word):
print(f"{input_word} is a palindrome.")
else:
These programs display prime numbers till a specified value (N) and
check whether a given word is a palindrome or not.
UNIT-2
ᴇɴɢɪɴᴇᴇʀ
• Hierarchical Inheritance: Multiple classes inherit from a
single base class, creating a tree-like structure.
2. Compile Time vs. Runtime Polymorphism in Python:
• Compile Time Polymorphism: In Python, it's achieved
through function overloading, where a function behaves
differently based on the number or types of its parameters.
• Runtime Polymorphism: Python achieves this through
method overriding in classes, where a subclass provides a
specific implementation of a method that is already defined in
its superclass.
3. Access Modifiers in Python:
• Public: Members are accessible from anywhere.
• Private: Members are accessible only within the class using
double underscores (e.g., __variable).
• Protected: Members are accessible within the class and its
subclasses using a single underscore (e.g., _variable).
• No Keyword (Public by default): Members are accessible
from anywhere.
4. Multiple Inheritance in Python: Multiple inheritance is supported
in Python. Here's an example:
pythonCopy code
5. class A:
6. def display(self):
7. print("Class A")
8.
9. class B(A):
10. def show(self):
11. print("Class B")
12.
13. class C(A):
14. def print(self):
15. print("Class C")
16.
17. class D(B, C):
18. pass
19.
20. obj = D()
obj.display() # Output: Class A
ᴇɴɢɪɴᴇᴇʀ
• Default Constructor: Automatically created if no constructor
is defined.
• Parameterized Constructor: Accepts parameters during
object creation.
• Constructor Overloading: Python doesn't support explicit
constructor overloading, but you can use default values for
parameters to achieve a similar effect.
• Special Constructor (init): The __init__ method is a special
constructor in Python, invoked when an object is created.
pythonCopy code
class Parent:
def __init__(self, name):
self.name = name
def display(self):
print("Parent class:", self.name)
class Child(Parent):
def __init__(self, name, age):
super().__init__(name)
self.age = age
def display(self):
super().display()
print("Child class:", self.age)
# Example usage
child_obj = Child("John", 25)
child_obj.display()
ᴇɴɢɪɴᴇᴇʀ
In this example, the super() function is used to call the display()
method of the parent class from within the child class, ensuring that both
the parent and child methods are executed.
7. What is the self keyword? What is the use of the self keyword?
pythonCopy code
class MyClass:
def __init__(self, value):
self.value = value
def display(self):
print("Value:", self.value)
# Example usage
obj = MyClass(10)
obj.display()
Answer: In Python, the try, except, and finally clauses are used for
exception handling. The try block contains the code that might raise an
exception, the except block handles the exception, and the finally block
contains code that will be executed regardless of whether an exception
occurs or not.
pythonCopy code
try:
ᴇɴɢɪɴᴇᴇʀ
x = 10 / 0 # This will raise a ZeroDivisionError
except ZeroDivisionError:
print("Cannot divide by zero!")
finally:
print("This will be executed no matter what.")
pythonCopy code
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius * self.radius
# Example usage
circle_obj = Circle(5)
print("Circle Area:", circle_obj.area())
ᴇɴɢɪɴᴇᴇʀ
common interface (e.g., area()) for different shapes without specifying
how each shape calculates its area.
Answer: To read a file in Python, you can use the open() function to
open a file and then use methods like read() or readlines() to access
the file's content.
pythonCopy code
# Reading a file
with open('example.txt', 'r') as file:
content = file.read()
print(content)
To write to a file, use the open() function with the mode 'w' for writing.
You can then use methods like write() to add content to the file.
pythonCopy code
# Writing to a file
with open('example_write.txt', 'w') as file:
file.write('Hello, this is a sample text.')
The with statement is used to ensure that the file is properly closed after
reading or writing. This helps in managing resources efficiently.
# Answer 1:
# You can use the following Python program to achieve this:
ᴇɴɢɪɴᴇᴇʀ
# Answer 2:
# The program uses a loop to iterate through the first 100 natural
numbers (50 even and 50 odd).
# It checks whether the current number is even or odd using the
modulo operator (%).
# If the number is even, it is written to the "even.txt" file;
otherwise, it is written to the "odd.txt" file.
# Answer 3:
# 1. Open two files, "even.txt" and "odd.txt", in write mode.
# 2. Iterate through the range of numbers from 1 to 101
(exclusive).
# 3. Check if the number is even or odd using the modulo
operator (%).
# 4. Write the even numbers to "even.txt" and odd numbers to
"odd.txt".
# 5. Close both files after writing.
# Answer 4:
# Save the following code in a Python file, for example,
"even_odd_writer.py".
# Run the script using a Python interpreter: `python
even_odd_writer.py`.
ᴇɴɢɪɴᴇᴇʀ
even_file = open("even.txt", "w")
odd_file = open("odd.txt", "w")
even_file.close()
odd_file.close()
This program creates two files, "even.txt" and "odd.txt," and writes the
first 50 even and odd numbers into their respective files. It uses a simple
loop and the modulo operator to determine whether a number is even or
odd. The even numbers are written to "even.txt," and the odd numbers
are written to "odd.txt." Finally, both files are closed.
ᴇɴɢɪɴᴇᴇʀ