Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
31 views14 pages

Python Que Bank Answers

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 14

1.

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.

6. Difference between list, tuple, set, dictionary?

List:

• Mutable: Lists can be modified after creation.


• Syntax: Declared using square brackets [].
• Example: my_list = [1, 2, 3]

Tuple:

• Immutable: Tuples cannot be modified once created.


• Syntax: Declared using parentheses ().
• Example: my_tuple = (1, 2, 3)

Set:

• Mutable: Sets can be modified, but they do not allow duplicate


elements.
• Syntax: Declared using curly braces {}.
• Example: my_set = {1, 2, 3}

Dictionary:

• Key-Value Pair: Dictionaries store data in key-value pairs.


• Syntax: Declared using curly braces with key-value pairs.
• Example: my_dict = {'key1': 'value1', 'key2': 'value2'}

7. Types of operators in python, explain membership and bitwise


operator in details.

Types of Operators:

• Arithmetic Operators: Perform basic arithmetic operations.


• Comparison Operators: Compare values and return Boolean
results.
• Logical Operators: Combine conditional statements.
• Assignment Operators: Assign values to variables.
• Membership Operators: Test if a value is a member of a
sequence.

ᴇɴɢɪɴᴇᴇʀ
• Bitwise Operators: Manipulate individual bits in binary
representation.

Membership Operator - in:

• 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:

• & (AND), | (OR), ^ (XOR), ~ (NOT), << (Left Shift), >>


(Right Shift).
• Example: x & y performs bitwise AND of x and y.
• Explanation: Bitwise operators manipulate individual bits of
integers.

8. What is string? Explain all the string functions.

String:

• Definition: A sequence of characters, represented in Python using


single (' '), double (" "), or triple (''' ''' or """ """) quotes.

String Functions:

1. len(): Returns the length of the string.


2. upper(): Converts all characters to uppercase.
3. lower(): Converts all characters to lowercase.
4. strip(): Removes leading and trailing whitespaces.
5. split(): Splits the string into a list of substrings based on a
delimiter.
6. join(): Joins elements of a sequence into a string using the
specified delimiter.
7. find(): Returns the index of the first occurrence of a substring.
8. replace(): Replaces a specified substring with another string.

9. Explain all List inbuilt functions. How do you remove an item


from the list.

List Inbuilt Functions:

1. append(): Adds an element to the end of the list.


2. extend(): Extends the list by appending elements from another list.

ᴇɴɢɪɴᴇᴇʀ
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.

Removing an Item from List:

• Using remove(): my_list.remove(3) removes the first


occurrence of '3'.
• Using pop(): my_list.pop(1) removes and returns the element at
index 1.

10. What are the types of functions? Explain in detail.

Types of Functions:

1. Built-in Functions: Pre-defined functions provided by Python (e.g.,


len(), print()).
2. User-Defined Functions: Functions created by the user to perform
specific tasks.
3. Anonymous Functions (Lambda Functions): Small, one-line
functions defined without a name using the lambda keyword.
4. Recursive Functions: Functions that call themselves during their
execution.
5. Higher-Order Functions: Functions that take other functions as
arguments or return functions as results.
6. Pure Functions: Functions with no side effects, producing the same
output for the same input, and not modifying external state.
7. Impure Functions: Functions with side effects, modifying external
state or producing different output for the same input.

Explanation:

• Built-in Functions: Provided by Python for common operations.


• User-Defined Functions: Created to modularize code and perform
specific tasks.
• Lambda Functions: Concise, used for short-term operations.
• Recursive Functions: Useful for solving problems with repetitive
structures.
• Higher-Order Functions: Enable functional programming
paradigms.

ᴇɴɢɪɴᴇᴇʀ
• Pure vs. Impure Functions: Relate to the predictability and
reliability of functions.

11. What is the use of the range function in a for loop?

Answer: The range function in Python is used to generate a sequence of


numbers that is often used in the context of a for loop. It produces a
range object representing a sequence of numbers from start (inclusive)
to stop (exclusive) with a specified step value. This is particularly useful
in iterating over a specific range of values in a loop. For example:

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.

