0% found this document useful (0 votes)
2 views67 pages

Python Interview Questions

Uploaded by

makot93318
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views67 pages

Python Interview Questions

Uploaded by

makot93318
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Interview Questions

1. Explain Python?

Answer:
Python is a highly comprehensive, interactive, and object-oriented script writing language. It
was developed to make the content highly readable among net surfers. Python makes use of
various English keywords other than just punctuations.

2. What are the distinct features of Python?

Answer:

● Structured and functional programming are supported.


● It can be compiled to byte-code for creating larger applications.
● Develops high-level dynamic data types.
● Supports checking of dynamic data types.
● Applies automated garbage collection.
● It could be used effectively along with Java, COBRA, C, C++, ActiveX, and COM.

3. What is the Python path?

Answer:
A Python path tells the Python interpreter to locate the module files that can be imported
into the program. It includes the Python source library directory and source code directory.

4. What are the supported standard data types in Python?

Answer:
The supported standard data types in Python include the following:

● List
● Number
● String
● Dictionary
● Tuples

5. Define tuples in Python.

Answer:
Tuples is a sequence data type in Python. The number of values in tuples is separated by
commas.

6. What are the positive and negative indices?


Answer:
Positive indices are applied when the search begins from left to right. Negative indices are
used when the search begins from right to left. For example, in an array list of size n, the
positive index starts at 0 and goes up to n-1, while the negative index starts at -n and goes
up to -1.

7. What can be the length of the identifier in Python?

Answer:
The length of the identifier in Python can be of any length. However, the longest identifier
will violate from PEP–8 and PEP–20.

8. Define Pass statement in Python.

Answer:
A Pass statement in Python is used when we cannot decide what to do in our code, but we
must type something to make it syntactically correct.

9. What are the limitations of Python?

Answer:
There are certain limitations of Python, which include:

● It has design restrictions.


● It is slower when compared with C, C++, or Java.
● It is inefficient in mobile computing.
● It consists of an underdeveloped database access layer.

10. Do runtime errors exist in Python? Give an example.

Answer:
Yes, runtime errors exist in Python. For example, if you are duck typing and something
looks like a duck, it is considered as a duck even if it is just a flag or stamp.

Example:

print “Hackr io” # This will result in a runtime error due to missing parentheses in Python 3.

11. Why do we need a break in Python?

Answer:
The break statement helps control the Python loop by stopping the current loop's execution
and transferring control to the next block.

12. Why do we need to continue in Python?

Answer:
The continue statement helps control the Python loop by making jumps to the next
iteration of the loop without exhausting it.
13. Can we use a break and continue together in Python? How?

Answer:

Yes, break and continue can be used together in Python. The break stops the current loop
from execution, while continue jumps to the next iteration of the loop.

14. Does Python support an intrinsic do-while loop?

Answer:

No, Python does not support an intrinsic do-while loop.

15. How many ways can be applied for applying reverse string?

Answer:
There are five ways to reverse a string, including:

● Loop
● Recursion
● Stack
● Extended Slice Syntax
● Reversed

16. What are the different stages of the Life Cycle of a Thread?

Answer:
The different stages of the Life Cycle of a Thread are as follows:

1. Stage 1: Creating a class where we can override the run method of the Thread
class.
2. Stage 2: Calling start() on the new thread. The thread is then taken forward for
scheduling.
3. Stage 3: Execution takes place where the thread starts execution and reaches the
running state.
4. Stage 4: Thread waits until methods like join() and sleep() are called.
5. Stage 5: After waiting for execution, the thread is sent for scheduling again.
6. Stage 6: The running thread completes its execution and terminates, reaching the
dead state.

17. What is the purpose of relational operators in Python?

Answer:
The purpose of relational operators in Python is to compare values.

18. What are assignment operators in Python?


Answer:
Assignment operators in Python combine arithmetic operations with the assignment symbol.
For example, +=, -=, *=, etc.

19. Why do we need membership operators in Python?

Answer:
Membership operators in Python confirm if a value is a member of a sequence or not. For
example, in and not in.

20. How are identity operators different from the membership operators?

Answer:
Identity operators (is, is not) compare objects to check if they are the same object, while
membership operators (in, not in) check if an element exists within a sequence.

21. Describe how multithreading is achieved in Python.

Answer:
Multithreading in Python is achieved using the threading module. However, Python has a
Global Interpreter Lock (GIL) that allows only one thread to execute at a time in a single
process. This means threads take turns using the CPU, giving the illusion of parallel
execution.

22. What is Inheritance in Python?

Answer:
Inheritance allows a class (child class) to acquire all the attributes and methods of another
class (parent class). It promotes code reuse and simplifies application maintenance.

23. What are the different types of inheritance?

Answer:
The types of inheritance in Python are:

● Single Inheritance: A single derived class inherits from one superclass.


● Multi-Level Inheritance: A derived class inherits from another derived class.
● Hierarchical Inheritance: Multiple derived classes inherit from a single superclass.
● Multiple Inheritance: A derived class inherits from multiple superclasses.

24. Explain memory management in Python.

Answer:
Memory management in Python is handled by:

● Private Heap Space: Stores Python objects and data structures.


● Memory Manager: Allocates memory for Python objects.
● Garbage Collector: Recycles unused memory to make it available for heap space.

25. What are Python decorators?


Answer:
Python decorators are functions that modify the behavior of other functions or methods.
They allow specific changes to be made to functions without altering their structure.

26. What do you understand by the process of compilation and linking in Python?

Answer:

In Python, compilation transforms the source code into bytecode, which is executed by the
interpreter. Linking happens when combining compiled code with libraries or dependencies,
especially in dynamic loading scenarios.

27. What is the map() function used for in Python?

Answer:
The map() function applies a given function to each item of an iterable (like a list) and
returns a map object (an iterator).

Example:

result = map(lambda x: x**2, [1, 2, 3, 4])

print(list(result)) # Output: [1, 4, 9, 16]

28. How will you distinguish between NumPy and SciPy?

Answer:

● NumPy: Focuses on arrays, basic element-wise operations, indexing, and reshaping.


● SciPy: Built on NumPy and provides additional modules for optimization, integration,
and advanced mathematics.

29. What is the lambda function?

Answer:
A lambda function is an anonymous, single-expression function.

Example:

square = lambda x: x ** 2

print(square(5)) # Output: 25

30. Differentiate between list and tuple.

Answer:

● List: Mutable, can contain duplicate elements, represented by [].


● Tuple: Immutable, hashable, can be used as dictionary keys, represented by ().
31. What is the // operator? What is its use?

Answer:
The // operator performs floor division, returning the integer part of a division.

Example:

