Python Interview Questions
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.
Answer:
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.
Answer:
The supported standard data types in Python include the following:
● List
● Number
● String
● Dictionary
● Tuples
Answer:
Tuples is a sequence data type in Python. The number of values in tuples is separated by
commas.
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.
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.
Answer:
There are certain limitations of Python, which include:
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.
Answer:
The break statement helps control the Python loop by stopping the current loop's execution
and transferring control to the next block.
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.
Answer:
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.
Answer:
The purpose of relational operators in Python is to compare values.
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.
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.
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.
Answer:
The types of inheritance in Python are:
Answer:
Memory management in Python is handled by:
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.
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:
Answer:
Answer:
A lambda function is an anonymous, single-expression function.
Example:
square = lambda x: x ** 2
print(square(5)) # Output: 25
Answer:
Answer:
The // operator performs floor division, returning the integer part of a division.
Example:
print(10 // 3) # Output: 3
Answer:
Monkey patching refers to dynamically modifying or extending a class or module during
runtime.
Answer:
The split() function breaks a string into a list of substrings based on a specified
separator.
Example:
Answer:
The Dogpile effect occurs when the cache expires, and multiple requests hit the server
simultaneously. It can be mitigated using semaphore locks.
Answer:
The pass statement is a placeholder that does nothing. It is used in blocks where code is
syntactically required but not yet implemented.
Answer:
Slicing allows extracting a subset of elements from sequences like lists, tuples, or strings
using [start:stop:step].
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"
Answer:
Iterators are objects that implement the __iter__() and __next__() methods, allowing
traversal of elements in a container like a list or tuple.
Answer:
Comments in Python start with a # for single-line comments. Multi-line comments are
written using triple quotes (""" or ''').
Answer:
You can use the capitalize() method to capitalize the first letter of a string.
Example:
text = "python"
Answer:
Answer:
Files are deleted using the os module.
Example:
import os
[Link]("[Link]")
Answer:
Yes, Python supports multiple inheritance, allowing a class to inherit from more than one
parent class.
Answer:
The object() method returns a featureless object that serves as the base for all classes.
Answer:
PEP 8 is the Python Enhancement Proposal that provides guidelines and best practices for
writing clean, readable, and consistent Python code.
Answer:
A namespace is a system that ensures unique names for variables and objects to prevent
naming conflicts.
Answer:
Yes, indentation is mandatory in Python. It defines the block structure of the code and
ensures proper execution.
Answer:
Answer:
Some core default modules include:
Answer:
Popular Python frameworks include:
Answer:
Memory in Python is managed using private heap space, the memory manager, and
garbage collection.
Answer:
Inheritance allows a child class to acquire properties and methods from a parent class.
Example:
class Parent:
def greet(self):
class Child(Parent):
pass
obj = Child()
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.
Answer:
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:
Answer:
The swapcase() function changes the case of all letters in a string: uppercase becomes
lowercase and vice versa.
Example:
text = "Python"
Answer:
Exception handling in Python uses try, except, and finally blocks:
try:
x=1/0
except ZeroDivisionError:
finally:
print("Execution complete.")
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.
Answer:
Decorators modify or enhance the behavior of a function or method without permanently
modifying it.
Example:
def decorator(func):
def wrapper():
func()
return wrapper
@decorator
def say_hello():
print("Hello!")
say_hello()
Answer:
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.
Answer:
Data abstraction in Python is achieved by using abstract classes and interfaces, hiding
implementation details while exposing only the necessary functionalities.
Answer:
import os
[Link]("[Link]")
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.
Answer:
A namespace is a naming system used to make sure that names are unique to avoid
naming conflicts.
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.
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.
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.
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.
try:
TypeError('Example TypeError'),
ValueError('Example ValueError'),
KeyError('Example KeyError'),
AttributeError('Example AttributeError')
))
except* TypeError:
pass
except* ValueError as e:
pass
pass
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.
match term:
case pattern-1:
action-1
case pattern-2:
action-2
case pattern-3:
action-3
case _:
action-default
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.
else:
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.
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.
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__().
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.
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:
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.
Answer:
The json library is used to serialize and deserialize JSON data, enabling easy data
exchange between systems.
Answer:
The csv library allows reading from and writing to CSV (Comma-Separated Values) files.
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.
Answer:
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.
Answer:
import math
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:
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:
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.
Answer:
import random
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:
103. How can you calculate the square root of a number using the math module?
Answer:
import math
104. What is the difference between [Link]() and the ** operator in Python?
Answer:
105. How can you compute the logarithm of a number to a specific base using the
math module?
Answer:
import math
106. Write a Python program to calculate the area of a circle using the [Link]
constant.
Answer:
import math
radius = 5
print(area)
107. What function would you use to round a number down to the nearest integer?
Answer:
[Link]().
Answer:
math.e is used as the base for natural logarithms.
Example:
import math
Answer:
Answer:
import math
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).
Answer:
115. How can you select a random element from a list using the random library?
Answer:
import random
print([Link]([1, 2, 3, 4]))
Answer:
import random
print([Link](1, 6))
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):
return password
print(generate_password(12))
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
[Link](deck)
print(deck)
Answer:
Answer:
d = date(2024, 1, 1)
Answer:
now = [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.
Answer:
Answer:
date_str = "2024-11-27"
d = [Link](date_str, "%Y-%m-%d")
127. How can you calculate the difference between two dates using the datetime
library?
Answer:
d1 = date(2024, 1, 1)
128. Write a Python program to calculate the number of days until New Year’s Day.
Answer:
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:
Answer:
Dictionary comprehensions provide a concise way to create dictionaries.
Example:
131. What is the difference between read(), readline(), and readlines() in file
handling?
Answer:
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).
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):
class Child(Parent):
def greet(self):
obj = Child()
Answer:
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.
Answer:
Pandas is a Python library used for data manipulation and analysis. It provides two primary
data structures:
Answer:
You can select a column using:
df['column_name']
Answer:
Use:
140. How do you group data by a specific column and calculate summary statistics?
Answer:
Use:
[Link]('column_name').agg({'another_column': 'mean'})
Answer:
Use:
correlation = [Link]()
print(correlation)
Answer:
Matplotlib is a popular Python library used for creating static, animated, and interactive
visualizations such as graphs, bar charts, pie charts, and histograms.
Answer:
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)
Answer:
[Link]()
[Link]()
Answer:
[Link](x, y)
[Link]()
Answer:
axs[0, 0].plot(x, y)
axs[1, 0].scatter(x, y)
[Link]()
148. How do you create a stacked bar chart in Matplotlib?
Answer:
data1 = [3, 5, 7]
data2 = [1, 3, 5]
[Link]()
[Link]()
149. How do you customize the appearance of a Matplotlib plot (e.g., changing line
width, markers, etc.)?
Answer:
[Link]()
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.
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]
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.
def add(x):
return lambda y: x + y
add_five = add(5)
print(add_five(3)) # Output: 8
def greet(name="Guest"):
print(f"Hello, {name}!")
print(args)
print(kwargs)
# Output: (1, 2, 3)
def generate_numbers():
for i in range(3):
yield i
print(num)
● 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]
162. What are the different modes for opening a file in Python? Explain their use
cases.
Answer:
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.
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.
import math
print([Link](-2.7)) # Output: -3
print([Link](-2.7)) # Output: -2
import math
Example:
import random
import random
lst = [1, 2, 3, 4, 5]
[Link](lst)
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
Example:
import random
[Link](42)
[Link](42)
import random
print(choices) # Output: ['a', 'a', 'c', 'b', 'a'] (order may vary)
Example:
class Bird:
def speak(self):
print("Chirp")
class Dog:
def speak(self):
print("Bark")
[Link]()
def quack(duck):
[Link]()
class Duck:
def quack(self):
print("Quack!")
class Human:
def quack(self):
class MyClass:
[Link] = value
obj1 = MyClass(10)
obj2 = MyClass(20)
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"
word = "programming"
count = 0
if char in vowels:
count += 1
print(count) # Output: 3
count = 0
count += 1
print(count) # Output: 8
word = "python"
character = "p"
count = 0
if char == character:
count += 1
print(count) # Output: 1
fib = [0, 1]
[Link](fib[-1] + fib[-2])
min_num = min(number_list)
print(min_num) # Output: 2
num_list = [1, 2, 3, 4, 5]
mid_index = len(num_list) // 2
print(num_list[mid_index]) # Output: 3
string = ''.join(lst)
lst1 = [1, 2, 3]
lst2 = [4, 5, 6]
str1 = "Listen"
str2 = "Silent"
if sorted([Link]()) == sorted([Link]()):
else:
print("False")
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
string = "madam"
if string == string[::-1]:
else:
print("Not a Palindrome")
Answer:
import re
print(len(digitCount))
print(len(letterCount))
print(len(spaceCount))
1
8
2
17. Counting Special Characters in a String
Answer:
import re
spChar = "!@#$%^&*()"
print(len(count))
10
Answer:
import re
spaces = [Link](r'\s+')
result = [Link](spaces, '', string)
print(result)
CODE
19. Building a Pyramid in Python
Answer:
floors = 3
h = 2*floors-1
print('{:^{}}'.format('*'*i, h))
>*
***
*****
Answer:
shuffle(lst)
print(lst)
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'
else:
print("Not a Digit")
Not a Digit
26. Program to replace the string space with any given character
Answer:
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:
except FileNotFoundError:
file_content = read_file("[Link]")
print(file_content)
Answer:
try:
except Exception as e:
print(f"Error: {e}")
write_file("[Link]", data)
Answer:
import csv
def read_csv(file_path):
try:
with open(file_path, "r") as csv_file:
reader = [Link](csv_file)
except FileNotFoundError:
csv_data = read_csv("[Link]")
print(csv_data)
Answer:
import csv
try:
writer = [Link](csv_file)
[Link](data)
except Exception as e:
print(f"Error: {e}")
data = [["Name", "Age", "City"], ["Alice", 30, "New York"], ["Bob", 25, "Los Angeles"]]
write_csv("[Link]", data)
Answer:
import csv
try:
[Link]()
[Link](data)
except Exception as e:
print(f"Error: {e}")
Answer:
print(person["age"])
30
Answer:
square = lambda x: x ** 2
print(square(4))
16
Answer:
x = 42
print(type(x))
<class 'int'>
Answer:
import numpy as np
arr_2d = [Link]([[1, 2], [3, 4], [5, 6]])
print(arr_2d)
Answer:
print([Link])
Answer:
print(arr_zeros)
Answer:
print(arr)
Answer:
Answer:
transpose = arr.T
print(transpose)
Answer:
print([Link]())
print([Link]().sum())
43. Handle Missing Data in Pandas
Answer:
[Link](0, inplace=True)
[Link](inplace=True)
Answer:
grouped = [Link]('Age').mean()
print(grouped)
Answer:
[Link](categories, values)
[Link]()
Answer:
[Link](categories, values)
[Link]()
Answer:
[Link]()
48. Create a Histogram in Matplotlib
Answer:
data = [1, 2, 2, 3, 3, 3, 4, 5, 5, 5, 5, 6]
[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:
except Exception as e:
xml_data = '''<note><to>Tove</to><from>Jani</from><message>Remember
me!</message></note>'''
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)
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)
import random
guess = 0
print("Too high!")
else:
text = "This is a sample text. This text contains some repeated words."
word_count = {}
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):
Args:
Returns:
"""
start = 0
end = len(lst) - 1
start += 1
end -= 1
return ls
# Example usage:
my_list = [1, 2, 3, 4, 5]
reversed_list = reverse_list(my_list)
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
# Difference (B - A)
difference_set2 = B - A
# Symmetric difference
symmetric_difference_set = A ^ B
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}
import math
def pythagorean_theorem():
c = [Link](a**2 + b**2)
pythagorean_theorem()
import random
def roll_dice():
dice_roll = [Link](1, 6)
roll_dice()
import random
import string
def generate_password(length):
letters = string.ascii_letters
digits = [Link]
symbols = [Link]
characters = letters + digits + symbols
generate_password(12)
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)
num_darts_in_circle += 1
monte_carlo_pi(1000000)
import random
def random_walk(steps):
x, y = 0, 0
for _ in range(steps):
if direction == 'N':
y += 1
elif direction == 'S':
y -= 1
x += 1
x -= 1
random_walk(100)
import random
return data
print(data)
import math
import random
values = []
for t in range(time_steps):
[Link](value)
return values
def reverse_string(s):
return s[::-1]
Test:
def is_palindrome(s):
s = [Link]()
return s == s[::-1]
Test:
def find_largest(nums):
return max(nums)
Test:
4. Fibonacci Sequence
Question: Write a Python function to generate the first n Fibonacci numbers.
Answer:
def fibonacci(n):
fib = [0, 1]
[Link](fib[i-1] + fib[i-2])
return fib[:n]
Test:
seen = {}
if diff in seen:
return [seen[diff], i]
seen[num] = i
Test:
def count_characters(s):
return Counter(s)
Test:
def find_missing(nums):
n = len(nums)
total = n * (n + 1) // 2
Test:
8. Validate Parentheses
Question: Write a Python program to validate a string containing parentheses.
Answer:
def is_valid_parentheses(s):
stack = []
for char in s:
if char in mapping:
if mapping[char] != top_element:
return False
else:
[Link](char)
Test:
Test:
def first_non_repeating_char(s):
count = Counter(s)
for char in s:
if count[char] == 1:
return char
return None
Test:
Here’s the same set of questions and answers formatted without lines between the question-
answer sets:
def remove_duplicates(nums):
return list(set(nums))
Test:
def is_prime(n):
if n <= 1:
return False
if n % i == 0:
return False
return True
Test:
Test:
def factorial(n):
if n == 0 or n == 1:
return 1
return n * factorial(n - 1)
Test:
def find_duplicates(nums):
counts = Counter(nums)
Test:
def flatten_list(nested_list):
flat_list = []
if isinstance(item, list):
flat_list.extend(flatten_list(item))
else:
flat_list.append(item)
return flat_list
Test:
def all_subsets(nums):
Test:
print(all_subsets([1, 2, 3])) # Output: [(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]
Test:
def longest_common_prefix(strs):
if not strs:
return ""
prefix = strs[0]
prefix = prefix[:-1]
if not prefix:
return ""
return prefix
Test:
import heapq
Test:
Here’s the formatted set of questions and answers without lines between each question-
answer pair:
def has_zero_sum_subarray(nums):
seen = set()
current_sum = 0
for num in nums:
current_sum += num
return True
[Link](current_sum)
return False
Test:
def transpose_matrix(matrix):
Test:
return gcd(a, b)
Test:
if nums[mid] == target:
return mid
low = mid + 1
else:
high = mid - 1
return -1
Test:
def count_vowels(s):
Test:
return x**y
Test:
def merge_intervals(intervals):
[Link](key=lambda x: x[0])
merged = []
[Link](interval)
else:
return merged
Test:
print(merge_intervals([[1, 3], [2, 6], [8, 10], [15, 18]])) # Output: [[1, 6], [8, 10], [15, 18]]