12. What are the condition control statements? With example

Answer: Condition control statements in Python are used to control the


flow of a program based on certain conditions. The key ones are if, elif
(else if), and else. Here's an example:

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.

13. Jump statements in Python

Answer: Jump statements in Python are used to control the flow of a


program by explicitly altering the normal execution sequence. The key
jump statements are break, continue, and return. For example:

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.

14. Write a Python program to display prime numbers till N value.


Write a program to check for palindrome

Answer:

# Program to display prime numbers till N

def is_prime(num):

if num < 2:

return False

for i in range(2, int(num**0.5) + 1):

if num % i == 0:

return False

return True

N = 20 # Replace with desired value

ᴇɴɢɪɴᴇᴇʀ
print(f"Prime numbers till {N}:")

for i in range(2, N + 1):

if is_prime(i):

print(i)

# Program to check for palindrome

def is_palindrome(word):

return word == word[::-1]

input_word = "radar" # Replace with desired word

if is_palindrome(input_word):

print(f"{input_word} is a palindrome.")

else:

print(f"{input_word} is not a palindrome.")

These programs display prime numbers till a specified value (N) and
check whether a given word is a palindrome or not.

UNIT-2

1. Types of Inheritance in Python:


• Single Inheritance: A class can inherit from only one parent
class.
• Multiple Inheritance: A class can inherit from more than one
class.
• Multilevel Inheritance: A class can inherit from a parent
class, and then another class can inherit from this derived
class, forming a chain.

ᴇɴɢɪɴᴇᴇʀ
• 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

Constructor and its Types in Python:

ᴇɴɢɪɴᴇᴇʀ
• 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.

6. What is super function? Explain with a suitable program.

Answer: The super() function in Python is used to call a method from


the parent class. It is often used in the context of inheritance to invoke
the method of the superclass. This ensures that the method from the
parent class is executed before the method in the child class.

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?

Answer: In Python, self is a conventionally used keyword that refers to


the instance of the class. It is the first parameter in the definition of a
method in a class and is used to access the instance variables and
methods of that class.

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()

Here, self is used to reference the instance variable value. It allows


each instance of the class to have its own unique values for variables,
preventing them from interfering with each other.

8. What is the try-except and finally clause? Explain with an


example.

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.")

In this example, if a ZeroDivisionError occurs in the try block, the


corresponding except block is executed. The finally block is then
executed regardless of whether an exception occurred, making it suitable
for cleanup or resource release.

9. What is abstraction? How is it used? Explain in detail.

Answer: Abstraction is a concept in object-oriented programming that


involves hiding the complex implementation details of an object and
exposing only the essential features. It allows the programmer to focus
on the functionality of an object without worrying about its internal
workings.

pythonCopy code

from abc import ABC, abstractmethod

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())

In this example, Shape is an abstract base class with an abstract method


area(). The Circle class inherits from Shape and provides a concrete
implementation of the area() method. Abstraction allows us to define a

ᴇɴɢɪɴᴇᴇʀ
common interface (e.g., area()) for different shapes without specifying
how each shape calculates its area.

10. How to read and write a file? Explain in detail.

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.

# Question 1: How can I create a program in Python to generate


and write the first 50 even and odd numbers into separate files?

# Answer 1:
# You can use the following Python program to achieve this:

# Question 2: How does the program work?

ᴇɴɢɪɴᴇᴇʀ
# 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.

# Question 3: Can you explain the steps of the program?

# 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.

# Question 4: How can I run this program?

# 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`.

# Python program to write first 50 even and odd numbers into


separate files

ᴇɴɢɪɴᴇᴇʀ
even_file = open("even.txt", "w")
odd_file = open("odd.txt", "w")

for num in range(1, 101):


if num % 2 == 0:
even_file.write(str(num) + "\n")
else:
odd_file.write(str(num) + "\n")

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.

ᴇɴɢɪɴᴇᴇʀ

You might also like