DON'T WANT TO MISS A THING?

Certification Exam Passing Tips

Latest exam news and discount info

Curated and up-to-date by our experts

Yes, send me the newsletter

Common Python Developer Interview Questions Guide | SPOTO

Whether you're preparing for your first job interview or leveling up your career, having the right preparation makes all the difference. This comprehensive resource covers the most common and challenging Interview Questions and Answers across a wide range of roles and industries — from technical positions to managerial and entry-level jobs. Browse our curated lists of Frequently Asked Interview Questions, behavioral interview questions and answers, situational interview questions, and role-specific interview prep guides designed to help you walk into any interview with confidence. Whether you're looking for IT interview questions and answers, project management interview questions, or top interview questions for freshers, our expert-reviewed content gives you real-world sample answers, proven tips, and insider strategies to help you stand out.
Make your resume stand out — at SPOTO, you can accelerate your career growth by preparing for job interviews while studying for your certification. Click Learn More to take the first step toward career advancement.
View Other Interview Questions

1
What are the benefits of using Python Selenium for web automation?
Reference answer
- Open-source and free to use. - Supports various web browsers and operating systems. - Provides comprehensive API for interacting with web elements. - Integrates well with other Python libraries for data manipulation and testing frameworks.
2
What is Python?
Reference answer
Python is a high-level, interpreted programming language known for its simplicity and readability. It is widely used for web development, data analysis, artificial intelligence, and automation.
Career Acceleration

Earn a certification to make your resume stand out.

According to data analysis, IT certification holders earn an annual salary that is 26% higher than that of average job seekers. At SPOTO, you have the opportunity to accelerate your career growth by pursuing certification and preparing for job interviews simultaneously.