print(10 // 3) # Output: 3

32. What is monkey patching in Python?

Answer:
Monkey patching refers to dynamically modifying or extending a class or module during
runtime.

33. What is the split() function used for?

Answer:
The split() function breaks a string into a list of substrings based on a specified
separator.

Example:

text = "Hello World"

print([Link]()) # Output: ['Hello', 'World']

34. Explain the Dogpile effect.

Answer:
The Dogpile effect occurs when the cache expires, and multiple requests hit the server
simultaneously. It can be mitigated using semaphore locks.

35. What is a pass in Python?

Answer:
The pass statement is a placeholder that does nothing. It is used in blocks where code is
syntactically required but not yet implemented.

36. Define slicing in Python.

Answer:
Slicing allows extracting a subset of elements from sequences like lists, tuples, or strings
using [start:stop:step].

37. What are docstrings?

Answer:
Docstrings are documentation strings used to describe Python modules, classes, or
functions. They are written as triple-quoted strings.
38. What is [::-1] used for?

Answer:
[::-1] is used to reverse a sequence (string, list, etc.).

Example:

text = "Python"

print(text[::-1]) # Output: "nohtyP"

39. Define Python Iterators.

Answer:
Iterators are objects that implement the __iter__() and __next__() methods, allowing
traversal of elements in a container like a list or tuple.

40. How are comments written in Python?

Answer:
Comments in Python start with a # for single-line comments. Multi-line comments are
written using triple quotes (""" or ''').

41. How do you capitalize the first letter of a string?

Answer:
You can use the capitalize() method to capitalize the first letter of a string.

Example:

text = "python"

print([Link]()) # Output: "Python"

42. What is is, not, and in operators?

Answer:

● is: Returns True if two variables point to the same object.


● not: Returns the inverse of a boolean value.
● in: Checks if an element exists within a sequence.

43. How are files deleted in Python?

Answer:
Files are deleted using the os module.

Example:

import os
[Link]("[Link]")

44. Does Python support multiple inheritance?

Answer:
Yes, Python supports multiple inheritance, allowing a class to inherit from more than one
parent class.

45. What does the method object() do?

Answer:
The object() method returns a featureless object that serves as the base for all classes.

46. What is PEP 8?

Answer:
PEP 8 is the Python Enhancement Proposal that provides guidelines and best practices for
writing clean, readable, and consistent Python code.

47. What is a namespace in Python?

Answer:
A namespace is a system that ensures unique names for variables and objects to prevent
naming conflicts.

48. Is indentation necessary in Python?

Answer:
Yes, indentation is mandatory in Python. It defines the block structure of the code and
ensures proper execution.

49. Discuss some characteristics of the Python programming language.

Answer:

● Object-oriented and dynamically typed.


● Easy-to-read syntax.
● Interpreted language.
● Extensive libraries for data analysis, visualization, and machine learning.
● Compatible with all major operating systems.

50. What are some of Python's core default modules?

Answer:
Some core default modules include:

● os: For interacting with the operating system.


● math: For mathematical operations.
● datetime: For date and time handling.
● random: For generating random numbers.
51. Discuss the frameworks for app development that are popular with Python users.

Answer:
Popular Python frameworks include:

● Web frameworks: Django, Flask, Pyramid.


● Mobile app frameworks: Kivy, BeeWare.

52. How does Python manage memory?

Answer:
Memory in Python is managed using private heap space, the memory manager, and
garbage collection.

53. Explain and give an example of inheritance.

Answer:
Inheritance allows a child class to acquire properties and methods from a parent class.
Example:

class Parent:

def greet(self):

print("Hello from Parent")

class Child(Parent):

pass

obj = Child()

[Link]() # Output: Hello from Parent

54. What are arrays in Python?

Answer:
Arrays are used to store multiple items of the same type in a single variable. While Python
does not have a built-in array type, lists and libraries like NumPy are commonly used.

55. Differentiate between List, Tuple, Set, and Dictionary.

Answer:

● List: Mutable, allows duplicates, ordered.


● Tuple: Immutable, allows duplicates, ordered.
● Set: Mutable, does not allow duplicates, unordered.
● Dictionary: Mutable, stores key-value pairs, ordered from Python 3.7 onward.

56. What are the benefits of using Python in the current scenario?
Answer:

● Extensive library support for data analysis, machine learning, and web development.
● Open-source and community-driven.
● Platform-independent.
● User-friendly syntax.

57. What is the difference between mutable and immutable data types?

Answer:

● Mutable: Can be changed after creation (e.g., list, dictionary).


● Immutable: Cannot be changed after creation (e.g., string, tuple).

58. What is the swapcase() function in Python?

Answer:
The swapcase() function changes the case of all letters in a string: uppercase becomes
lowercase and vice versa.
Example:

text = "Python"

print([Link]()) # Output: "pYTHON"

59. How is exception handling done in Python?

Answer:
Exception handling in Python uses try, except, and finally blocks:

try:

x=1/0

except ZeroDivisionError:

print("Cannot divide by zero!")

finally:

print("Execution complete.")

60. Is indentation required in Python?

Answer:
Yes, indentation is required to define the structure of code blocks.

61. What is the difference between a shallow copy and a deep copy?

Answer:
● Shallow copy: Copies only the reference to objects, not the objects themselves.
● Deep copy: Creates a new copy of all objects.

62. What are decorators?

Answer:
Decorators modify or enhance the behavior of a function or method without permanently
modifying it.
Example:

def decorator(func):

def wrapper():

print("Before function call")

func()

print("After function call")

return wrapper

@decorator

def say_hello():

print("Hello!")

say_hello()

63. What is the difference between / and // in Python?

Answer:

● /: Performs floating-point division.


● //: Performs floor division, returning the integer part of the quotient.

64. What is the difference between xrange and range functions?

Answer:

● Python 2:
○ range(): Returns a list.
○ xrange(): Returns an iterator for memory efficiency.
● Python 3: Only range() is available, and it behaves like xrange() from Python 2.

65. Define encapsulation in Python.


Answer:
Encapsulation means bundling data and methods that operate on that data into a single unit
(class). It also includes restricting direct access to some components for security.

66. How do you perform data abstraction in Python?

Answer:
Data abstraction in Python is achieved by using abstract classes and interfaces, hiding
implementation details while exposing only the necessary functionalities.

67. How do you delete a file using Python?

Answer:

You can delete a file using the os module:

import os

[Link]("[Link]")

68. What is slicing in Python?

Answer:

Python Slicing is a string operation for extracting a part of the string, or some part of a
list. With this operator, one can specify where to start the slicing, where to end, and
specify the step. List slicing returns a new list from the existing list.

Syntax: Lst[ Initial : End : IndexJump ]

69. What is a namespace in Python?

Answer:
A namespace is a naming system used to make sure that names are unique to avoid
naming conflicts.

70. What is PIP?

Answer:
PIP is an acronym for Python Installer Package which provides a seamless interface to
install various Python modules. It is a command-line tool that can search for packages over
the internet and install them without any user interaction.

71. What is a zip function?

Answer:
Python zip() function returns a zip object, which maps a similar index of multiple
containers. It takes an iterable, converts it into an iterator, and aggregates the elements
based on iterables passed. It returns an iterator of tuples.
72. What are Pickling and Unpickling?

Answer:
The Pickle module accepts any Python object and converts it into a string representation
and dumps it into a file by using the dump function; this process is called pickling. While the
process of retrieving original Python objects from the stored string representation is called
unpickling.

73. What are Function Annotations in Python?

Answer:
Function Annotation is a feature that allows you to add metadata to function parameters and
return values. This way, you can specify the input type of the function parameters and the
return type of the value the function returns.

Function annotations are arbitrary Python expressions that are associated with various parts
of functions. These expressions are evaluated at compile time and have no life in Python’s
runtime environment. Python does not attach any meaning to these annotations. They take
life when interpreted by third-party libraries, for example, mypy.

74. What are Exception Groups in Python?

Answer:
The latest feature of Python 3.11, Exception Groups. The ExceptionGroup can be handled
using a new except* syntax. The * symbol indicates that multiple exceptions can be
handled by each except* clause.

ExceptionGroup is a collection/group of different kinds of Exception. Without creating


Multiple Exceptions, we can group together different Exceptions which we can later fetch
one by one whenever necessary; the order in which the Exceptions are stored in the
Exception Group doesn’t matter while calling them.

try:

raise ExceptionGroup('Example ExceptionGroup', (

TypeError('Example TypeError'),

ValueError('Example ValueError'),

KeyError('Example KeyError'),

AttributeError('Example AttributeError')

))

except* TypeError:

pass
except* ValueError as e:

pass

except* (KeyError, AttributeError) as e:

pass

75. What is Python Switch Statement?

Answer:
From version 3.10 upward, Python has implemented a switch-case feature called “structural
pattern matching.” You can implement this feature with the match and case keywords. Note
that the underscore symbol is used to define a default case for the switch statement in
Python.

Note: Before Python 3.10, Python didn't support match statements.

match term:

case pattern-1:

action-1

case pattern-2:

action-2

case pattern-3:

action-3

case _:

action-default

76. What is a Walrus Operator?

Answer:
The Walrus Operator allows you to assign a value to a variable within an expression. This
can be useful when you need to use a value multiple times in a loop but don’t want to repeat
the calculation.

The Walrus Operator is represented by the := syntax and can be used in a variety of
contexts, including while loops and if statements.

Note: Python versions before 3.8 don't support the Walrus Operator.

names = ["Jacob", "Joe", "Jim"]

if (name := input("Enter a name: ")) in names:


print(f"Hello, {name}!")

else:

print("Name not found.")

77. What are Access Specifiers in Python?

Answer:
Python uses the _ symbol to determine the access control for a specific data member or a
member function of a class. A Class in Python has three types of Python access modifiers:

● Public Access Modifier: The members of a class that are declared public are easily
accessible from any part of the program. All data members and member functions of
a class are public by default.
● Protected Access Modifier: The members of a class that are declared protected are
only accessible to a class derived from it. All data members of a class are declared
protected by adding a single underscore _ symbol before the data members of that
class.
● Private Access Modifier: The members of a class that are declared private are
accessible within the class only; the private access modifier is the most secure
access modifier. Data members of a class are declared private by adding a double
underscore __ symbol before the data member of that class.

78. Python Global Interpreter Lock (GIL)?

Answer:
Python Global Interpreter Lock (GIL) is a type of process lock that is used by Python
whenever it deals with processes. Generally, Python uses only one thread to execute the set
of written statements. The performance of the single-threaded process and the multi-
threaded process will be the same in Python, and this is because of GIL in Python. We
cannot achieve multithreading in Python because we have a global interpreter lock that
restricts the threads and works as a single thread.

79. What is __init__() in Python?

Answer:
The __init__() method in Python is equivalent to constructors in OOP terminology. It is a
reserved method in Python classes and is called automatically whenever a new object is
instantiated. This method is used to initialize the object’s attributes with values. While
__init__() initializes the object, it does not allocate memory. Memory allocation for a new
object is handled by the __new__() method, which is called before __init__().

80. What is PYTHONPATH?

Answer:
PYTHONPATH is an environment variable that is used when a module is imported.
Whenever a module is imported, PYTHONPATH is also looked up to check for the presence
of the imported modules in various directories. The interpreter uses it to determine which
module to load.

81. What is the Python Standard Library?

Answer:
A collection of modules and packages that come pre-installed with Python, providing
solutions for common programming tasks like file handling, math operations, and data
serialization.

82. List some commonly used libraries in the Python Standard Library and their
purposes.

Answer:

● os: Interacting with the operating system.


● sys: Command-line arguments and Python runtime.
● math: Mathematical operations.
● datetime: Handling dates and times.
● random: Generating random numbers.

83. What are the advantages of using the Python Standard Library?

Answer:

● No installation required.
● Well-documented.
● Optimized for performance.

84. How does the os module help in interacting with the operating system?

Answer:
The os module provides methods to interact with the file system, execute shell commands,
and manipulate environment variables.

85. What is the purpose of the json library in Python?

Answer:
The json library is used to serialize and deserialize JSON data, enabling easy data
exchange between systems.

86. Explain the role of the csv library in Python.

Answer:
The csv library allows reading from and writing to CSV (Comma-Separated Values) files.

87. When would you use the re module in Python?

Answer:
The re module is used when working with pattern matching or searching for patterns in text
using regular expressions.

88. How does the sys module differ from the os module?

Answer:
The sys module deals with the Python runtime environment (e.g., command-line
arguments), while the os module interacts with the operating system's file and directory
structure.

89. What is the difference between a module and a package in Python?

Answer:

● Module: A single Python file containing definitions and functions.


● Package: A collection of modules organized into a directory with an __init__.py
file.

90. Why is the Python Standard Library considered efficient for development?

Answer:
It saves time by providing pre-built, tested, and optimized tools for common programming
tasks.

91. How do you import a library in Python? Provide an example.

Answer:

import math

print([Link](16)) # Output: 4.0

92. What is the difference between import math and from math import sqrt?

Answer:

● import math: Imports the entire module, and functions must be called as
[Link].
● from math import sqrt: Imports only the sqrt function, which can be called
directly as sqrt.

93. Why would you use an alias when importing a library? Provide an example.

Answer:
To shorten library names for convenience. Example:

import numpy as np

94. What happens if you import two libraries with the same function names?
Answer:
The function from the most recent import will overwrite the earlier one.

95. How can you import multiple specific functions from a library? Give an example.

Answer:

from math import sqrt, ceil

96. What is the purpose of dir() when working with imported libraries?

Answer:
dir() lists all the available attributes and methods in a module. Example:

import math

print(dir(math))

97. Explain what happens if you try to use a library without importing it first.

Answer:

Python raises a NameError because the module is not recognized.

98. How can you check if a specific module is part of the Python Standard Library?

Answer:
Check the Python documentation for the Standard Library.

99. What are the risks of importing all functions using from module import *?

Answer:
Namespace conflicts may occur if multiple modules have functions with the same name.

100. Demonstrate how to use a function from a library in Python.

Answer:

import random

print([Link](1, 10)) # Random integer between 1 and 10

101. What is the purpose of the math library in Python?

Answer:
The math library is used to perform advanced mathematical operations like trigonometry,
logarithms, and power calculations.
102. List five commonly used functions in the math library and their uses.

Answer:

● sqrt(): Square root.


● pow(): Exponentiation.
● log(): Logarithm.
● sin(): Sine of an angle.
● pi: Mathematical constant.

103. How can you calculate the square root of a number using the math module?

Answer:

import math

print([Link](16)) # Output: 4.0

104. What is the difference between [Link]() and the ** operator in Python?

Answer:

● [Link](): Returns a float.


● **: Supports both integers and floats.

105. How can you compute the logarithm of a number to a specific base using the
math module?

Answer:

import math

print([Link](100, 10)) # Output: 2.0

106. Write a Python program to calculate the area of a circle using the [Link]
constant.

Answer:

import math

radius = 5

area = [Link] * radius ** 2

print(area)

107. What function would you use to round a number down to the nearest integer?
Answer:
[Link]().

108. How is math.e used in exponential calculations?

Answer:
math.e is used as the base for natural logarithms.

Example:

import math

print([Link](1)) # Output: 2.718281828459045 (e)

109. Explain the difference between [Link]() and [Link]().

Answer:

● ceil(): Rounds up to the nearest integer.


● floor(): Rounds down to the nearest integer.

110. Demonstrate the use of trigonometric functions like [Link]() and


[Link]().

Answer:

import math

print([Link]([Link] / 2)) # Output: 1.0

print([Link](0)) # Output: 1.0

111. What is the purpose of the random library in Python?

Answer:
To generate random numbers and perform random operations.

112. How can you generate a random float between 0.0 and 1.0?

Answer:

import random

print([Link]())

113. Which function would you use to generate a random integer within a range?
Answer:
[Link](a, b).

114. Explain the difference between [Link]() and [Link](a, b).

Answer:

● [Link](): Generates a random float between 0.0 (inclusive) and 1.0


(exclusive).
● [Link](a, b): Generates a random float between a (inclusive) and b
(exclusive).

115. How can you select a random element from a list using the random library?

Answer:

import random

print([Link]([1, 2, 3, 4]))

116. Write a Python program to simulate rolling a six-sided die.

Answer:

import random

print([Link](1, 6))

117. What is the purpose of the [Link]() function?

Answer:
It shuffles a list in place.
Example:

import random

lst = [1, 2, 3, 4]

[Link](lst)

print(lst)

118. How would you create a random password generator using the random library?

Answer:
Use [Link]() on a combination of letters, digits, and special characters.
Example:
import random

import string

def generate_password(length):

characters = string.ascii_letters + [Link] + [Link]

password = ''.join([Link](characters) for _ in range(length))

return password

print(generate_password(12))

119. What is the output of [Link]()? Why is it used?

Answer:
[Link]() initializes the random number generator, ensuring reproducibility of the
sequence of random numbers.

120. Write a Python program to shuffle a deck of cards using the random library.

Answer:

import random

deck = list(range(1, 53)) # Simulates a deck with cards numbered 1 to 52

[Link](deck)

print(deck)

121. What are [Link], [Link], and [Link]?

Answer:

● [Link]: Represents a date.


● [Link]: Represents a time.
● [Link]: Combines date and time.

122. Write a Python program to create and display a specific date.

Answer:

from datetime import date

d = date(2024, 1, 1)

print(d) # Output: 2024-01-01


123. How can you extract the year, month, and day from a datetime object?

Answer:

from datetime import datetime

now = [Link]()

print([Link], [Link], [Link])

124. What is the purpose of the strftime() method in the datetime library?

Answer:

The strftime() method formats a datetime object into a string based on a specified
format.

125. Explain the difference between strftime() and strptime().

Answer:

● strftime(): Converts a datetime object to a formatted string.


● strptime(): Parses a string into a datetime object based on a specified format.

126. Write a Python program to convert a string into a datetime object.

Answer:

from datetime import datetime

date_str = "2024-11-27"

d = [Link](date_str, "%Y-%m-%d")

print(d) # Output: 2024-11-27 00:00:00

127. How can you calculate the difference between two dates using the datetime
library?

Answer:

from datetime import date

d1 = date(2024, 1, 1)

d2 = date(2023, 12, 25)

print(d1 - d2) # Output: 7 days

128. Write a Python program to calculate the number of days until New Year’s Day.
Answer:

from datetime import date

today = [Link]()

new_year = date([Link] + 1, 1, 1)

print((new_year - today).days)

129. What is the difference between positional and keyword arguments in Python
functions?

Answer:

● Positional arguments: Matched based on their position in the function call.


● Keyword arguments: Explicitly specify parameter names, allowing flexibility in order.

130. Explain dictionary comprehensions and provide an example.

Answer:
Dictionary comprehensions provide a concise way to create dictionaries.
Example:

squares = {x: x**2 for x in range(5)}

print(squares) # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

131. What is the difference between read(), readline(), and readlines() in file
handling?

Answer:

● read(): Reads the entire file content as a string.


● readline(): Reads one line at a time.
● readlines(): Reads all lines into a list of strings.

132. What is the difference between a syntax error and an exception?

Answer:

● Syntax Error: Occurs when code violates Python’s syntax rules and prevents the
code from running.
● Exception: Occurs during execution when valid code produces an error (e.g.,
dividing by zero).

133. What is the purpose of the self keyword in Python classes?


Answer:
The self keyword refers to the instance of the class and is used to access instance
variables and methods.

134. What is method overriding in Python, and how is it achieved?

Answer:

Method overriding occurs when a child class provides its own implementation of a method
defined in the parent class, using the same method name.
Example:

class Parent:

def greet(self):

print("Hello from Parent")

class Child(Parent):

def greet(self):

print("Hello from Child")

obj = Child()

[Link]() # Output: Hello from Child

135. Why is testing and debugging important in project development?

Answer:

● Testing: Ensures the program works as intended.


● Debugging: Helps identify and fix errors, improving program reliability.

136. What is the difference between a Python list and a NumPy array?

Answer:

● Python List: Can store elements of different data types and is slower for numerical
operations.
● NumPy Array: Stores elements of the same type, supports vectorized operations,
and is more efficient for numerical computations.

137. What is Pandas, and why is it used?

Answer:
Pandas is a Python library used for data manipulation and analysis. It provides two primary
data structures:

● DataFrame: 2D tabular data.


● Series: 1D array-like data.

It is widely used for cleaning, transforming, and analyzing structured data.

138. How do you select a specific column from a DataFrame?

Answer:
You can select a column using:

df['column_name']

139. How do you rename columns in a Pandas DataFrame?

Answer:
Use:

[Link](columns={'old_name': 'new_name'}, inplace=True)

140. How do you group data by a specific column and calculate summary statistics?

Answer:
Use:

[Link]('column_name').agg({'another_column': 'mean'})

141. How do you calculate the correlation between columns?

Answer:
Use:

correlation = [Link]()

print(correlation)

142. What is Matplotlib, and why is it used in Python?

Answer:

Matplotlib is a popular Python library used for creating static, animated, and interactive
visualizations such as graphs, bar charts, pie charts, and histograms.

143. How do you create a simple line plot using Matplotlib?

Answer:

import [Link] as plt

x = [1, 2, 3]

y = [2, 4, 6]
[Link](x, y)

[Link]()

144. How do you set the title, labels for the axes, and grid for a plot?

Answer:
Use the following:

[Link]("Title")

[Link]("X-axis")

[Link]("Y-axis")

[Link](True)

145. How do you plot multiple lines on the same graph?

Answer:

[Link](x1, y1, label="Line 1")

[Link](x2, y2, label="Line 2")

[Link]()

[Link]()

146. How do you create a scatter plot using Matplotlib?

Answer:

[Link](x, y)

[Link]()

147. How do you plot multiple subplots with different sizes?

Answer:

fig, axs = [Link](2, 2, figsize=(10, 8))

axs[0, 0].plot(x, y)

axs[0, 1].bar(categories, values)

axs[1, 0].scatter(x, y)

axs[1, 1].pie(sizes, labels=labels)

[Link]()
148. How do you create a stacked bar chart in Matplotlib?

Answer:

data1 = [3, 5, 7]

data2 = [1, 3, 5]

labels = ['A', 'B', 'C']

[Link](labels, data1, label='Data 1')

[Link](labels, data2, bottom=data1, label='Data 2')

[Link]()

[Link]()

149. How do you customize the appearance of a Matplotlib plot (e.g., changing line
width, markers, etc.)?

Answer:

[Link](x, y, linewidth=2, marker='o', color='b')

[Link]()

150. What is BeautifulSoup, and what is it used for in Python?

Answer:
BeautifulSoup is a Python library used for parsing HTML and XML documents. It is mainly
used for web scraping, allowing developers to navigate and search the HTML tree structure
to extract specific elements.

151. How do you import BeautifulSoup and requests in Python?


Answer:

from bs4 import BeautifulSoup

import requests

You import BeautifulSoup from the bs4 module and send HTTP requests and fetch web
content.

152. How do you fetch the HTML content of a webpage using requests and parse it
with BeautifulSoup?
Answer:

response = [Link]("[Link]

soup = BeautifulSoup([Link], "[Link]")


print([Link]())

153. How do you extract the text content from a tag?


Answer:
You can use the .get_text() method to extract the text inside an HTML tag.

text = tag.get_text()

print(text)

154. How do you scrape data from a website while respecting the [Link] file?
Answer:
Before scraping, always check a website's [Link] file to ensure you're allowed to
scrape it. Tools like [Link] can be used to handle this programmatically,
ensuring ethical scraping practices.

155. What is a higher-order function in Python?


Answer:
A higher-order function is a function that either takes one or more functions as arguments or
returns a function as a result.
Example:

def add(x):

return lambda y: x + y

add_five = add(5)

print(add_five(3)) # Output: 8

156. What is the difference between @staticmethod and @classmethod in Python?


Answer:

● @staticmethod: Defines a method that does not operate on an instance or class


but belongs to the class itself. It cannot access instance or class variables.
● @classmethod: Defines a method that operates on the class and takes the class as
its first argument, usually named cls.

157. How does Python handle default argument values in functions?


Answer:
Python allows you to define default values for function parameters, which are used when no
argument is provided for that parameter.
Example:

def greet(name="Guest"):

print(f"Hello, {name}!")

greet() # Output: Hello, Guest!


greet("Alice") # Output: Hello, Alice!

158. What is *args and **kwargs in Python functions?


Answer:

● *args: Used to pass a variable number of non-keyword arguments to a function.


● **kwargs: Used to pass a variable number of keyword arguments to a function.
Example:

def example_function(*args, **kwargs):

print(args)

print(kwargs)

example_function(1, 2, 3, a=4, b=5)

# Output: (1, 2, 3)

# Output: {'a': 4, 'b': 5}

159. What is the purpose of the yield keyword in Python?


Answer:
The yield keyword is used in a function to create a generator. It allows the function to
return an iterator that produces a series of values lazily, one at a time.
Example:

def generate_numbers():

for i in range(3):

yield i

for num in generate_numbers():

print(num)

160. What is the difference between del and pop() in Python?


Answer:

● del: Deletes an item from a list by its index or deletes the entire list or object.
● pop(): Removes and returns an item from a list by index (default is the last item).
Example:

lst = [1, 2, 3]

del lst[1] # Removes element at index 1

[Link]() # Removes and returns the last element


161. What is the functools module used for in Python?
Answer:
The functools module contains higher-order functions that work on other functions to
enhance their behavior or simplify code. Examples include partial, reduce, and wraps.

162. What are the different modes for opening a file in Python? Explain their use
cases.
Answer:

● 'r': Read mode (default).


● 'w': Write mode (overwrites an existing file or creates a new one).
● 'a': Append mode (adds data to the end of a file or creates a new one).
● 'x': Exclusive creation mode (raises an error if the file exists).
● 'r+': Read and write mode.
● 'w+': Write and read mode (overwrites an existing file).
● 'a+': Append and read mode.

163. Explain the concept of buffering in file I/O. How does it affect performance?
Answer:
Buffering involves reading or writing data in chunks instead of one byte at a time. This
improves performance by reducing the number of system calls and disk access operations.
You can control buffering using the buffering argument in the open() function.

164. Explain the role of the csv module in Python. What are its primary functions?
Answer:
The csv module provides tools for reading and writing CSV files.

● reader: Reads rows from a CSV file.


● writer: Writes rows to a CSV file.
● DictReader: Reads rows as dictionaries.
● DictWriter: Writes rows as dictionaries.

165. What are some common challenges and best practices when working with CSV
files?
Answer:

● Data Cleaning: Handle missing values, inconsistent formatting, and encoding issues.
● Error Handling: Handle errors like file not found or invalid format.
● Performance Optimization: Use efficient reading/writing techniques for large files.
● Security: Be cautious of CSV files from untrusted sources to avoid injection attacks.

166. What is the difference between [Link]() and [Link]()?


Answer:

● [Link](): Rounds a number down to the nearest integer.


● [Link](): Truncates a number, removing the decimal part without rounding.
Example:

import math

print([Link](-2.7)) # Output: -3

print([Link](-2.7)) # Output: -2

167. Explain the purpose of the [Link]() function.


Answer:
The [Link]() function calculates the factorial of a non-negative integer.
Example:

import math

print([Link](5)) # Output: 120

168. What is the difference between [Link]() and [Link](a,


b)?
Answer:

● [Link](): Generates a random float between 0.0 (inclusive) and 1.0


(exclusive).
● [Link](a, b): Generates a random float between a (inclusive) and b
(inclusive).

Example:

import random

print([Link]()) # Output: 0.534... (random float between 0.0 and 1.0)

print([Link](5, 10)) # Output: 7.234... (random float between 5 and 10)

169. How can you shuffle a list of elements randomly?


Answer:
Use [Link]().
Example:

import random

lst = [1, 2, 3, 4, 5]

[Link](lst)

print(lst) # Output: [3, 5, 1, 4, 2] (order may vary)

170. What is the difference between math.e and [Link]?


Answer:
● math.e: Represents Euler's number, approximately 2.71828.
● [Link]: Represents the ratio of a circle's circumference to its diameter,
approximately 3.14159.

171. How can you calculate the hypotenuse of a right-angled triangle using the math
module?
Answer:
Use [Link](x, y), where x and y are the lengths of the two shorter sides.
Example:

import math

print([Link](3, 4)) # Output: 5.0

172. What is the difference between [Link]() and [Link]()?


Answer:

● [Link](): Initializes the pseudorandom number generator, ensuring


reproducibility of the sequence.
● [Link](): Generates a random float between 0.0 and 1.0.

Example:

import random

[Link](42)

print([Link]()) # Output: 0.639...

[Link](42)

print([Link]()) # Output: 0.639... (same result)

173. What is the purpose of the [Link]() function?


Answer:
The [Link]() function selects elements from a sequence with replacement,
allowing for weighted probabilities.
Example:

import random

choices = [Link](['a', 'b', 'c'], weights=[2, 1, 1], k=5)

print(choices) # Output: ['a', 'a', 'c', 'b', 'a'] (order may vary)

174. How does polymorphism work in Python?


Answer:
Polymorphism in Python allows objects of different classes to be treated as instances of the
same class through:
● Method Overriding: Subclasses provide specific implementations for methods in the
parent class.
● Duck Typing: Behavior is determined by the methods and attributes an object has,
not by its explicit type.

Example:

class Bird:

def speak(self):

print("Chirp")

class Dog:

def speak(self):

print("Bark")

animals = [Bird(), Dog()]

for animal in animals:

[Link]()

175. Explain the concept of duck typing in Python.


Answer:
Duck typing is a programming style where the type of an object is determined by its
behavior rather than its explicit class. If an object has the necessary methods or attributes, it
is treated as the required type.
Example:

def quack(duck):

[Link]()

class Duck:

def quack(self):

print("Quack!")

class Human:

def quack(self):

print("I'm quacking like a duck!")

quack(Duck()) # Output: Quack!

quack(Human()) # Output: I'm quacking like a duck!


176. How can you achieve operator overloading in Python?
Answer:
Operator overloading is achieved by defining special methods in a class. For example, to
overload the + operator:

class MyClass:

def __init__(self, value):

[Link] = value

def __add__(self, other):

return MyClass([Link] + [Link])

obj1 = MyClass(10)

obj2 = MyClass(20)

result = obj1 + obj2

print([Link]) # Output: 30
Practical based Question and Answer
1. How do you convert a string of integers into decimals in Python?
Answer:
You can use the [Link] class from the decimal module to convert a string of
integers into a decimal.
Example:

import decimal

string = "12345"

print([Link](string)) # Output: 12345

print(type([Link](string))) # Output: <class '[Link]'>

2. How do you reverse a string using an extended slicing technique?


Answer:
You can reverse a string using the slicing syntax [::-1].
Example:

string = "Python Programming"

print(string[::-1]) # Output: gnimmargorP nohtyP

3. How do you count vowels in a given word?


Answer:
You can use a loop to iterate through the word and count the vowels.
Example:

vowels = ['a', 'e', 'i', 'o', 'u']

word = "programming"

count = 0

for char in word:

if char in vowels:

count += 1

print(count) # Output: 3

4. How do you count consonants in a given word?


Answer:
You can count consonants by excluding vowels.
Example:

vowels = ['a', 'e', 'i', 'o', 'u']


word = "programming"

count = 0

for char in word:

if char not in vowels:

count += 1

print(count) # Output: 8

5. How do you count the number of occurrences of a character in a string?


Answer:
You can use a loop to count occurrences of a specific character.
Example:

word = "python"

character = "p"

count = 0

for char in word:

if char == character:

count += 1

print(count) # Output: 1

6. How do you write a Fibonacci series in Python?


Answer:
You can use a loop to generate the Fibonacci series.
Example:

fib = [0, 1]

for i in range(5): # Adjust range for more terms

[Link](fib[-1] + fib[-2])

print(', '.join(str(num) for num in fib)) # Output: 0, 1, 1, 2, 3, 5, 8

7. How do you find the maximum number in a list?


Answer:
You can use a loop to find the maximum number or use the max() function.
Example:

number_list = [15, 85, 35, 89, 125]


max_num = max(number_list)

print(max_num) # Output: 125

8. How do you find the minimum number in a list?


Answer:
You can use a loop to find the minimum number or use the min() function.
Example:

number_list = [15, 85, 35, 89, 125, 2]

min_num = min(number_list)

print(min_num) # Output: 2

9. How do you find the middle element in a list?


Answer:
You can calculate the index of the middle element and access it.
Example:

num_list = [1, 2, 3, 4, 5]

mid_index = len(num_list) // 2

print(num_list[mid_index]) # Output: 3

10. How do you convert a list into a string?


Answer:
You can use the join() method to convert a list into a string.
Example:

lst = ["P", "Y", "T", "H", "O", "N"]

string = ''.join(lst)

print(string) # Output: PYTHON

print(type(string)) # Output: <class 'str'>

11. How do you add two list elements together?


Answer:
You can use a loop to add corresponding elements from two lists.
Example:

lst1 = [1, 2, 3]

lst2 = [4, 5, 6]

result_list = [lst1[i] + lst2[i] for i in range(len(lst1))]

print(result_list) # Output: [5, 7, 9]


12. How do you compare two strings for anagrams?
Answer:
You can compare sorted versions of the strings.
Example:

str1 = "Listen"

str2 = "Silent"

if sorted([Link]()) == sorted([Link]()):

print("True") # Output: True

else:

print("False")

13. How do you find the factorial of a number using recursion?


Answer:
You can use a recursive function to calculate the factorial of a number.
Example:

def factorial(n):

if n == 0:

return 1

else:

return n * factorial(n - 1)

print(factorial(5)) # Output: 120

14. How do you check if a string is a palindrome?


Answer:
You can compare the string with its reverse.
Example:

string = "madam"

if string == string[::-1]:

print("Palindrome") # Output: Palindrome

else:

print("Not a Palindrome")

15. Counting the White Spaces in a String


Answer:

string = "P r ogramm in g "

print([Link](' ')) # Output: 120

16. Counting Digits, Letters, and Spaces in a String

Answer:

import re

name = 'Python is 1'

digitCount = [Link]("[^0-9]", "", name)

letterCount = [Link]("[^a-zA-Z]", "", name)

spaceCount = [Link]("[ \n]", name)

print(len(digitCount))

print(len(letterCount))

print(len(spaceCount))

1
8
2
17. Counting Special Characters in a String

Answer:

import re

spChar = "!@#$%^&*()"

count = [Link]('[\w]+', '', spChar)

print(len(count))

10

18. Removing All Whitespace in a String

Answer:

import re

string = "C O D E"

spaces = [Link](r'\s+')
result = [Link](spaces, '', string)

print(result)

CODE
19. Building a Pyramid in Python

Answer:

floors = 3

h = 2*floors-1

for i in range(1, 2*floors, 2):

print('{:^{}}'.format('*'*i, h))

>*

***

*****

20. Randomizing the Items of a List in Python

Answer:

from random import shuffle

lst = ['Python', 'is', 'Easy']

shuffle(lst)

print(lst)

['Easy', 'is', 'Python']


21. Python program to remove character from string

Answer:

str = "Python"

ch = "o"

print([Link](ch," "))

Pyth n
22. Python Program to count occurrence of characters in string

Answer:

string = "Python"
char = "y"

count = 0

for i in range(len(string)):

if(string[i] == char):

count = count + 1

print(count)

1
23. Python program to check if strings are anagrams or not

Answer:

str1 = "python"

str2 = "yonthp"

if (sorted(str1) == sorted(str2)):

print("Anagram")

else:

print("Not an anagram")

Anagram
24. Python program to check if a string is palindrome or not

Answer:

string = "madam"

if(string == string[::-1]):

print("Palindrome")

else:

print("Not a Palindrome")

Palindrome
25. Python code to check if given character is digit or not

Answer:

ch = 'a'

if ch >= '0' and ch <= '9':


print("Digit")

else:

print("Not a Digit")

Not a Digit
26. Program to replace the string space with any given character

Answer:

string = "m d m"

result = ''

ch = "a"

for i in string:

if i == ' ':

i = ch

result += i

print(result)

madam
27. What is monkey patching in Python?

Answer:

In Python, the term monkey patch refers to dynamic modifications of a class or module at
run-time.

class pythonClass:

def function(self):

print "function()"

import m

def monkey_function(self):

print "monkey_function()"

[Link] = monkey_function

obj = [Link]()

[Link]()
28. Function to Read a File

Answer:

def read_file(file_path):

try:

with open(file_path, "r") as file:

return [[Link]() for line in file]

except FileNotFoundError:

return f"Error: The file '{file_path}' does not exist."

file_content = read_file("[Link]")

print(file_content)

29. Function to Write to a File

Answer:

def write_file(file_path, data):

try:

with open(file_path, "w") as file:

[Link](f"{line}\n" for line in data)

print(f"Data successfully written to {file_path}")

except Exception as e:

print(f"Error: {e}")

data = ["First line", "Second line", "Third line"]

write_file("[Link]", data)

30. Function to Read a CSV File

Answer:

import csv

def read_csv(file_path):

try:
with open(file_path, "r") as csv_file:

reader = [Link](csv_file)

return [row for row in reader]

except FileNotFoundError:

return f"Error: The file '{file_path}' does not exist."

csv_data = read_csv("[Link]")

print(csv_data)

31. Function to Write to a CSV File

Answer:

import csv

def write_csv(file_path, data):

try:

with open(file_path, "w", newline="") as csv_file:

writer = [Link](csv_file)

[Link](data)

print(f"CSV data written to {file_path}")

except Exception as e:

print(f"Error: {e}")

data = [["Name", "Age", "City"], ["Alice", 30, "New York"], ["Bob", 25, "Los Angeles"]]

write_csv("[Link]", data)

32. Function to Modify a CSV File

Answer:

import csv

def modify_csv(input_file, output_file, operation):

try:

with open(input_file, "r") as csv_file:


reader = [Link](csv_file)

data = [operation(row) for row in reader]

with open(output_file, "w", newline="") as csv_file:

writer = [Link](csv_file, fieldnames=data[0].keys())

[Link]()

[Link](data)

except Exception as e:

print(f"Error: {e}")

33. Retrieve the Value of a Key from a Dictionary

Answer:

person = {"name": "Alice", "age": 30}

print(person["age"])

30

34. Lambda Function to Calculate the Square of a Number

Answer:

square = lambda x: x ** 2

print(square(4))

16

35. Check the Data Type of a Variable

Answer:

x = 42

print(type(x))

<class 'int'>

36. Create a 2D NumPy Array

Answer:

import numpy as np
arr_2d = [Link]([[1, 2], [3, 4], [5, 6]])

print(arr_2d)

37. Shape of a NumPy Array

Answer:

arr = [Link]([1, 2, 3, 4])

print([Link])

38. Create a NumPy Array of Zeros

Answer:

arr_zeros = [Link]((3, 3))

print(arr_zeros)

39. Use of [Link]() in NumPy

Answer:

arr = [Link](0, 10, 2)

print(arr)

40. Difference Between [Link]() and [Link]()

Answer:

# [Link]() for dot product, [Link]() for matrix multiplication

41. Transpose of a NumPy Array

Answer:

arr = [Link]([[1, 2], [3, 4], [5, 6]])

transpose = arr.T

print(transpose)

42. Check for Missing Data in Pandas

Answer:

print([Link]())

print([Link]().sum())
43. Handle Missing Data in Pandas

Answer:

[Link](0, inplace=True)

[Link](inplace=True)

44. Group Data by Column and Calculate Statistics

Answer:

grouped = [Link]('Age').mean()

print(grouped)

45. Create a Bar Chart in Matplotlib

Answer:

import [Link] as plt

categories = ['A', 'B', 'C']

values = [10, 20, 15]

[Link](categories, values)

[Link]()

46. Create a Horizontal Bar Chart in Matplotlib

Answer:

[Link](categories, values)

[Link]()

47. Plot a Pie Chart in Matplotlib

Answer:

sizes = [10, 20, 30, 40]

labels = ['A', 'B', 'C', 'D']

[Link](sizes, labels=labels, autopct='%1.1f%%')

[Link]()
48. Create a Histogram in Matplotlib

Answer:

data = [1, 2, 2, 3, 3, 3, 4, 5, 5, 5, 5, 6]

[Link](data, bins=6, edgecolor='black')

[Link]()

49. How do you navigate the parse tree, for example, moving to a parent or sibling
element?
Answer: You can use .parent to navigate to a parent tag, and .find_next_sibling()
to find the next sibling element.

50. How do you handle exceptions or errors when using BeautifulSoup to parse an
invalid HTML document?
Answer: You can use a try-except block to catch errors if the HTML is invalid or not
parseable:

try:

soup = BeautifulSoup(invalid_html, '[Link]')

except Exception as e:

print(f"Error occurred: {e}")

51. How do you parse an XML document using BeautifulSoup?


Answer: You can parse XML documents similarly to HTML by using 'xml' as the parser
argument when initializing BeautifulSoup:

xml_data = '''<note><to>Tove</to><from>Jani</from><message>Remember
me!</message></note>'''

soup = BeautifulSoup(xml_data, 'xml')

52. How do you parse a large HTML document efficiently?


Answer: For large documents, it's better to parse directly from a file or stream the content
using file handlers to reduce memory usage:

with open('large_file.html') as file:

soup = BeautifulSoup(file, '[Link]')

53. How do you handle pagination when scraping multiple pages of a website?
Answer: You can handle pagination by looking for the next page link (e.g., a next button or
link), extracting its URL, and sending a new request to scrape the subsequent page:
next_page = [Link]('a', {'class': 'next'})

if next_page:

next_url = next_page.get('href')

response = [Link](next_url)

soup = BeautifulSoup([Link], '[Link]')

54. Create a to-do list.


Answer: Here's a simple to-do list with functions to add, remove, and mark tasks as
completed:

todo_list = []

def add_task(task):

todo_list.append(task)

def remove_task(task):

todo_list.remove(task)

def mark_as_completed(task):

todo_list.remove(task

# Example usage:

add_task("Buy groceries")

add_task("Finish report")

print(todo_list)

55. Number Guessing Game:


Answer: This is a simple number guessing game:

import random

secret_number = [Link](1, 100)

guess = 0

while guess != secret_number:

guess = int(input("Guess a number between 1 and 100: "))

if guess < secret_number:


print("Too low!")

elif guess > secret_number:

print("Too high!")

else:

print("You guessed it!")

56. Word Frequency Counter:


Answer: This program counts the frequency of each word in a given text:

text = "This is a sample text. This text contains some repeated words."

word_count = {}

for word in [Link]():

word_count[word] = word_count.get(word, 0) + 1

print(word_count)

57. Given a list of numbers, write a Python program to reverse the order of elements
in the list without using the reverse() method.
Answer: Here's how you can reverse a list without using the reverse() method:

def reverse_list(lst):

"""Reverses the order of elements in a list.

Args:

lst: The input list.

Returns:

The reversed list.

"""

start = 0

end = len(lst) - 1

while start < end:

lst[start], lst[end] = lst[end], lst[start]

start += 1

end -= 1
return ls

# Example usage:

my_list = [1, 2, 3, 4, 5]

reversed_list = reverse_list(my_list)

print(reversed_list) # Output: [5, 4, 3, 2, 1]

58. Given two sets, A and B, write Python code to perform the following set
operations: Union, Intersection, Difference, Symmetric difference.
Answer: Here are the set operations:

A = {1, 2, 3, 4, 5}

B = {3, 4, 5, 6, 7}

# Union

union_set = A | B

print("Union:", union_set)

# Intersection

intersection_set = A & B

print("Intersection:", intersection_set)

# Difference (A - B)

difference_set1 = A - B

print("Difference (A - B):", difference_set1)

# Difference (B - A)

difference_set2 = B - A

print("Difference (B - A):", difference_set2)

# Symmetric difference

symmetric_difference_set = A ^ B

print("Symmetric Difference:", symmetric_difference_set)

59. Write a Python program to iterate over a dictionary and print each key-value pair in
a formatted way.
Answer: Here’s how you can iterate over a dictionary and print the key-value pairs:
my_dict = {'apple': 3, 'banana': 5, 'orange': 2}

for key, value in my_dict.items():

print(f"Key: {key}, Value: {value}")

60. Pythagorean Theorem:


Answer: This program calculates the hypotenuse of a right triangle using the Pythagorean
theorem:

import math

def pythagorean_theorem():

a = float(input("Enter the length of side a: "))

b = float(input("Enter the length of side b: "))

c = [Link](a**2 + b**2)

print("The length of the hypotenuse is:", c)

pythagorean_theorem()

61. Dice Roll Simulator:


Answer: Here’s a simple dice roll simulator:

import random

def roll_dice():

dice_roll = [Link](1, 6)

print("You rolled a:", dice_roll)

roll_dice()

62. Random Password Generator:


Answer: This program generates a random password of a given length:

import random

import string

def generate_password(length):

letters = string.ascii_letters

digits = [Link]

symbols = [Link]
characters = letters + digits + symbols

password = ''.join([Link](characters) for _ in range(length))

print("Generated password:", password)

generate_password(12)

63. Monte Carlo Simulation for Pi:


Answer: This Monte Carlo simulation estimates the value of pi:

import math

import random

def monte_carlo_pi(num_darts):

num_darts_in_circle = 0

for _ in range(num_darts):

x = [Link](-1, 1)

y = [Link](-1, 1)

if x**2 + y**2 <= 1:

num_darts_in_circle += 1

pi_estimate = 4 * num_darts_in_circle / num_darts

print("Estimated value of pi:", pi_estimate)

monte_carlo_pi(1000000)

64. Random Walk Simulation:


Answer: Here’s how to simulate a random walk:

import random

def random_walk(steps):

x, y = 0, 0

for _ in range(steps):

direction = [Link](['N', 'S', 'E', 'W'])

if direction == 'N':

y += 1
elif direction == 'S':

y -= 1

elif direction == 'E':

x += 1

elif direction == 'W':

x -= 1

print("Final position:", (x, y))

random_walk(100)

65. Generating Random Data for Testing:


Answer: This program generates random data for testing:

import random

def generate_random_data(num_samples, min_value, max_value):

data = [[Link](min_value, max_value) for _ in range(num_samples)]

return data

data = generate_random_data(100, 0, 10)

print(data)

66. Simulating Exponential Decay:


Answer: Here’s a program to simulate exponential decay:

import math

import random

def exponential_decay(initial_value, decay_rate, time_steps):

values = []

for t in range(time_steps):

value = initial_value * [Link](-decay_rate * t)

[Link](value)

return values

values = exponential_decay(100, 0.1, 10)


print(values)

Python interview questions and solutions that are


commonly asked in interviews for IT companies.
1. Reverse a String
Question: Write a Python function to reverse a string.
Answer:

def reverse_string(s):

return s[::-1]

Test:

print(reverse_string("hello")) # Output: "olleh"

2. Check for Palindrome


Question: Write a function to check if a given string is a palindrome.
Answer:

def is_palindrome(s):

s = [Link]()

return s == s[::-1]
Test:

print(is_palindrome("madam")) # Output: True

print(is_palindrome("hello")) # Output: False

3. Find the Largest Element in a List


Question: Write a Python program to find the largest number in a list.
Answer:

def find_largest(nums):

return max(nums)

Test:

print(find_largest([1, 3, 7, 2, 5])) # Output: 7

4. Fibonacci Sequence
Question: Write a Python function to generate the first n Fibonacci numbers.
Answer:

def fibonacci(n):

fib = [0, 1]

for i in range(2, n):

[Link](fib[i-1] + fib[i-2])

return fib[:n]

Test:

print(fibonacci(10)) # Output: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

5. Two Sum Problem


Question: Given an array of integers, return indices of the two numbers such that they add
up to a specific target.
Answer:

def two_sum(nums, target):

seen = {}

for i, num in enumerate(nums):

diff = target - num

if diff in seen:

return [seen[diff], i]

seen[num] = i

Test:

print(two_sum([2, 7, 11, 15], 9)) # Output: [0, 1]

6. Count Occurrences of Each Character


Question: Write a Python program to count the occurrences of each character in a string.
Answer:

from collections import Counter

def count_characters(s):

return Counter(s)

Test:

print(count_characters("hello")) # Output: Counter({'l': 2, 'h': 1, 'e': 1, 'o': 1})

7. Find the Missing Number


Question: Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the
missing number.
Answer:

def find_missing(nums):

n = len(nums)
total = n * (n + 1) // 2

return total - sum(nums)

Test:

print(find_missing([3, 0, 1])) # Output: 2

8. Validate Parentheses
Question: Write a Python program to validate a string containing parentheses.
Answer:

def is_valid_parentheses(s):

stack = []

mapping = {')': '(', '}': '{', ']': '['}

for char in s:

if char in mapping:

top_element = [Link]() if stack else '#'

if mapping[char] != top_element:

return False

else:

[Link](char)

return not stack

Test:

print(is_valid_parentheses("()[]{}")) # Output: True

print(is_valid_parentheses("(]")) # Output: False

9. Merge Two Sorted Lists


Question: Merge two sorted lists into one sorted list.
Answer:
def merge_sorted_lists(list1, list2):

return sorted(list1 + list2)

Test:

print(merge_sorted_lists([1, 3, 5], [2, 4, 6])) # Output: [1, 2, 3, 4, 5, 6]

10. Find the First Non-Repeating Character


Question: Write a function to find the first non-repeating character in a string.
Answer:

def first_non_repeating_char(s):

count = Counter(s)

for char in s:

if count[char] == 1:

return char

return None

Test:

print(first_non_repeating_char("swiss")) # Output: "w"

Here’s the same set of questions and answers formatted without lines between the question-
answer sets:

11. Remove Duplicates from a List


Question: Write a function to remove duplicates from a list.
Answer:

def remove_duplicates(nums):

return list(set(nums))

Test:

print(remove_duplicates([1, 2, 2, 3, 4, 4, 5])) # Output: [1, 2, 3, 4, 5]


12. Check If a Number Is Prime
Question: Write a function to check if a number is prime.
Answer:

def is_prime(n):

if n <= 1:

return False

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

if n % i == 0:

return False

return True

Test:

print(is_prime(7)) # Output: True

print(is_prime(4)) # Output: False

13. Anagram Check


Question: Write a function to check if two strings are anagrams.
Answer:

def are_anagrams(s1, s2):

return sorted(s1) == sorted(s2)

Test:

print(are_anagrams("listen", "silent")) # Output: True

print(are_anagrams("hello", "world")) # Output: False

14. Factorial of a Number


Question: Write a function to calculate the factorial of a number.
Answer:

def factorial(n):
if n == 0 or n == 1:

return 1

return n * factorial(n - 1)

Test:

print(factorial(5)) # Output: 120

15. Find Duplicates in a List


Question: Write a function to find all duplicates in a list.
Answer:

def find_duplicates(nums):

from collections import Counter

counts = Counter(nums)

return [num for num, count in [Link]() if count > 1]

Test:

print(find_duplicates([1, 2, 3, 2, 4, 5, 1])) # Output: [1, 2]

16. Flatten a Nested List


Question: Write a function to flatten a nested list.
Answer:

def flatten_list(nested_list):

flat_list = []

for item in nested_list:

if isinstance(item, list):

flat_list.extend(flatten_list(item))

else:

flat_list.append(item)
return flat_list

Test:

print(flatten_list([1, [2, [3, 4]], 5])) # Output: [1, 2, 3, 4, 5]

17. Generate All Subsets of a List


Question: Write a function to generate all subsets of a list.
Answer:

from itertools import chain, combinations

def all_subsets(nums):

return list(chain.from_iterable(combinations(nums, r) for r in range(len(nums) + 1)))

Test:

print(all_subsets([1, 2, 3])) # Output: [(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]

18. Find Intersection of Two Lists


Question: Write a function to find the intersection of two lists.
Answer:

def list_intersection(list1, list2):

return list(set(list1) & set(list2))

Test:

print(list_intersection([1, 2, 3], [2, 3, 4])) # Output: [2, 3]

19. Longest Common Prefix


Question: Write a function to find the longest common prefix among a list of strings.
Answer:

def longest_common_prefix(strs):

if not strs:
return ""

prefix = strs[0]

for string in strs[1:]:

while not [Link](prefix):

prefix = prefix[:-1]

if not prefix:

return ""

return prefix

Test:

print(longest_common_prefix(["flower", "flow", "flight"])) # Output: "fl"

20. Find K Largest Elements


Question: Find the k largest elements in a list.
Answer:

import heapq

def k_largest(nums, k):

return [Link](k, nums)

Test:

print(k_largest([3, 2, 1, 5, 6, 4], 2)) # Output: [6, 5]

Here’s the formatted set of questions and answers without lines between each question-
answer pair:

21. Check for Subarray with Zero Sum


Question: Check if a subarray with a sum of 0 exists.
Answer:

def has_zero_sum_subarray(nums):

seen = set()

current_sum = 0
for num in nums:

current_sum += num

if current_sum in seen or current_sum == 0:

return True

[Link](current_sum)

return False

Test:

print(has_zero_sum_subarray([3, 4, -7, 1, 2])) # Output: True

22. Matrix Transpose


Question: Write a function to transpose a matrix.
Answer:

def transpose_matrix(matrix):

return [list(row) for row in zip(*matrix)]

Test:

print(transpose_matrix([[1, 2], [3, 4]])) # Output: [[1, 3], [2, 4]]

23. Find GCD of Two Numbers


Question: Write a Python program to find the GCD of two numbers.
Answer:

from math import gcd

def find_gcd(a, b):

return gcd(a, b)

Test:

print(find_gcd(54, 24)) # Output: 6


24. Binary Search
Question: Implement a binary search algorithm.
Answer:

def binary_search(nums, target):

low, high = 0, len(nums) - 1

while low <= high:

mid = (low + high) // 2

if nums[mid] == target:

return mid

elif nums[mid] < target:

low = mid + 1

else:

high = mid - 1

return -1

Test:

print(binary_search([1, 2, 3, 4, 5], 4)) # Output: 3

25. Count Vowels in a String


Question: Write a function to count the vowels in a string.
Answer:

def count_vowels(s):

return sum(1 for char in [Link]() if char in "aeiou")

Test:

print(count_vowels("hello world")) # Output: 3


26. Find Power of a Number
Question: Write a function to calculate x^y.
Answer:

def power(x, y):

return x**y

Test:

print(power(2, 3)) # Output: 8

27. Merge Intervals


Question: Merge overlapping intervals.
Answer:

def merge_intervals(intervals):

[Link](key=lambda x: x[0])

merged = []

for interval in intervals:

if not merged or merged[-1][1] < interval[0]:

[Link](interval)

else:

merged[-1][1] = max(merged[-1][1], interval[1])

return merged

Test:

print(merge_intervals([[1, 3], [2, 6], [8, 10], [15, 18]])) # Output: [[1, 6], [8, 10], [15, 18]]

You might also like