1 100% Pass Rate
2 2 Weeks of Dump Practice
3 Pass the Certification Exam
3
Describe how list comprehensions work in Python. Provide an example.
Reference answer
List comprehensions provide a concise way to create lists. Example: [x for x in range(10) if x % 2 == 0] generates a list of even numbers from 0 to 9.
4
What will be the output of the following code in each step? class C: dangerous = 2 c1 = C() c2 = C() print c1.dangerous c1.dangerous = 3 print c1.dangerous print c2.dangerous del c1.dangerous print c1.dangerous C.dangerous = 3 print c2.dangerous
Reference answer
Output step by step: 2 (class attribute accessed via c1) 3 (instance attribute set on c1) 2 (c2 still accesses class attribute) 2 (after deleting c1's instance attribute, it falls back to class attribute) 3 (class attribute changed, c2 reflects it)
5
What is the difference between .py and .pyc files?
Reference answer
The .py files are the python source code files. While the .pyc files contain the bytecode of the python files. .pyc files are created when the code is imported from some other source. The interpreter converts the source .py files to .pyc files which helps by saving time.
6
What is an iterator in Python?
Reference answer
An iterator is an object that contains a countable number of values. An iterator is an object that can be iterated upon, meaning that you can traverse through all the values. Technically, in Python, an iterator is an object which implements the iterator protocol, which consist of the methods __iter__() and __next__().
7
What is the difference between a list and a tuple?
Reference answer
Unlike lists, tuples are not editable and faster. They also have different syntax: for tuples: tup_1 = (10, 'Chelsea' , 20) for lists: Syntax: list_1 = [10, 'Chelsea', 20]
8
What are Literals in Python and explain about different Literals
Reference answer
A literal in python source code represents a fixed value for primitive data types. There are 5 types of literals in python- name="Tanya" a='t' a=50 a) List collections-Eg. a=[1,2,3,'Amit'] b) Tuple literals- Eg. a=(5,6,7,8) c) Dictionary literals- Eg. dict={1: 'apple', 2: 'mango, 3: 'banana`'} d) Set literals- Eg. {"Tanya", "Rohit", "Mohan"} 6. Special literal- Python has 1 special literal None which is used to return a null variable.
9
How do you find the longest consecutive sequence in an unsorted list?
Reference answer
Use a set for O(1) lookups and iterate to find consecutive elements. Example: def longest_consecutive(nums): num_set = set(nums) longest = 0 for num in num_set: if num - 1 not in num_set: length = 1 while num + length in num_set: length += 1 longest = max(longest, length) return longest print(longest_consecutive([100, 4, 200, 1, 3, 2])) # 4
10
What are global, protected and private attributes in Python?
Reference answer
- Global variables are public variables that are defined in the global scope. To use the variable in the global scope inside a function, we use the global keyword. - Protected attributes are attributes defined with an underscore prefixed to their identifier eg. _sara. They can still be accessed and modified from outside the class they are defined in but a responsible developer should refrain from doing so. - Private attributes are attributes with double underscore prefixed to their identifier eg. __ansh. They cannot be accessed or modified from the outside directly and will result in an AttributeError if such an attempt is made.
11
Explain the term Monkey Patching in python?
Reference answer
Monkey patching is a method by which we can extend or modify our code while runtime.
12
What are the key security considerations in Python applications?
Reference answer
Security is paramount in Python applications. Key considerations include: - Sanitize user input to prevent injection attacks. Use parameterized queries and avoid concatenating user input into commands or queries. - Be mindful of third-party modules and libraries. Use reputable sources and regularly update them. Check libraries for known vulnerabilities using tools like PyUp or Safety. - Implement proper error handling to avoid exposing stack traces or sensitive information. Customize error pages to hide system details. - Use strong encryption standards for data protection. Employ robust encryption algorithms for storing sensitive data. Python's cryptography library can help. - Enable secure communication by using HTTPS to encrypt data transmitted between client and server. - Manage session security by using secure, HttpOnly cookies and implementing token expiration and regeneration strategies. - Limit user and system privileges by applying the principle of least privilege. - Regularly audit and test for vulnerabilities using automated tools like SAST and DAST, and consider manual penetration testing. - Stay informed about latest security threats and best practices by joining communities and attending conferences.
13
What is the purpose of the subprocess module in Python, and how can you use it to execute external processes?
Reference answer
The `subprocess` module allows you to spawn new processes, connect to their input/output/``error pipes, and obtain return codes.
14
What are decorators?
Reference answer
Decorators in Python are functions that modify the behavior of another function or method without changing its code. They are applied using the @decorator syntax and are commonly used for logging, access control, or timing.
15
How Can You Generate Random Numbers in Python?
Reference answer
Python supports several functions to generate random numbers, some of these are: - random() – generates a floating point number between 0 and 1. - uniform (X, Y) – generates a floating point number between X and Y. - Randint (X, Y) – generates a random integer that lies between X and Y.
16
94. How can you set a breakpoint in Python code to debug?
Reference answer
To set a breakpoint in Python code for debugging, use the `breakpoint()` function. This function was introduced in Python 3.7 and offers a convenient way to enter the built-in debugger, `pdb`. Interpreter pauses the execution, when it encounters the `breakpoint()` function. You can inspect variables, step through code, and evaluate expressions at this point. Insert `import pdb; pdb.set_trace()`, To use the breakpoint in older versions of Python, prior to 3.7. This command provides similar functionality, allowing you to stop the code and interact with the debugger. Always remember to remove or comment out breakpoints before deploying or sharing your code, as they halt the execution and open the debugger.
17
What is Python, and why is it so popular in the programming world?
Reference answer
Python is a high-level, interpreted, and general-purpose programming language. It gained popularity due to its simplicity, readability, versatility, and a large collection of libraries and frameworks that make development faster and more efficient.
18
How can you filter rows of a DataFrame based on a condition in Pandas?
Reference answer
You can filter rows by specifying a condition within square brackets. For example: `df[df[```'column_name'] > 50```]filters``rows where the 'column_name' is greater than 50.```
19
What Are the Different Applications That Python Can Create?
Reference answer
With Python, you can create web applications of any type like healthcare, fintech, entertainment, eCommerce apps, etc. You can also work with data-related projects, including machine learning, artificial intelligence, and natural language processing. The language is used for IoT technology as well.
20
What is the Global Interpreter Lock (GIL) in Python?
Reference answer
The Global Interpreter Lock (GIL) is a mutex in the CPython interpreter that allows only one thread to execute Python bytecode at a time. This can limit the parallelism of multi-threaded Python programs.
21
What do you mean by dead code?
Reference answer
: A part of the code, which is never executed, is known as dead code. This is generally written after the return statement and will never be executed.
22
How do you iterate through a list in Python?
Reference answer
Alternatively, use list comprehension: [expression for item in list]
23
What are Python functions?
Reference answer
A Python function is a set of commands and instructions that is active after a developer calls it. To define a function, Python programmers use the def keyword. To call the function, type functioname(). If a function features arguments, you have to specify them inside the parentheses.
24
What are python namespaces ? What are their applications ?
Reference answer
Namespace is a mapping from names (identifiers) to objects. It serves as a system to organize and provide a unique context for names in a Python program. Namespaces help prevent naming conflicts and provide a way to access objects in a structured manner. Python uses namespaces to determine the scope of names. When you use a variable, function, or any other object, Python looks for that name within the available namespaces to resolve it. Here are a few types of namespaces in Python: - Built-in Namespace: It contains the names of built-in functions, exceptions, and objects that are available by default in Python. Examples include print(), len(), str, etc. - Global Namespace: It refers to the names defined at the top level of a module or declared as global within a function. These names are accessible throughout the module or function. - Local Namespace: It represents the names defined within a function. These names are accessible only within the function's scope. - Class Namespace: It contains the names defined within a class. These names are accessible within the class and can be accessed using the class name.
25
What is the purpose of the __str__ method in Python classes?
Reference answer
The __str__ method is used to define the "informal" or user-friendly string representation of an object. It is called when the str() function is used or when an object is printed. class MyClass: def __init__(self, x, y): self.x = x self.y = y def __str__(self): return f"MyClass(x={self.x}, y={self.y})" # Usage obj = MyClass(10, 20) print(obj) # Output: MyClass(x=10, y=20)
26
Implement depth first search (DFS) in Python
Reference answer
Consider this graph, implemented in the code below: # Using a Python dictionary to act as an adjacency list graph = { 'A' : ['B','C'], 'B' : ['D', 'E'], 'C' : ['F'], 'D' : [], 'E' : ['F'], 'F' : [] } visited = set() # Set to keep track of visited nodes. def dfs(visited, graph, node): if node not in visited: print (node) visited.add(node) for neighbour in graph[node]: dfs(visited, graph, neighbour) # Driver Code dfs(visited, graph, 'A') Output: A B D E F C Explanation Lines 2-9: The illustrated graph is represented using an adjacency list - an easy way to do it in Python is to use a dictionary data structure. Each vertex has a list of its adjacent nodes stored. Line 11: visited is a set that is used to keep track of visited nodes. Line 21: The dfs function is called and is passed the visited set, the graph in the form of a dictionary, and A , which is the starting node. Lines 13-18: dfs follows the algorithm described above: - It first checks if the current node is unvisited - if yes, it is appended in the visited set. - Then for each neighbor of the current node, the dfs function is invoked again. - The base case is invoked when all the nodes are visited. The function then returns. Time Complexity Since all the nodes and vertices are visited, the average time complexity for DFS on a graph is O(V + E), where V is the number of vertices and E is the number of edges. In case of DFS on a tree, the time complexity is O(V), where V is the number of nodes.
27
How does Python's ecosystem and community contributions impact development?
Reference answer
Python's ecosystem is incredibly rich and diverse, thanks to extensive community contributions. The community's contributions have significantly expanded Python's capabilities, making it a powerful and versatile tool for developers. One of the most notable aspects is its vast collection of libraries and frameworks, providing pre-written code for tasks from complex calculations to data visualization. Libraries like NumPy and pandas are staples for data scientists, while web developers use frameworks like Django and Flask. The Python Package Index (PyPI) is a central repository housing thousands of packages, a testament to the collaborative nature of the community. Open source contributions are a cornerstone, allowing anyone to contribute to development, speeding up the process and ensuring continuous improvement. The vibrant community provides support and collaboration through online forums like Stack Overflow and Reddit, tech conferences, and regional user groups. The Python Software Foundation (PSF) manages open source licensing and supports the growth of the international community. Python's documentation is another community-driven achievement, comprehensive and constantly updated, along with tutorials and guides that disseminate knowledge and best practices.
28
Write a Python function to find all unique triplets in a list that sum up to zero.
Reference answer
Sample Answer: To find triplets that sum to zero, you can sort the list and use a two-pointer approach to find combinations. Here is a sample Python function to find all unique triplets in a list that sum up to zero: def three_sum(nums): nums.sort() result = [] for i in range(len(nums) - 2): if i > 0 and nums[i] == nums[i - 1]: continue left, right = i + 1, len(nums) - 1 while left < right: total = nums[i] + nums[left] + nums[right] if total < 0: left += 1 elif total > 0: right -= 1 else: result.append([nums[i], nums[left], nums[right]]) left += 1 right -= 1 while left < right and nums[left] == nums[left - 1]: left += 1 while left < right and nums[right] == nums[right + 1]: right -= 1 return result
29
What are the ways to swap the values of two elements?
Reference answer
The below program can be used to swap the value in a List: # Swap function def swapPositions(list, pos1, pos2) list[pos1], list[pos2] = list[pos2], list[pos1] return list # Driver function List = [23, 65, 19, 90] pos1, pos2 = 1, 3 print(swapPositions(List, pos1-1, pos2-1)) Output: [19, 65, 23, 90]
30
What is the output of the following code? print(var[0]) if var='Hello Everyone!'
Reference answer
The output would be: H
31
Define encapsulation.
Reference answer
It is the process of transforming a sequence of statements into a function definition. Everything is encapsulated inside the function.
32
What is a virtual environment in Python, and why would you use one?
Reference answer
A virtual environment is an isolated Python environment that allows you to manage dependencies separately for different projects. You use them to avoid conflicts between project-specific libraries.
33
What does the Python help() function do?
Reference answer
The Python help() function will return the documentation of Python modules, classes, functions, etc.
34
66. What is the difference between a stack and a queue?
Reference answer
The difference between Stack and Queue Data Structures is that Stack follows LIFO while Queue follows FIFO data structure type. A stack operates on the principle of Last-In, First-Out (LIFO), meaning that the last element added is the first one to be removed. It resembles a stack of books, where you can only add or remove items from the top. Stacks are used for tasks like function call management and maintaining a history of actions. A queue follows the First-In, First-Out (FIFO) rule, where the first element added is the first to be removed. Imagine it as a line of people waiting for a bus; the person who arrived first boards the bus first. Queues are essential in scenarios like task scheduling and managing resources in a sequential order.
35
How do you locate web elements on a page using Selenium?
Reference answer
- Different locators like by ID, name, class name, XPath, CSS selector offer unique targeting abilities. - Choose the most efficient and robust locator based on the element structure.
36
Write a Python code to implement a queue using collections.deque
Reference answer
from collections import deque class Queue: def __init__(self): self.queue = deque() def enqueue(self, item): self.queue.append(item) def dequeue(self): return self.queue.popleft() if self.queue else None # Example usage q = Queue() q.enqueue(1) q.enqueue(2) print(q.dequeue()) # 1 print(q.dequeue()) # 2 print(q.dequeue()) # None
37
What are Python decorators?
Reference answer
A design pattern in Python that helps you to modify the behavior of a function or method without changing its code is a decorator. They are implemented as higher order functions. Example: def decorator(func): def wrapper(): print("Before function call") func() print("After function call") return wrapper @decorator def greet(): print("Hello") greet() Output: Before function call Hello After function call
38
Explain the purpose of SQLAlchemy in Python.
Reference answer
SQLAlchemy is a library used for database interaction in Python. It provides an Object-Relational Mapping (ORM) system for working with databases.
39
Does Python have good multithreading capabilities?
Reference answer
Python offers a multi-threading package but it is not really good for speeding up the code. The GIL is a great way though it is not really multithreading. It executes one at a time but takes turns for different threads really fast which makes it seem like processes are running simultaneously.
40
Debug the following Python code snippet that is supposed to find the sum of even numbers in a list.
Reference answer
def sum_even_numbers(lst): sum = 0 for num in lst: if num % 2 == 0: sum += num return sum # Example usage: # print(sum_even_numbers([1, 2, 3, 4, 5, 6])) # Output: 12
41
What is a map function in Python?
Reference answer
The map() function in Python applies a given function to every item in an iterable, such as a list, and returns a map object (an iterator). It is used for efficient data transformation without explicit loops.
42
What are the four core principles of Object-Oriented Programming (OOP) in Python?
Reference answer
Encapsulation: This involves bundling data and methods together while controlling access. Python achieves this with naming conventions like a single underscore (_variable) for internal use and double underscores (__variable) for name mangling. Inheritance: This allows a child class to inherit properties and methods from a parent class, promoting code reuse. Polymorphism: This enables different classes to use the same interface, often achieved by overriding methods in subclasses. Abstraction: This hides complex implementation details, exposing only the essentials through abstract base classes.
43
How do you find all combinations of a given sum in a list?
Reference answer
Sample Answer: To find all combinations of numbers that sum up to a target value, you can use backtracking. Here is how you can find all combinations of a given sum in a list: def combination_sum(candidates, target): def backtrack(start, path, total): if total == target: result.append(path) return if total > target: return for i in range(start, len(candidates)): backtrack(i, path + [candidates[i]], total + candidates[i]) result = [] backtrack(0, [], 0) return result
44
You're building a REST API endpoint. How would you handle authentication, authorization, and error handling?
Reference answer
- Answer: I'd utilize libraries like Flask-JWT or Flask-RESTful for authentication and authorization. For error handling, I'd define custom error codes and responses based on the type of error encountered.
45
What are some popular testing frameworks for Python?
Reference answer
Unittest - Built-in with the standard library. - Simple and beginner-friendly. - Best for unit testing individual modules and functions. - Python Example: import unittest class TestMyFunction(unittest.TestCase): def test_case(self): self.assertEqual(my_function(2), 4) Pytest - Most popular and flexible framework. - Supports various testing types like unit, integration, and functional tests. - Highly customizable and extensible with plugins. - Python Example: def test_my_function(): assert my_function(2) == 4 Doctest - Extracts and runs test examples from docstrings. - Encourages clear and documented code. - Simple for small projects or quick tests. - Python Example: def add(a, b): """ >>> add(2, 3) 5 """ return a + b Behave and Lettuce: - Focus on behavior-driven development (BDD). - Write tests in human-readable language like Gherkin. - Good for collaborative testing and non-technical stakeholders. - Python Example: Feature: Login Scenario: Successful login Given I am on the login page When I enter valid credentials Then I should see the dashboard Selenium: - For testing web applications through browser automation. - Simulates user interactions like clicking buttons and entering text. - Requires additional libraries like Selenium WebDriver. - Python Example: from selenium import webdriver driver = webdriver.Chrome() driver.get('https://example.com')
46
What are the basic data types in Python?
Reference answer
Python has several basic data types: - Numbers: Integers (whole numbers), floats (decimals), booleans (True/False). - Strings: Sequences of characters enclosed in quotes (e.g., "Hello"). - Lists: Ordered collections of elements enclosed in square brackets (e.g., [1, 2, "apple"]). - Tuples: Similar to lists but immutable (cannot be changed) and enclosed in parentheses (e.g., (1, 2, "apple")). - Sets: Unordered collections of unique elements enclosed in curly braces (e.g., {1, 2, 3}). - Dictionaries: Key-value pairs enclosed in curly braces (e.g., {"name": "John", "age": 30}).
47
What are list and dict comprehensions?
Reference answer
List comprehensions provide a concise way to create lists by iterating over an iterable and optionally filtering elements. Example: [x**2 for x in range(5) if x % 2 == 0]. Dict comprehensions create dictionaries similarly: {x: x**2 for x in range(5)}.
48
Write a program to check for an anagram.
Reference answer
Sample Answer: Two strings are considered anagrams if they can be rearranged to form one another. This means they contain the same characters in the same frequency but in a different order. A simple way to check for anagrams is to sort both strings and compare the sorted versions. If the sorted strings are identical, then the original strings are anagrams of each other. For example: def are_anagrams(s1, s2): return sorted(s1) == sorted(s2)
49
Explain Python's indentation.
Reference answer
Python uses indentation (whitespace) to define code blocks. It enforces code readability and consistency.
50
99. How to use Python's `logging` module to log errors?
Reference answer
To use Python's `logging` module to log errors, you first import the module. Various logging levels are available, such as DEBUG, INFO, WARNING, ERROR, and CRITICAL, once imported. The logging module logs messages with a severity level of WARNING or higher by default. Use the `logging.error()` function, To log an error. This function records messages with the ERROR level. For example, `logging.error("This is an error message")` will log the provided error message. You add the `exc_info=True` argument, To capture exception information. This is especially useful when handling exceptions in a try-except block. Customize logging behavior by configuring the basic settings using `logging.basicConfig()`. This function allows you to set the logging level, specify a log file, and format the log messages. Set the logging level to ERROR using `logging.basicConfig(level=logging.ERROR)`. Adjust this level as needed to capture messages of different severities. Your engineers should not be hiring. They should be coding. Help your team focus on what they were hired for. Flexiple will manage your entire hiring process and scale your tech team.
51
What is __init__ in Python?
Reference answer
In Python, the __init__ method is used as a constructor for classes. Whenever a new instance of a class is created, __init__ is called first. Constructors are usually used to set up class attributes. class Car(): # __init__ sets up the make, model, and color of the car object def __init__(self, make, model, color): self.make = make self.model = model self.color = color
52
How can you apply a function to every element in a Pandas DataFrame or Series?
Reference answer
You can use the `.applymap()` method for DataFrames and the `.apply()` method for Series to apply a function to every element.
53
What is the purpose of the index_col parameter in the pd.read_csv() function?
Reference answer
The `index_col` parameter is used to specify which column from the CSV file should be used as the index (``row labels) of the DataFrame.
54
Calculate the factorial of a number:
Reference answer
def factorial(n): if n == 0: return 1 return n * factorial(n - 1)
55
What is the difference between a built-in exception and a custom exception in Python?
Reference answer
A built-in exception is an exception that is provided by the Python interpreter, such as TypeError or IndexError. A custom exception, on the other hand, is an exception that is defined by the user to handle specific error conditions in their program**.**
56
Explain the difference between list and tuple in Python.
Reference answer
Lists are mutable, meaning you can modify their elements, while tuples are immutable, meaning their elements cannot be changed after creation. Lists are defined using square brackets [], and tuples use parentheses ().
57
What is the purpose of the zip() function?
Reference answer
The zip() function combines two or more iterables into tuples, stopping at the shortest iterable. Example: a = [1, 2, 3] b = ['x', 'y', 'z'] print(list(zip(a, b))) # [(1, 'x'), (2, 'y'), (3, 'z')]
58
What Is PIP Software in the Python World?
Reference answer
Pip is a package manager. It allows you to add frameworks, libraries, and other additions that are not included in the standard Python package.
59
What is OrderedDict in Python?
Reference answer
OrderedDict() is used to maintains the sequence in which keys are added, ensuring that the order is preserved during iteration. In contrast, a standard dictionary does not guarantee any specific order when iterated, providing values in an arbitrary sequence. OrderedDict() distinguishes itself by retaining the original insertion order of items.
60
What are literals in Python?
Reference answer
Literals are used to represent fixed values for primitive data types in a Python source code.
61
What is Python, and list some of its key features.
Reference answer
Python is a versatile, high-level programming language known for its easy-to-read syntax and broad applications. Here are some of Python's key features: - Simple and Readable Syntax: Python's syntax is clear and straightforward, making it accessible for beginners and efficient for experienced developers. - Interpreted Language: Python executes code line by line, which helps in debugging and testing. - Dynamic Typing: Python does not require explicit data type declarations, allowing more flexibility. - Extensive Libraries and Frameworks: Libraries like NumPy, Pandas, and Django expand Python's functionality for specialized tasks in data science, web development, and more. - Cross-Platform Compatibility: Python can run on different operating systems, including Windows, macOS, and Linux.
62
46. How to write a Python program to find the second largest number in a list?
Reference answer
Second largest number in a Python list can be found using built-in functions and list comprehension. One approach is to convert the list into a set to remove duplicates, then convert it back to a list and sort it. The second last element of this sorted list is the second largest number. For instance, `sorted(list(set(my_list)))[-2]` gives the desired result. However, consider edge cases. Ensure the list contains at least two distinct numbers before proceeding, to avoid index errors. If the list doesn't satisfy this condition, return an appropriate message or value.
63
What is namespace in Python?
Reference answer
In order to give a distinct and unique name to every single object, Python has a system called, namespace. The value of the object, which can be a variable or a method, is connected to the unique name assigned to that object. While searching for the object, the key, which corresponds to the unique name, is mapped with the value assigned to the related object. Python has its namespace maintained like a Python dictionary.
64
84. How can you secure a web application in Python?
Reference answer
You must sanitize user input to prevent SQL injection attacks, to secure a web application in Python. Input validation ensures that the application doesn't process harmful data. Implement Content Security Policy headers to reduce the risk of cross-site scripting attacks. Use HTTPS to encrypt data transmitted between the client and the server, ensuring data integrity and preventing man-in-the-middle attacks. Use well-established libraries and frameworks, such as Flask and Django, which provide built-in security mechanisms. Update these libraries regularly to stay protected from known vulnerabilities. Handle user authentication with care. Store passwords using cryptographic hashing functions like bcrypt or Argon2. Implement rate limiting to prevent brute force attacks. Limit exposure of sensitive information in error messages. Customize your error pages, so they don't leak internal application details. Audit your code for security vulnerabilities, and consider using automated tools to identify potential security flaws. Remember to secure not just the application but also its environment, including the database and server.
65
Write the python code to perform Write and Read operation in Python ?
Reference answer
# Open the file in write file = open("file.txt", "w") file.write("Hello Prepsters.\n") file.write("We will assist you in getting IT Job.\n") file.write("Here, You'll learn various skills.") file.close() # Opening the file in read mode. file = open("file.txt", "r") contents = file.read() print(contents) # file.close() # Closing the file
66
How can you find unique values in a column of a Pandas DataFrame?
Reference answer
You can use the `.```unique```()` method to find unique values in a column of a Pandas DataFrame.
67
How can you access the first five rows of a DataFrame in Pandas?
Reference answer
You can use the .head() method on a DataFrame to access the first five rows. For example: df.head().
68
What is the difference between pass by value and pass by reference?
Reference answer
Pass by value is the passing of the copy. If the copy is edited, the original object will remain the same. Pass by reference is passing of the reference to the original. Edits in the reference will result in changes in the original object.
69
Can you copy a List in Python by simply writing: list2 = list1?
Reference answer
No, because: list2 will only be a reference to list1, and changes made in list1 will automatically also be made in list2. To make a copy of a list, you can use copy() or the list() method.
70
What do you mean by module object?
Reference answer
A value created by an import statement that provides access to the values defined in a module. e.g import math , here math is a module object and using dot notation you can access the variables defined in this module for instance math.pi
71
What are Python's coroutines, and how are they used?
Reference answer
Coroutines are functions that can pause and resume execution using the yield or await keywords. They are used in asynchronous programming to handle tasks like I/O without blocking execution. Example: async def fetch_data(): await asyncio.sleep(1) return "Data fetched"
72
What does the ** operator do in Python?
Reference answer
The ** operator performs exponential calculations in Python. # x equals 8 x=2**3
73
What is Scope in Python?
Reference answer
Every object in Python functions within a scope. A scope is a block of code where an object in Python remains relevant. Namespaces uniquely identify all the objects inside a program. However, these namespaces also have a scope defined for them where you could use their objects without any prefix. A few examples of scope created during code execution in Python are as follows: - A local scope refers to the local objects available in the current function. - A global scope refers to the objects available throughout the code execution since their inception. - A module-level scope refers to the global objects of the current module accessible in the program. - An outermost scope refers to all the built-in names callable in the program. The objects in this scope are searched last to find the name referenced. Note: Local scope objects can be synced with global scope objects using keywords such as global.
74
What are the key differences between the multiprocessing and threading modules in Python, and when would you use each for parallelism?
Reference answer
multiprocessing``is used for CPU-bound tasks and creates separate processes,` `while` threading `is` `used` `for` `I/O-bound tasks and creates threads.
75
18. How can you explain inheritance and polymorphism in Python?
Reference answer
Inheritance in Python is a way to create new classes based on existing classes. Inheritance allows you to reuse code and create more complex classes without having to start from scratch. Polymorphism in Python is the ability of objects to take on different forms. Polymorphism is done by creating multiple classes that inherit from a single base class. Each class can then be used interchangeably, as they all share the same interface. Inheritance allows a class to inherit attributes and methods from another class. The class being inherited from is the "base" or "parent" class, and the class that inherits is the "derived" or "child" class. Allowing developers to extend functionality without altering existing code, code reuse is enhanced through inheritance. A child class can also override or extend the properties and methods of its parent class, enabling customization and enhancement. Polymorphism is the ability of different classes to be treated as instances of the same class through inheritance. This is achieved by method overriding In Python, where a child class provides a different implementation of a method defined in its parent class. You can use the same method name to perform different tasks depending on the object you're working with. With polymorphism, flexibility and extensibility are boosted, ensuring code is more maintainable and versatile.
76
How would you get all the values in a Python dictionary?
Reference answer
You would use the dictionary values function. dict={'first':'Bob', 'last':'Smith'} all_values=dict.values()
77
What is the pd.to_numeric() function used for in Pandas?
Reference answer
The `pd.to_numeric()` function is used to convert a Pandas Series to numeric data types, handling errors or missing values as specified.
78
12. What is the purpose of `__init__.py` in Python?
Reference answer
The purpose of `__init__.py` in Python is to indicate that a directory should be considered a Python package. Directory are imported just like a module, when a directory is recognized as a Python package. This allows for organized structuring and modularization of Python code. The presence of `__init__.py` signifies to the Python interpreter that the directory contains package-related information. `__init__.py` contains initialization code. This code runs when the package is imported. Any package-level variables or initial setup tasks are placed here. The introduction of namespace packages allows directories without `__init__.py ` to also be considered as packages, with Python 3.3 and later. This is facilitated by the "PEP 420" specification. It's still a good practice to include `__init__.py` , especially for compatibility with older versions. `__init__.py` serves both as an indicator for package directories and as an initialization script for package contents, including it ensures clarity and backward compatibility in Python projects.
79
What is inheritance in Python?
Reference answer
Inheritance allows One class to gain all the members(say attributes and methods) of another class. Inheritance provides code reusability, makes it easier to create and maintain an application. The class from which we are inheriting is called super-class and the class that is inherited is called a derived / child class. They are different types of inheritance supported by Python:
80
Explain what Python generators are.
Reference answer
Python generators are functions that use the 'yield' keyword to return values one at a time, pausing execution between yields. They are memory-efficient for iterating over large datasets and produce an iterator object.
81
What are Python libraries? Give some examples.
Reference answer
Python libraries are a collection of Python packages. Some of the majorly used python libraries are – Numpy, Pandas, Matplotlib, Scikit-learn and many more.
82
Describe the use of *args and **kwargs in Python.
Reference answer
*args allows you to pass a variable number of positional arguments, and **kwargs lets you pass a variable number of keyword arguments. They're useful for functions that can accept an arbitrary number of inputs.
83
Make a Binary search program in Python
Reference answer
def binary_search(arr, target): low = 0 high = len(arr) - 1 while low <= high: mid = (low + high) // 2 mid_value = arr[mid] if mid_value == target: return mid elif mid_value < target: low = mid + 1 else: high = mid - 1 return -1 elements = input("Enter a list of numbers = ").split() target = int(input("Enter the number to be searched = ")) arr = [int(element) for element in elements] arr.sort() print("Sorted List =",arr) index = binary_search(arr, target) if index != -1: print(f"{target} is at index {index}") else: print(f"{target} is not present in the list")
84
34. How to write a Python function to compute the factorial of a number?
Reference answer
Python function to compute the factorial of a number is written with the help of recursion or iteration. Using recursion, the factorial function is defined such that it multiplies the number by the factorial of the number minus one. The function calls itself until it reaches the base case. For the number 0, the factorial is 1. Using iteration, you can define the factorial function with a loop. Initialize a result variable to 1, then multiply it by every integer up to the given number. Using iteration Using recursion Both methods achieve the same result, recursion can lead to a stack overflow for large numbers, making iteration more efficient in such cases.
85
What is the difference between mutable and immutable data types in Python?
Reference answer
The difference between mutable and immutable objects is that mutable objects can be modified, while immutable objects can't be altered once created. For example, types like list, dict, and set are mutable, meaning they can be changed in place while retaining the same memory address. On the other hand, types like int, str, tuple, and frozenset are immutable - any modification creates a new object.
86
What are the major two-loop statements in Python?
Reference answer
While and For are the major two-loop statements in Python.
87
What is a lambda function in Python and when would you use it?
Reference answer
A lambda function is a small, anonymous function defined using the lambda keyword. Unlike standard functions defined with def, lambdas are typically used for short-lived operations where a formal name is unnecessary. The body is strictly limited to a single expression with no explicit return statement; the evaluated result is returned automatically. Common use cases include: as arguments to map() and filter() for in-place transformations, as custom key functions for sorting complex data structures (e.g., sorted(data, key=lambda x: x['age'])), and as callbacks in GUI frameworks or asynchronous programming. Named functions are preferred when logic is not immediately obvious. PEP 8 discourages binding lambdas to identifiers since a def statement should be used instead.
88
Does Python support multiple inheritance?
Reference answer
There are only a few modern programming languages supporting multiple inheritance and Python is one of them. So yes, it has the ability to derive a class from multiple base classes at the same time.
89
How do you remove duplicates from a list in Python?
Reference answer
You can remove duplicates from a list by converting it to a set and then back to a list, or by using a loop with a temporary list. my_list = [1, 2, 2, 3, 4, 4, 5] unique_list = list(set(my_list)) # Removes duplicates # OR unique_list = [] for item in my_list: if item not in unique_list: unique_list.append(item)
90
What is the purpose of the indentation in Python?
Reference answer
- Python syntax uses indentation (spaces or tabs) to define code blocks and control program flow.
91
How does Python handle exceptions?
Reference answer
Python uses try-except blocks to catch and handle errors. Example: try: print(10 / 0) except ZeroDivisionError: print("Cannot divide by zero!")
92
How do you create a Pandas DataFrame from various data sources (CSV, Excel, SQL)?
Reference answer
- Use built-in functions like pd.read_csv, pd.read_excel, and pd.read_sql with appropriate parameters.
93
How will you read CSV data into an array in NumPy?
Reference answer
This can be achieved by using the genfromtxt() method by setting the delimiter as a comma. from numpy import genfromtxt csv_data = genfromtxt('sample_file.csv', delimiter=',')
94
How will you find bugs and errors in python code?
Reference answer
To find bugs and errors in python code we can use Python Debgger Tool or PDB.
95
Write a Python function to check if a number is a perfect number.
Reference answer
Solution: def is_perfect_number(number): if number <= 0: return False divisor_sum = 0 # Find proper divisors and sum them up for i in range(1, number): if number % i == 0: divisor_sum += i # Check if the sum of proper divisors equals the number return divisor_sum == number # Example usage input_number = 28 if is_perfect_number(input_number): print(input_number, "is a perfect number.") else: print(input_number, "is not a perfect number.") Output: 28 is a perfect number.
96
Explain the Global Interpreter Lock (GIL) in Python.
Reference answer
The Global Interpreter Lock (GIL) is a mutex in the CPython interpreter that allows only one thread to execute Python bytecode at a time. This can limit multi-threading performance, especially for CPU-bound tasks.
97
How do developers use "with" in Python?
Reference answer
With is a statement used to simplify exception handling. It encapsulates cleanup and preparation in a context manager. It facilitates managing a file stream and improves code readability – for example, there's no need to call file.close() when using with.
98
How does Python's try, except, else, and finally blocks work for exception handling?
Reference answer
try: Runs the main code block. except: Catches specific exceptions. else: Executes if no errors occur. finally: Ensures cleanup happens, no matter what. It's important to catch specific exceptions rather than using a generic except. For instance, catching FileNotFoundError is more precise than broadly catching all exceptions.
99
What is Dynamically typed and Statically typed languages ?
Reference answer
Dynamically Typed: In dynamically typed languages, variable types are determined at runtime, meaning that type checking occurs during program execution. Variables can be assigned values of different types at different points in the program. Code Ex- # Dynamically typed language example (Python) x = 10 # x is an integer print(x) x = "Ten" # x is now a string print(x) x = [10, 20, 30] # x is now a list print(x) Statically Typed: In statically typed languages, variable types are checked and resolved during compile-time, before the program is executed. Variables must be explicitly declared with their types, and type checking is performed at compile-time. Code Ex- #include using namespace std; int main () { int x = 5; // x is an integer cout << x << endl; x = "Hello"; cout << x << endl; return 0; } // Error: invalid conversion from 'const char*' to 'int'
100
How can you check if all the characters in a string are alphanumeric?
Reference answer
You can use the isalnum() method, which returns True if all the characters are alphanumeric, meaning alphabet letter (a-z) and numbers (0-9).
101
Explain the purpose of the __str__ and __repr__ methods in Python classes?
Reference answer
The __str__ method is used to define a string representation of an object that is suitable for end-users. It is called by the str() function and the print() function. The __repr__ method, on the other hand, is used to define a string representation of an object that is mainly used for debugging and development purposes. It is called by the repr() function and is often used to produce a string that can recreate the object when evaluated.
102
What is asynchronous programming in Python?
Reference answer
Asynchronous programming in Python is a method of concurrency where tasks are executed without blocking the execution of other tasks. It is particularly useful for I/O-bound and high-latency operations, allowing programs to be more responsive and efficient. The asyncio library is commonly used, providing a framework revolving around the event loop, which is the core of every asyncio application. The event loop runs asynchronous tasks and callbacks, performs network IO operations, and manages subprocesses. Key concepts include: - Coroutines: Functions defined using async def that can be paused and resumed, allowing non-blocking code that looks synchronous. - Event Loop: The orchestrator managing the execution of different tasks. - Tasks: Used to schedule coroutines concurrently using asyncio.create_task(). - Futures: Low-level awaitable objects representing an eventual result of an asynchronous operation. - Awaitables: Objects that can be used in an await expression, including coroutines, Tasks, and Futures. A simple example is fetching data from a server without blocking other tasks. Not all libraries are async-friendly; use async versions like aiohttp for HTTP requests instead of requests to avoid blocking the event loop.
103
92. What are the different ways to do code testing in Python?
Reference answer
There are different ways to do code testing in Python. One of the most common methods is using the built-in `unittest` module. This framework, based on Java's JUnit, supports test automation, aggregation of tests into collections, and independence of the tests from the reporting framework. Python also supports testing with the `pytest` module. This is a popular tool due to its concise syntax and powerful features. Do X, if a test fails, `pytest` provides detailed error reports. Python developers use `behave`, For behavior-driven development. It reads tests in natural language and translates them to Python code. Python supports a variety of testing tools and libraries such as `nose2`, `doctest`, and `tox`. These tools help ensure the code's quality, functionality, and performance.
104
What are generators in Python?
Reference answer
Generators are functions that return an iterable collection of items, one at a time, in a set manner. Generators, in general, are used to create iterators with a different approach. They employ the use of yield keyword rather than return to return a generator object. Let's try and build a generator for fibonacci numbers - ## generate fibonacci numbers upto n def fib(n): p, q = 0, 1 while(p < n): yield p p, q = q, p + q x = fib(10) # create generator object ## iterating using __next__(), for Python2, use next() x.__next__() # output => 0 x.__next__() # output => 1 x.__next__() # output => 1 x.__next__() # output => 2 x.__next__() # output => 3 x.__next__() # output => 5 x.__next__() # output => 8 x.__next__() # error ## iterating using loop for i in fib(10): print(i) # output => 0 1 1 2 3 5 8
105
Tell something about Python ?
Reference answer
Python is a general-purpose, high-level, and interpreted programming language. Python supports objects, modules, exception-handling, threads, and automatic memory management which help in solving real-world problems with less coding.
106
What are the benefits of using vectorized code in NumPy?
Reference answer
There are several benefits to using vectorized code in NumPy, including: Faster computation: Vectorized code is generally much faster than traditional loops for array operations. Cleaner code: Vectorized code is often more concise and easier to read than equivalent loop-based code. Fewer bugs: Vectorized code is less error-prone than equivalent loop-based code, as it avoids common mistakes, such as off-by-one and index out-of-bounds errors. Improved memory efficiency: Vectorized code is often more memory-efficient than equivalent loop-based code, as it avoids creating temporary variables and arrays.
107
Write a Python function to check if a given string is a palindrome.
Reference answer
def is_palindrome(s): return s == s[::-1] # Example usage: # print(is_palindrome("racecar")) # Output: True # print(is_palindrome("hello")) # Output: False
108
What is a heatmap, and how would you create one with Seaborn?
Reference answer
A heatmap is a type of plot that displays data as a grid of colored cells, with each cell representing a value in the data. To create a heatmap with Seaborn, you would first import the library, create a figure and axis object using the subplots() function, then use the heatmap() function to plot the data. For example: Loading...
109
Write a Python program to generate the Fibonacci series.
Reference answer
# Enter number of terms needednbsp;#0,1,1,2,3,5.... a=int(input("Enter the terms")) f=0;#first element of series s=1#second element of series if a=0: print("The requested series is",f) else: print(f,s,end=" ") for x in range(2,a): print(next,end=" ") f=s s=next Output: Enter the terms 5 0 1 1 2 3
110
How will you get the items that are not common to both the given series A and B?
Reference answer
We can achieve this by first performing the union of both series, then taking the intersection of both series. Then we follow the approach of getting items of union that are not there in the list of the intersection. The following code demonstrates this: import pandas as pd import numpy as np df1 = pd.Series([2, 4, 5, 8, 10]) df2 = pd.Series([8, 10, 13, 15, 17]) p_union = pd.Series(np.union1d(df1, df2)) # union of series p_intersect = pd.Series(np.intersect1d(df1, df2)) # intersection of series unique_elements = p_union[~p_union.isin(p_intersect)] print(unique_elements) """ Output: 0 2 1 4 2 5 5 13 6 15 7 17 dtype: int64 """
111
What will be the output of the following code? list = ['a', 'b', 'c', 'd', 'e'] print list[10:]
Reference answer
The output will be an empty list []. In Python, slicing a list beyond its length does not raise an error; it returns an empty list.
112
What is the difference between .py and .pyc files?
Reference answer
- .py files contain the source code of a program. Whereas, .pyc file contains the bytecode of your program. We get bytecode after compilation of .py file (source code). .pyc files are not created for all the files that you run. It is only created for the files that you import. - Before executing a python program python interpreter checks for the compiled files. If the file is present, the virtual machine executes it. If not found, it checks for .py file. If found, compiles it to .pyc file and then python virtual machine executes it. - Having .pyc file saves you the compilation time.
113
Write a Python code to check if a string is a palindrome
Reference answer
def is_palindrome(s): return s == s[::-1] print(is_palindrome("radar")) # True print(is_palindrome("hello")) # False
114
How Would You Programmatically Check the Python Version in Use?
Reference answer
The developer can check the Python version using the sys module. The code for this would be: import sys print(sys.version)
115
What is a DataFrame in Pandas?
Reference answer
A DataFrame is a two-dimensional, size-mutable, and heterogeneous tabular data structure with labeled axes (rows and columns). It is similar to a spreadsheet or SQL table.
116
Explain the difference between deep copy and shallow copy.
Reference answer
- Shallow Copy: Creates a new object but copies only references of nested objects. Changes in nested objects affect both copies. - Deep Copy: Recursively copies all objects, creating independent copies. Example: import copy original = [[1, 2], [3, 4]] shallow = copy.copy(original) deep = copy.deepcopy(original) shallow[0][0] = 99 # Affects original deep[0][0] = 88 # Does not affect original
117
30. What is a metaclass in Python?
Reference answer
A metaclass in Python is a class that defines how classes are created. Metaclass is a class of class. Metaclass defines how a class behaves. A metaclass determines how classes themselves behave, while a class determines how instances of the class behave. Every class in Python is an instance of a metaclass, and the default metaclass is the `type` class. You can customize class creation and modification by creating your own metaclass. This involves inheriting from the base `type` class and overriding its methods. One common use of metaclasses is to ensure certain attributes or methods exist in subclasses. They are powerful tools and should be used with caution, as they can add complexity to code.
118
What is the use of help() and dir() functions?
Reference answer
The help() function displays documentation and usage details for Python objects, such as modules, functions, or classes. The dir() function returns a list of attributes and methods of an object, aiding in exploration and debugging.
119
What are comprehensive approaches to ensuring code reliability through automated testing in Python?
Reference answer
Approaches include writing extensive unit, integration, and end-to-end tests, employing code coverage tools, automating test execution in CI/CD pipelines, practicing test-driven development, and using property-based testing libraries like Hypothesis.
120
Explain the difference between class methods and static methods. How does inheritance work in Python?
Reference answer
Class methods take 'cls' as the first parameter and can modify class state, while static methods do not take a special first parameter and behave like regular functions, belonging to the class for organization. Inheritance allows a subclass to inherit attributes and methods from a parent class, with method overriding and support for multiple inheritance via the MRO (Method Resolution Order).
121
Write a Python function to merge k-sorted linked lists.
Reference answer
Sample Answer: To merge k-sorted linked lists, you can use a min-heap to always extract the smallest element from each list. Here's a code to merge k-sorted linked lists: class ListNode: def __init__(self, value=0, next=None): self.value = value self.next = next def merge_k_lists(lists): import heapq min_heap = [] for l in lists: if l: heapq.heappush(min_heap, (l.value, l)) dummy = ListNode() current = dummy while min_heap: value, node = heapq.heappop(min_heap) current.next = node current = current.next if node.next: heapq.heappush(min_heap, (node.next.value, node.next)) return dummy.next
122
Is Python an interpreted language?
Reference answer
Yes, since it does not have machine-level code before runtime. Code uses an interpreter to be executed by the machine.
123
Explain the difference between append() and extend() methods in Python lists.
Reference answer
The append() method adds an element to the end of a list, while the extend() method adds the elements of an iterable (e.g., another list) to the end of the list. list1 = [1, 2, 3] list1.append(4) # list1 becomes [1, 2, 3, 4] list2 = [5, 6] list1.extend(list2) # list1 becomes [1, 2, 3, 4, 5, 6]
124
How to delete a file in Python?
Reference answer
To delete a file in Python, use the os.remove() function from the os module, passing the file path as an argument. Alternatively, the pathlib module's Path.unlink() method can be used for object-oriented file handling.
125
What are the best practices for Python code testing?
Reference answer
Best practices for testing Python code include: - Write tests early and often. Incorporating testing from the beginning helps catch issues early and facilitates a test-driven development approach. - Aim for thorough test coverage. Use tools to measure coverage, ensuring tests cover as much of the codebase as possible, including edge cases and failure paths. - Isolate tests from each other. Each test should run independently without relying on results or side-effects of another test to prevent cascading failures. - Use mocking and patching wisely. Mock external dependencies like databases or APIs to ensure tests are not reliant on external factors, but avoid over-mocking. - Implement different levels of testing: unit tests, integration tests, and end-to-end tests. - Keep tests fast and automated. Tests should run quickly to encourage frequent use, and automate execution as part of CI/CD. - Write meaningful test cases and names. Test names should be descriptive to aid in understanding and debugging. - Refactor tests as you refactor code to maintain clarity and efficiency. - Review tests with the same rigor as production code. - Document the testing strategy to help onboard new developers and keep the team aligned.
126
What are Python's descriptors?
Reference answer
Descriptors are objects that manage attribute access through methods like __get__, __set__, and __delete__. They are used in frameworks for property management, like Django models. Example: class Descriptor: def __get__(self, instance, owner): return "Accessed value" class MyClass: attr = Descriptor()
127
What is a Python decorator?
Reference answer
A Python decorator is a function that extends the behavior of another Python function without explicitly modifying it.
128
What is SVM?
Reference answer
SVM, or Support Vector Machine, is a supervised machine learning algorithm used for classification and regression tasks. It works by finding a hyperplane that best separates data points into different classes with maximum margin.
129
What is a generator in Python?
Reference answer
Generators in Python are like functions that can return more than once. This is called yielding. They are used to return an iterable collection of items. They are defined with def just like Python functions. def squares(): x = range(1, 4) # 1 to 4 for n in x: yield n**2 for y in squares(): print(y) # prints 1 4 9 16
130
Can You Explain What a Namespace is?
Reference answer
Namespace in Python refers to the naming system used in Python to ensure that every object receives a unique name. It is implemented through the Python dictionary. Some common namespace in python is: - Global namespace: It stores the names of the imported modules that are in use. It is formed when the module is added and is discarded once the script is complete. - Local namespace: It stores the local names of functions. It is invoked when a function is called and lasts with the function. - Built-in namespace: It contains built-in functions and exceptions.
131
Write a test case for an asynchronous function async fetch_data(api_url) that retrieves data from an API. Ensure the test properly waits for the function to complete and checks the returned result.
Reference answer
import asyncio import unittest async def fetch_data(api_url): # Asynchronous function to fetch data pass class TestAsyncFetchData(unittest.TestCase): def test_async_fetch_data(self): loop = asyncio.get_event_loop() response = loop.run_until_complete(fetch_data("http://example.com/api")) self.assertEqual(response, expected_response) if __name__ == '__main__': unittest.main() Explanation of solution: This solution involves testing an asynchronous function fetch_data. An event loop is obtained using asyncio.get_event_loop(). loop.run_until_complete() is used to run the asynchronous function within the test, ensuring the test waits for its completion. The result of the async function is then tested using assertEqual.
132
How do you count digits, letters, and spaces in a string?
Reference answer
Use generator expressions with isdigit(), isalpha(), and isspace(): s = "Hello 123" digits = sum(c.isdigit() for c in s) letters = sum(c.isalpha() for c in s) spaces = sum(c.isspace() for c in s) print(f"Digits: {digits}, Letters: {letters}, Spaces: {spaces}") # Output: Digits: 3, Letters: 5, Spaces: 1 Output: Digits: 3, Letters: 5, Spaces: 1
133
How do you shuffle a list in Python?
Reference answer
Consider the example shown below: from random import shuffle x = ['Keep', 'The', 'Blue', 'Flag', 'Flying', 'High'] shuffle(x) print(x) The output of the following code is as below. ['Flying', 'Keep', 'Blue', 'High', 'The', 'Flag']
134
Discuss best practices for handling missing values and outliers in Pandas datasets.
Reference answer
- Impute missing values with specific strategies, identify and handle outliers using statistical methods.
135
How do you handle datetime data in Pandas?
Reference answer
You can use the `.to_datetime()` function to convert strings or integers to datetime objects and then perform various datetime operations.
136
Write a Python function that takes a list of numbers and returns the sum of all elements in the list. For example, for the list [1, 2, 3, 4], the function should return 10. Do not use the built-in Python sum function.
Reference answer
def sum_of_list(numbers): total = 0 for number in numbers: total += number return total Explanation of solution: The function iterates over each element in the list numbers using a for loop. It initializes a variable total to 0 and adds each element of the list to this variable, accumulating the sum. Finally, it returns the total sum of the elements.
137
What is the use Range function in python ?
Reference answer
range() function in Python allows to create a sequence of numbers that can be used for iteration. It can be used to create a range of numbers with a specified start, stop, and step value. [ i.e. range( start, stop, steps) ] Code Ex – for i in range(10): print(i) #Output: 0 1 2 3 4 5 6 7 8 9 for j in range(0, 10, 2): print(j) #Output: 0 2 4 6 8
138
What is the purpose of the unittest library in Python?
Reference answer
unittest is a built-in Python library for writing and running unit tests. It helps ensure the correctness of your code by automating the testing process.
139
How do you create and use a virtual environment?
Reference answer
A virtual environment keeps project libraries separate from system Python, this avoids version conflicts, you create it using the venv module, then activate it before running or installing packages, this is very common in scripting and automation. python3 -m venv env source env/bin/activate # macOS/Linux env\Scripts\activate # Windows
140
Write a function to count the number of palindromic substrings in a given string. For instance, in the string "aba", there are three palindromic substrings: "a", "b", "aba".
Reference answer
def count_palindromic_substrings(s): count = 0 for i in range(len(s)): for j in range(i, len(s)): if s[i:j+1] == s[i:j+1][::-1]: count += 1 return count Explanation of solution: The function uses nested loops to generate all possible substrings of the input string. The outer loop fixes the starting point of the substring, and the inner loop varies the endpoint. For each substring generated (s[i:j+1]), the function checks if it is a palindrome (by comparing it to its reverse). The count is incremented each time a palindromic substring is found.
141
How would you create a bar plot with Seaborn?
Reference answer
To create a bar plot with Seaborn, you would first import the library, create a figure and axis object using the subplots() function, then use the barplot() function to plot the data. For example: Loading...
142
How are arguments passed by value or by reference in python?
Reference answer
- Pass by value: Copy of the actual object is passed. Changing the value of the copy of the object will not change the value of the original object. - Pass by reference: Reference to the actual object is passed. Changing the value of the new object will change the value of the original object. In Python, arguments are passed by reference, i.e., reference to the actual object is passed. def appendNumber(arr): arr.append(4) arr = [1, 2, 3] print(arr) #Output: => [1, 2, 3] appendNumber(arr) print(arr) #Output: => [1, 2, 3, 4]
143
What is the 'with' statement used for?
Reference answer
With statement makes exception handling easier: encapsulates cleanup and preparation, assists in file stream management, and makes code more readable.
144
How memory is managed in python programming language ?
Reference answer
In Python, memory management operates in the following manner: - Memory management in Python is handled by a private heap space. All Python objects and data structures are stored within this private heap, which remains inaccessible to programmers. The responsibility of managing this private heap lies with the Python interpreter. - The allocation of heap space for Python objects is handled by Python's memory manager. Although programmers do not have direct access to this process, Python's core API provides certain tools that can be utilized. - Python incorporates an internal garbage collector that is responsible for reclaiming unused memory. This ensures that memory becomes available within the heap space for future utilization.
145
Write a program to count the number of vowels in a given string.
Reference answer
Sample Answer: Vowels in the English language are 'a', 'e', 'i', 'o', and 'u'. You can iterate over the string and count how many of these vowels it contains. In the following example, the function 'count_vowels(s)' use a generator expression to iterate through each character in the input string 's', converting each character to lowercase to ensure the check is case-insensitive. The 'sum()' function then totals the number of vowels found. Here's the code: def count_vowels(s): return sum(1 for char in s if char.lower() in 'aeiou')
146
What is Python? What are the benefits of using Python
Reference answer
Python is a high-level, interpreted, general-purpose programming language. Being a general-purpose language, it can be used to build almost any type of application with the right tools/libraries. Additionally, python supports objects, modules, threads, exception-handling, and automatic memory management which help in modelling real-world problems and building applications to solve these problems. Benefits of using Python: - Python is a general-purpose programming language that has a simple, easy-to-learn syntax that emphasizes readability and therefore reduces the cost of program maintenance. Moreover, the language is capable of scripting, is completely open-source, and supports third-party packages encouraging modularity and code reuse. - Its high-level data structures, combined with dynamic typing and dynamic binding, attract a huge community of developers for Rapid Application Development and deployment.
147
How do you remove whitespace from a string in Python?
Reference answer
Python offers a strip function that is already built-in. It clears all the whitespace or trailing spaces automatically.
148
What are Python iterators?
Reference answer
Iterators are objects that contain some countable values. As the name suggests, a developer can iterate on each value. Python data collections: lists, tuples, sets, and dictionaries are examples of iterate objects.
149
What do you understand by NumPy?
Reference answer
NumPy is one of the most popular, easy-to-use, versatile, open-source, python-based, general-purpose package that is used for processing arrays. NumPy is short for NUMerical PYthon. This is very famous for its highly optimized tools that result in high performance and powerful N-Dimensional array processing feature that is designed explicitly to work on complex arrays. Due to its popularity and powerful performance and its flexibility to perform various operations like trigonometric operations, algebraic and statistical computations, it is most commonly used in performing scientific computations and various broadcasting functions. The following image shows the applications of NumPy:
150
How do you set a column as the index of a DataFrame in Pandas?
Reference answer
You can use the `.set_index()` method``, specifying the column name as an argument, to set a specific column as the index of a DataFrame.
151
Explain the differences between a shallow copy and a deep copy of an object in Python.
Reference answer
A shallow copy creates a new object with references to nested objects, while a deep copy creates a completely independent copy of the object and all its nested objects_._
152
How do you create a DataFrame in Pandas?
Reference answer
You can create a DataFrame using the pd.DataFrame() constructor, passing a dictionary, a list of dictionaries, or other data structures.
153
How do you handle logging in scripts (instead of print)?
Reference answer
Instead of using print, Python has a logging module that is better for real scripts, it lets you write messages with levels like info, warning, and error, you can also save logs to a file, this helps when scripts run in background or on servers, and it makes debugging easier because you know what happened and when. import logging logging.basicConfig(level=logging.INFO) logging.info("Script started") logging.error("Something went wrong")
154
What is the difference between Python 2 and Python 3?
Reference answer
Python 2 is an older version with ongoing support, while Python 3 is the latest version with many improvements and new features. It's recommended to use Python 3 for new projects.
155
What is the purpose of Python's __slots__?
Reference answer
__slots__ restricts the attributes of a class to predefined ones, saving memory by preventing the creation of __dict__. Example: class MyClass: __slots__ = ['x', 'y'] obj = MyClass() obj.x = 10 # Allowed obj.z = 20 # Raises AttributeError
156
How is a dictionary different from a list?
Reference answer
A list is an ordered collection of items accessed by their index, while a dictionary is an ordered collection of key-value pairs accessed using unique keys accessed using unique keys. Lists are ideal for sequential data, whereas dictionaries are better for associative data. For example, a list can store [10, 20, 30], whereas a dictionary can store {"a": 10, "b": 20, "c": 30}.
157
Describe the primary features of Python as a programming language.
Reference answer
Python is an interpreted, high-level, general-purpose language known for its simplicity, readability, and vast standard library. It supports multiple programming paradigms including procedural, object-oriented, and functional programming.
158
How does Python handle memory allocation and garbage collection?
Reference answer
Python manages memory automatically through the Python Memory Manager, which controls a private Heap containing all objects. Small objects (≤512 bytes) use a specialized allocator called obmalloc, which organizes memory into Arenas (256 KB), Pools (4 KB), and Blocks. Large objects bypass obmalloc and use standard C malloc(). Python uses Reference Counting as its primary garbage collection mechanism, where every object has an ob_refcnt field. When ref_count reaches 0, memory is immediately deallocated. For circular references, Python's gc module uses a Generational Garbage Collector with three generations (G0, G1, G2). New objects start in G0 and are promoted if they survive collection cycles. G0 is scanned most frequently following the heuristic that younger objects die young.
159
Explain the Global Interpreter Lock (GIL) in Python.
Reference answer
The Global Interpreter Lock (GIL) is a mechanism in CPython (the default Python interpreter) that allows only one thread to execute Python bytecode at a time. This can impact the performance of multithreaded Python programs, especially on multi-core systems.
160
17. How does Python support encapsulation?
Reference answer
Python supports encapsulation through the use of private and protected access modifiers and classes. Encapsulation is the bundling of data and methods that operate on that data within a single unit, known as a class. It restricts direct access to certain components, ensuring that unwanted modifications don't occur. You can denote a variable or method as private by prefixing it with an underscore In Python, such as `_my_variable `. Although this is merely a convention, it signals to the developer that it's for internal use only. You can use two underscores, like `__my_variable` , for a stronger indication of protection. This triggers name mangling, which makes it harder to access the variable from outside the class. Use classes to group relevant data and methods, ensuring a clean, logical structure. Combine this with private and protected members, and Python provides a solid foundation for encapsulation. This ensures data integrity and promotes the principles of object-oriented programming.
161
Explain list comprehensions in Python.
Reference answer
List comprehensions provide a concise way to create lists. For example, [x**2 for x in range(10)] creates a list of squares for numbers from 0 to 9.
162
Write a Python code to convert a string to an integer
Reference answer
str_num = "12345" int_num = int(str_num) print(int_num) # 12345
163
What is the difference between Django and Flask for web development?
Reference answer
Django is a full-stack framework packed with built-in tools like an Object-Relational Mapper (ORM), an admin panel, and a templating system. It's perfect for building complex applications that require features like database integration and user authentication. On the other hand, Flask is a lightweight microframework, relying on Jinja2 for templating and Werkzeug for WSGI utilities. Flask is often preferred for smaller projects, microservices, or setups where flexibility is more important than built-in functionality.
164
What are Iterators in Python?
Reference answer
In Python, iterators are used to iterate a group of elements, containers like a list. Iterators work on iterable objects such as lists, tuples and dictionaries. Python iterator implements __iter__() and the next() methods to iterate the stored elements. We generally use loops to iterate over the collections (list, tuple) in Python.
165
What is Python's Global Interpreter Lock (GIL)?
Reference answer
In Python's CPython implementation, the GIL is a mutex that prevents multiple threads from running Python bytecode at the same time. It ensures memory management thread safe. But this doesn't allow Python to make the most of multi core processors for CPU bound tasks. The workarounds include using multiprocessing or external libraries like NumPy for heavy computations.
166
How do you monitor and maintain the health of your automated test scripts?
Reference answer
- Answer: Discuss scheduling regular test runs, integrating tests with CI/CD pipelines, reporting results with tools like pytest-html, and analyzing trends for stability and identifying regressions.
167
What are Python modules? What are they used for?
Reference answer
Python modules are files that contain executable code. They help break large chunks of code into smaller parts, increasing readability and working efficiency. Here is the list of widely used Python modules: - sys - math - random - JSON - data time
168
What are magic methods in Python? List a few common ones.
Reference answer
Magic methods (dunder methods) are special methods with double underscores, allowing customization of object behaviour for built-in operations. Common examples: - init(self, ...) — Constructor - str(self) — String representation - add(self, other) — Addition operator - len(self) — Length
169
How can you reverse a list in Python?
Reference answer
import array as arr My_Array=arr.array('i',[1,2,3,4,5]) My_Array[::-1] Output: array(‘i', [5, 4, 3, 2, 1])
170
Could you provide an example of a project where you improved application responsiveness using asynchronous programming, and how did it impact user experience?
Reference answer
Certainly. In a web application, we used asyncio to parallelize I/O-bound operations, such as database queries and external API requests. This significantly reduced response times, resulting in a much-improved user experience with faster page loads.
171
Write a Python function to reverse the words in a sentence.
Reference answer
Solution: def reverse_words(input_string): # Split the string into words words = input_string.split() # Reverse the order of words reversed_words = words[::-1] # Join the reversed words back into a string reversed_string = " ".join(reversed_words) return reversed_string # Example usage input_string = "Hello World" reversed_string = reverse_words(input_string) print("Original string:", input_string) print("Reversed string:", reversed_string) Output: Original string: Hello World Reversed string: World Hello
172
How is Python used for data analysis and machine learning?
Reference answer
Python has become the language of choice for data analysis and machine learning due to its simplicity and vast ecosystem of data science libraries. The Pandas library is a cornerstone for data analysis, providing high-performance data structures and tools for importing data from various file formats and performing operations like cleaning, transformation, and aggregation. For numerical computations, NumPy is foundational, supporting large multi-dimensional arrays and matrices with a collection of mathematical functions for operations like Fourier transforms and random number simulations. Matplotlib and Seaborn provide plotting functions for creating static, interactive, and animated visualizations to understand patterns and make decisions. Machine learning tasks are streamlined with Scikit-learn, featuring algorithms for classification, regression, clustering, and dimensionality reduction, designed to interoperate with NumPy and Pandas. For advanced tasks, TensorFlow and PyTorch are go-to frameworks for building and training neural networks with automatic differentiation, supporting complex architectures for NLP and computer vision. Jupyter Notebooks offer an interactive coding environment for exploratory data analysis and rapid prototyping. To excel, master basic Python syntax, engage with the community, practice with real-world datasets, and stay updated with library developments.
173
Explain in detail about packages and libraries?
Reference answer
Packages and libraries are collections of code written in a specific programming language that provides additional functionality to programs. Packages are a collection of modules, while libraries are a collection of related packages. In Python, packages are usually stored in directories and are organized hierarchically, with subpackages and modules contained within them. A package can contain subpackages and modules, and each module can contain classes, functions, and variables. Libraries, on the other hand, are collections of packages and modules that are designed to perform specific tasks. For example, NumPy is a library for numerical computing in Python, while Pandas is a library for data analysis and manipulation. Libraries can be installed in Python using a package manager like pip, and they can be imported into a program using the import statement.
174
What is the ternary operator in Python?
Reference answer
The Ternary operator is the operator that is used to show the conditional statements. This consists of the true or false values with a statement that has to be evaluated for it. Syntax: The Ternary operator will be given as: [on_true] if [expression] else [on_false]x, y = 25, 50big = x if x < y else y Example: The expression gets evaluated like if x
175
What are decorators and where do you use them in production?
Reference answer
Decorators are used to add extra behavior to a function without changing its code. They are written using @ syntax.Common uses are logging, timing, auth checks, and caching.They wrap a function and run code before or after it. This keeps main logic clean.Very common in web frameworks like Flask and Django. def my_decorator(func): def wrapper(): print("Before function") func() print("After function") return wrapper @my_decorator def say_hi(): print("Hi") say_hi()
176
What is the difference between set and frozenset in Python?
Reference answer
Set and frozenset are two built-in collection data types in Python that are used to store a collection of unique elements. While set is mutable, meaning that we can add, remove, or change elements in a set, frozenset is immutable and cannot be modified after creation.
177
What is the use of help() and dir() functions?
Reference answer
help() function in Python is used to display the documentation of modules, classes, functions, keywords, etc. If no parameter is passed to the help() function, then an interactive help utility is launched on the console. dir() function tries to return a valid list of attributes and methods of the object it is called upon. It behaves differently with different objects, as it aims to produce the most relevant data, rather than the complete information. - For Modules/Library objects, it returns a list of all attributes, contained in that module. - For Class Objects, it returns a list of all valid attributes and base attributes. - With no arguments passed, it returns a list of attributes in the current scope.
178
What are unit tests in Python?
Reference answer
Unit Testing is the first level of software testing where the smallest testable parts of the software are tested. This is used to validate that each unit of the software performs as designed. The unit test framework is Python's xUnit style framework. The White Box Testing method is used for Unit testing.
179
Write a program to find the second largest number in a list.
Reference answer
Sample Answer: To find the second largest number, you can remove duplicates by converting the list to a set. Once you have a set of unique numbers, you can sort them in ascending order and retrieve the second-to-last element. Here's how you can implement the code: def second_largest(numbers): unique_numbers = list(set(numbers)) unique_numbers.sort() return unique_numbers[-2] if len(unique_numbers) >= 2 else None
180
What is async / await used for? (and when not to use it)
Reference answer
async and await are used to write non-blocking code, mainly for things like API calls, file operations, and network requests, they allow your program to do other work while waiting for slow operations, but they are not useful for heavy CPU work like data processing, they also need an event loop to run, which is why they are common in web servers and async frameworks. import asyncio async def say_hi(): await asyncio.sleep(1) print("Hi after 1 second") asyncio.run(say_hi())
181
How do you find the maximum and minimum values in a NumPy array?
Reference answer
You can find the maximum and minimum values in a NumPy array using the numpy.amax() and numpy.amin() functions, respectively. For example, numpy.amax(array) or numpy.amin(array).
182
What is the pivot() function used for in Pandas?
Reference answer
The `pivot()` function is used to reshape a DataFrame by converting columns into rows and rows into columns based on specified values.
183
Why Python does not de-allocate all the memory on exits?
Reference answer
Python does not de-allocate all the memory as soon as it exits, because some memory is reserved by C library and possible there could be some circular references exists. Hence, memory can not be deallocated immediately in Python.
184
59. What is the use of the Scikit-learn library in Python?
Reference answer
The use of the Scikit-learn library in Python is to implement machine learning models and statistical modeling. Scikit-learn provides tools for data analysis and modeling. Scikit-learn offers a range of supervised and unsupervised learning algorithms, making it one of the most versatile libraries for machine learning tasks. Scikit-learn supports numerous algorithms, From classification and regression to clustering and dimensionality reduction. Scikit-learn also comes with utilities for preprocessing data, fine-tuning model parameters, and evaluating model performance. Developers can easily switch between different algorithms with its consistent API design. Integration with other Python libraries, like NumPy and pandas, further enhances its capabilities. Your engineers should not be hiring. They should be coding. Help your team focus on what they were hired for. Flexiple will manage your entire hiring process and scale your tech team.
185
How would you convert a list to an array?
Reference answer
During programming, there will be instances when you will need to convert existing lists to arrays in order to perform certain operations on them (arrays enable mathematical operations to be performed on them in ways that lists do not). Here we'll be using numpy.array() . This function of the numpy library takes a list as an argument and returns an array that contains all the elements of the list. See the example below: import numpy as np my_list = [2,4,6,8,10] my_array = np.array(my_list) # printing my_array print my_array # printing the type of my_array print type(my_array) Output: [ 2 4 6 8 10]
186
How do you handle script exit codes properly?
Reference answer
Exit codes tell the system if your script succeeded or failed, zero means success and any non-zero means error, you can control this using sys.exit(), this is important in automation because other tools check exit codes to know what to do next. import sys if False: sys.exit(1) # error else: sys.exit(0) # success
187
What are the key features of Python that differentiate it from other programming languages?
Reference answer
Python is known for its clear and concise syntax, object-oriented nature, platform independence, extensive standard library, and easy integration with other languages.
188
What does the Python is operator do?
Reference answer
When the is operator is used in a Python expression, it evaluates to true if the variables on both sides point to the same object. ## z is true x=3 y=x z=x is y
189
Create a Python function that flattens a nested list.
Reference answer
def flatten(nested_list): flat_list = [] for item in nested_list: if isinstance(item, list): flat_list.extend(flatten(item)) else: flat_list.append(item) return flat_list print(flatten([1, [2, [3, 4], 5], 6])) # [1, 2, 3, 4, 5, 6]
190
Explain the difference between a generator and an iterator in Python.
Reference answer
An iterator in Python serves as a holder for objects so that they can be iterated over; a generator facilitates the creation of a custom iterator. Apart from the obvious syntactic differences, the following are some noteworthy differences: | Generator | Iterator | |---|---| | Implemented using a function. | Implemented using a class. | Uses the yield keyword. | Does not use the yield keyword. | | Usage results in a concise code. | Usage results in a relatively less concise code. | All the local variables before the yield statements are stored. | No local variables are used. | Implementation of Iterator # Function to generate all the non-negative numbers # up to the given non-negative number. class UpTo: # giving the parameter a default value of 0 def __init__(self, max = 0): self.max = max def __iter__(self): self.n = 0 return self def __next__(self): # The next method will throw an # exception when the termination condition is reached. if self.n > self.max: raise StopIteration else: result = self.n self.n += 1 return result for number in UpTo(5): print(number) Output: 0 1 2 3 4 5 Implementation of Generator # Function to generate all the non-negative numbers # up to the given non-negative number def upto(n): for i in range(n+1): # The yield statement is what makes a function # a generator yield i for number in upto(5): print(number) Output: 0 1 2 3 4 5
191
What are Python packages?
Reference answer
Python packages are namespaces containing multiple modules.
192
How do you read a CSV file into a DataFrame using Pandas?
Reference answer
You can use the `pd.read_csv()` function``, providing the path to the CSV file as an argument. For example``: `` df = pd.read_csv('data.csv') ```.`
193
Explain how to handle exceptions in Python.
Reference answer
Use try, except, else, and finally blocks to handle exceptions gracefully. Ensure specific exceptions are caught to handle different error conditions.
194
What is the difference between a list and a tuple?
Reference answer
- List: - Mutable (can be modified). - Syntax: my_list = [1, 2, 3]. - Suitable for collections that might need changes. - Tuple: - Immutable (cannot be modified after creation). - Syntax: my_tuple = (1, 2, 3). - Used for fixed collections of items.
195
How can you iterate over the items of a dictionary in Python?
Reference answer
You can iterate over dictionary items using a `for` loop, iterating over keys, values, or both using the `items()` method.
196
Explain the purpose of the logging module in Python and how it can be configured for different logging levels and destinations.
Reference answer
The `logging` module allows you to log messages with different levels (e.g., INFO``, DEBUG``) to various outputs (e.g., console``, file) with flexible configurations.
197
Explain the purpose and usage of virtual environments in Python?
Reference answer
Virtual environments in Python allow developers to create isolated environments for their projects. This ensures that project dependencies do not interfere with each other, making it easier to manage dependencies and maintain project stability.
198
What is a KeyError in Python, and how can you handle it?
Reference answer
A KeyError in Python occurs when you try to access a key that doesn't exist in a dictionary. This error is raised because Python expects every key you look up to be present in the dictionary, and when it isn't, it throws a KeyError. For example, if you have a dictionary of student scores and try to access a student who isn't in the dictionary, you'll get a KeyError. To handle this error, you have a few options: - Use the .get() method: This method returns None (or a specified default value) instead of throwing an error if the key isn't found. - Use a try-except block: Wrapping your code in try-except allows you to catch the KeyError and handle it gracefully. - Check for the key with in: You can check if a key exists in the dictionary using if key in dictionary before trying to access it.
199
What is a scope in Python?
Reference answer
A scope is a block of code in which an object is relevant. Examples of scopes in Python are local scope, module-level scope, outermost scope, and global scope.
200
How do you handle circular imports in Python?
Reference answer
Circular imports occur when two modules depend on each other. Solutions include restructuring code to reduce interdependencies or using dynamic imports within functions.