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

Best Python Developer Interview Questions to Practice | 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
27. What are Python namespaces, and what is their purpose?
Reference answer
Python namespaces are a collection of currently defined symbolic names along with information about the object that each name references. Python namespaces are containers that hold a collection of identifiers, ensuring they remain distinct and organized. Their primary purpose is to differentiate between various identifiers, ensuring there are no naming conflicts in the program. A namespace maps names to objects. For example, A variable is added to the namespace with its associated value, when defined. Namespaces exist in different scopes, such as local, global, and built-in. A function, for example, has its local namespace where its variables live, while the main program has a global namespace. Namespaces provide a clear structure, enabling developers to use variable names without worrying about naming clashes, especially in large projects with multiple modules and packages.
2
What are the differences between the three popular libraries: Django, Flask, and Pyramid?
Reference answer
- Flask is a relatively straightforward, ready-to-use framework used for building smaller applications. - Pyramid is a larger-scale framework with tools for database management, templating, and many others. Pyramid is configurable. - Django can also be used to develop large applications. It relies on the model-view-template architecture.
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
How is memory management done in Python?
Reference answer
Python uses its private heap space to manage the memory. Basically, all the objects and data structures are stored in the private heap space. Even the programmer can not access this private space as the interpreter takes care of this space. Python also has an inbuilt garbage collector, which recycles all the unused memory and frees the memory and makes it available to the heap space. Python manages memory automatically using a private heap, where all objects and data structures are stored. Python interpreter handles memory allocation and deallocation and an inbuilt garbage collector reclaims memory occupied by objects that are no longer in use. - All objects and data structures are stored in a private heap. - The Python interpreter manages memory allocation automatically. - Programmers do not access the private heap directly. - Python uses garbage collection to free unused memory.
4
How do you handle errors and exceptions in Python?
Reference answer
- try and except blocks handle runtime errors. - Example: try: # code that may raise an exception except SomeException as e: # handle the exception
5
What is broadcasting in NumPy arrays?
Reference answer
Broadcasting is a mechanism in NumPy arrays that allows for arithmetic operations between arrays with different shapes or sizes. NumPy broadcasts the smaller array to the shape of the larger array, allowing for element-wise operations.
6
37. How to find the intersection of two lists in Python?
Reference answer
Intersection of two lists means you need to take all those elements which are common to both of the lists. The intersection of two lists in Python can be found using set operations. Convert both lists to sets. Then, use the `&` operator or the `intersection()` method of the set to find common elements. After finding the intersection as a set, you can convert it back to a list, if required. Consider lists `list1` and `list2` . The intersection can be derived using `set(list1) & set(list2)` . This method is efficient, but remember that sets do not maintain order and duplicate values are discarded. Make sure these characteristics align with your requirements before employing this method.
7
Write a Python function to flatten a nested list.
Reference answer
Sample Answer: To flatten a nested list, which is a list that may contain other lists as its elements, you can use a recursive approach. This method involves iterating through each item in the list and checking if it is itself a list. If it is, you recursively flatten that sublist; if it's not, you simply add it to the flattened list. Here is an example of how to write a Python function to flatten a nested list: 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
8
Write a Python code to check if a number is even or odd
Reference answer
def is_even(num): return num % 2 == 0 print(is_even(4)) # True print(is_even(5)) # False
9
How do you handle edge cases and unexpected inputs in your programs?
Reference answer
By writing comprehensive test cases, using assertions, and implementing input validation checks.
10
What are the differences between lists and tuples?
Reference answer
Lists are mutable, meaning their elements can be changed after creation, while tuples are immutable and cannot be modified. Lists use square brackets [] and tuples use parentheses (). Tuples are generally faster and used for fixed data.
11
How Do You Track Versions of Your Code?
Reference answer
The developer is likely to mention Git, GitHub, or Gitlab where you can see code at different stages and collaborate with teams to track different versions. However, they may also use other code repositories like Apache Subversion, CVS, or Bitbucket. It is one of the Python core interview questions with an easy answer but it is more important to understand how they actually work with versions: whether they actually care about different versions and organize them properly.
12
Pretend I'm not a tech person. Can you explain [Python concept] in simple terms?
Reference answer
This might be the toughest question you face during your interview – most Python Developers are adept at explaining complex Python concepts, but not in the straightforward way necessary to teach a layperson about concepts and functions in Python like multiple inheritances, string representation, xrange, and range, or import array. Try use simple analogies and stay away from technical jargon and concepts. Developers will often have to work with diverse teams of product managers, marketers, designers, and other roles, so the ability to communicate complex technical ideas is important for many companies.
13
How do you use a function to find all prime numbers within a given range in Python?
Reference answer
An array of all prime numbers within a starting and ending value can be obtained by defining a function named find_primes. This function utilizes the is_prime helper to check each candidate number. def is_prime(num): if num <= 1: return False for i in range(2, int(num ** 0.5) + 1): if num % i == 0: return False return True def find_primes(start, end): primes = [] for num in range(start, end + 1): if is_prime(num): primes.append(num) return primes print(find_primes(1, 10)) # Output: [2, 3, 5, 7]
14
How do you calculate basic statistics (mean, median, etc.) for a DataFrame in Pandas?
Reference answer
You can use methods like `.mean()` ```,` .median() ,` `` `.sum()` , and``.std()``to calculate basic statistics for columns in a DataFrame.`
15
What is the difference between a line plot and a scatter plot?
Reference answer
A line plot displays data as a series of connected points, with each point representing a value in the data. A scatter plot is a type of plot that displays data as a set of individual points, with each point representing a value in the data. Line plots are typically used to show trends or patterns in the data over time or other continuous variables. Scatter plots are typically used to show the relationship between two variables.
16
54. What are Flask and its uses?
Reference answer
Flask is a lightweight web framework written in Python. It lets you develop web applications easily. Flask provides essential tools to build web applications without imposing a specific project structure. Developers have the flexibility to design their application's architecture, which is especially useful for simple projects or prototypes. Flask's primary use is to create web applications and RESTful services. Its simplicity and scalability make it a preferred choice for startups and individual developers. Developers easily integrate with databases, set up authentication, and add other functionalities using extensions with Flask. Flask applications are easy to deploy, making them live on the web becomes seamless.
17
81. How can you develop a web application using Python?
Reference answer
Develop a web application using Python with the help of Flask and Django. Django provides an admin panel, an ORM, and many built-in features, making it easier to build robust web applications. It follows the Model-View-Controller (MVC) pattern, ensuring a separation of concerns in application design. Flask is another option. Flask is a lightweight micro web framework that gives more flexibility in terms of structure. Flask allows for rapid development and is a great choice for smaller projects or microservices. Integrating Flask with extensions like Flask-SQLAlchemy or Flask-RESTful provides additional functionality. Choose Django for a comprehensive solution with many built-in features. Opt for Flask if you want more control over the components and architecture of your application.
18
What is type conversion in Python?
Reference answer
It is used for converting one data type into the other, for example, characters into an integer - ord(0), any data type to list type - list(), integer into a string - str(), etc.
19
How do you use a for loop versus a while loop in Python?
Reference answer
A for loop is ideal for iterating through a known range, while a while loop works better for conditions that change dynamically, like user input. Since Python lacks a do-while loop, you'll need to structure your code to handle similar situations.
20
Explain the concept of object-oriented programming (OOP) in Python.
Reference answer
- OOP focuses on building objects with attributes and methods. - Classes define object blueprints, and instances define specific objects.
21
First Non-Repeating Character: How do you find the first unique character in a string?
Reference answer
You first count how many times each character appears using a dictionary, then loop again through the string and return the first character whose count is one, if none exist return -1. def first_unique(s): count = {} for ch in s: count[ch] = count.get(ch, 0) + 1 for i, ch in enumerate(s): if count[ch] == 1: return i return -1 print(first_unique("leetcode")) # 0 print(first_unique("aabb")) # -1
22
Can You Explain Monkey Patching in Python?
Reference answer
Monkey patching refers to the dynamic editing of a class or module during run-time, which changes the code behavior.
23
What is the pass statement in Python, and when is it used?
Reference answer
The `pass` statement is a placeholder that does nothing. It is often used as a placeholder for code that will be implemented later.
24
Describe methods for dealing with frames and nested elements in web pages.
Reference answer
- Use switch_to.frame() to switch context to frames, then locate and interact with elements within. - Consider using relative locators that traverse through the element hierarchy.
25
What tools do you use for linting, debugging and profiling?
Reference answer
For linting, tools like Flake8, Pylint, and Black are commonly used. For debugging, Python's built-in pdb, as well as IDEs like PyCharm and VSCode debuggers, are popular. For profiling, cProfile and line_profiler are typical choices.
26
How do you remove elements from a list in Python?
Reference answer
You can remove elements from a list in Python using the remove() method to remove a specific value or the pop() method to remove an element at a specific index. Additionally, you can use slicing to remove multiple elements from a list.
27
Write a custom loss function in TensorFlow and demonstrate how to use it in training a model. Explain in what scenarios custom loss functions are necessary and how they are integrated into the training process.
Reference answer
import tensorflow as tf # Custom loss function def custom_loss_function(y_true, y_pred): return tf.reduce_mean(tf.square(y_true - y_pred)) # Example model (could be any model) model = tf.keras.models.Sequential([ tf.keras.layers.Dense(10, activation='relu', input_shape=(input_shape,)), tf.keras.layers.Dense(1) ]) # Compile the model with the custom loss function model.compile(optimizer='adam', loss=custom_loss_function) # Train the model # model.fit(X_train, y_train, epochs=10) Explanation of solution: A custom loss function is defined, which calculates the mean squared error between the true and predicted values. An example neural network model is defined using the Sequential API. The model is compiled, specifying the custom loss function in the loss parameter. This approach allows for flexibility in model training, particularly in scenarios where standard loss functions are inadequate or need customization.
28
What are metaclasses and when would you avoid them?
Reference answer
Metaclasses control how classes themselves are created, just like classes create objects, metaclasses create classes, they are mostly used in frameworks, ORMs, or when you want to automatically change or register classes, but they make code very hard to read and debug, so in normal projects they are avoided unless there is a very strong reason to use them. class MyMeta(type): def __new__(cls, name, bases, dct): print("Creating class:", name) return super().__new__(cls, name, bases, dct) class Test(metaclass=MyMeta): Pass
29
What are the key differences between Python's built-in data structures: lists, tuples, sets, and dictionaries?
Reference answer
Lists: These are mutable and ordered, making them perfect for general collections or datasets that might change in size. Tuples: Since they're immutable, tuples are ideal for fixed data like coordinates or RGB color values. Sets: Great for fast membership checks and removing duplicates. Dictionaries: Excellent for fast key-value lookups, often operating in constant time.
30
Explain the difference between range() and xrange()
Reference answer
For the most part, xrange and range are the exact same in terms of functionality. They both provide a way to generate a list of integers for you to use. The only difference is that range returns a Python list object and xrange returns an xrange object. This means that xrange doesn't actually generate a static list at run-time like range does. It creates the values as you need them with a special technique called yielding. This technique is used with a type of object known as generators.
31
How do you generate a list of IP addresses within a given range in Python?
Reference answer
You can use the ipaddress.ip_address and ipaddress.ip_network functions from the ipaddress module in Python to generate a list of IP addresses within a given range.
32
What are ODBC modules in Python?
Reference answer
The Microsoft Open Database Connectivity is an interface for the C programming language. It is the standard for all APIs using database C. If you use a Python ODBC interface with the standard ODBC drivers that ship with most databases, you can likely connect your Python application with most databases in the market. The different Python ODBC modules are pyodbc, PythonWin ODBC, and MxODBC.
33
89. How can you deploy a Python web application?
Reference answer
You can deploy a Python web application using various methods. Using web servers like Apache with mod_wsgi or Gunicorn behind a reverse proxy like Nginx. This setup ensures your application is scalable and can handle multiple requests simultaneously. Deployment tools such as Docker can encapsulate your application and its dependencies into containers. These containers are platform-independent and ensure a consistent environment across development, testing, and production. Deploying with cloud platforms like AWS, Google Cloud, or Azure offers scalable infrastructure to host your Python web application. Choose a deployment method based on the scale and complexity of your project. Utilize tools and platforms that align with your project's requirements to ensure smooth and efficient deployment. 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.
34
Define pandas dataframe.
Reference answer
A dataframe is a 2D mutable and tabular structure for representing data labelled with axes - rows and columns. The syntax for creating dataframe: import pandas as pd dataframe = pd.DataFrame( data, index, columns, dtype) where: - data - Represents various forms like series, map, ndarray, lists, dict etc. - index - Optional argument that represents an index to row labels. - columns - Optional argument for column labels. - Dtype - the data type of each column. Again optional.
35
What are Python modules?
Reference answer
You can consider a Python module as a code library. A module is a collection of Python classes, functions, and variables. Modules are usually separated from each other when they supply different functionality.
36
What is the importance of the with statement in Python?
Reference answer
The with statement is used to encapsulate an execution within a block. The with statement is used in conjunction with methods being supplied by a context manager (which are almost always closing/opening files) and guarantees that there is no resource leak, even if exceptions are raised in the blocks. Example: # Reading the contents of a file with open('file.txt', 'r') as file: data = file.read() print(data)
37
What is the purpose of the else block in a try statement in Python?
Reference answer
The else block in a try statement in Python is executed if no exception is raised in the try block. It is typically used to perform additional operations that depend on the success of the try block.
38
What is Walrus Operator?
Reference answer
- Walrus Operator allows you to assign a value to a variable within an expression. This can be useful when you need to use a value multiple times in a loop, but don't want to repeat the calculation. - Walrus Operator is represented by the `:=` syntax and can be used in a variety of contexts including while loops and if statements. Note: Python versions before 3.8 doesn't support Walrus Operator. numbers = [1, 2, 3, 4, 5] while (n := len(numbers)) > 0: print(numbers.pop()) Output 5 4 3 2 1
39
What are descriptors in Python (in simple terms)?
Reference answer
Descriptors are a way to control how class attributes are read, written, or deleted, they work using special methods like __get__, __set__, and __delete__, and they are actually used behind features like @property, they help add rules like validation or logging when someone accesses a value, most developers don't write descriptors directly but use them through properties. class Age: def __get__(self, obj, objtype): return obj._age def __set__(self, obj, value): if value < 0: raise ValueError("Age cannot be negative") obj._age = value class Person: age = Age() p = Person() p.age = 25 print(p.age)
40
How to read a CSV file into NumPy?
Reference answer
To read a csv file, we can use the numpy.loadtxt() function. Syntax: numpy.loadtxt(fname, dtype=, comments='#', delimiter=None, converters=None, skiprows=0, usecols=None, unpack=False, ndmin=0, encoding='bytes', max_rows=None, *, quotechar=None, like=None) Example: import numpy as np # using loadtxt() arr = np.loadtxt("sample_data.csv", delimiter=",", dtype=str) display(arr)
41
What are the predictions for Python in the next decade?
Reference answer
Python's versatility and simplicity will continue to fuel its growth, with predictions indicating its use in various domains will only increase in the next decade. As machine learning, artificial intelligence, and data analysis continue to dominate the tech landscape, Python's role in these fields is expected to strengthen. Expect Python to solidify its position in the emerging fields of data science and machine learning. Its extensive libraries and frameworks, such as TensorFlow, PyTorch, and SciPy, make it a go-to language for professionals in these areas. The language's readability and efficiency lend itself well to the rapid prototyping and iterative nature of AI research and development. The Internet of Things (IoT) is another area where Python could see significant growth. As more devices become connected and smart, Python's ability to handle and process data efficiently will make it a preferred choice for developers working on IoT projects. Python's ease of learning and its vibrant community support contribute to its widespread adoption among beginners and educators. It is likely to remain a primary language taught in educational institutions, fostering a new generation of Python developers. Web development with Python will evolve further, as frameworks like Django and Flask are continually improved. They offer robust features that enable the creation of both simple and complex web applications. Cybersecurity is a field ripe for Python's application, with the language's ability to automate tasks and analyze data being crucial for security analytics and threat detection systems. The open-source nature of Python ensures constant evolution, with contributions from around the globe. This collaborative approach to development means Python is poised to adapt quickly to new programming paradigms and technologies. Finally, Python's role in scientific computing and academic research is expected to grow. Its capacity for handling large datasets and performing complex calculations with ease makes it ideal for scientific applications.
42
How can you create and use a Module in Python?
Reference answer
To create a module just save the code you want in a file with the file extension .py: def greeting(name): print("Hello, " + name) Now we can use the module we just created, by using the import statement: import mymodule mymodule.greeting("Jonathan")
43
What are .py and .pyc files ?
Reference answer
.py files: - These files contain Python source code written in plain text. - They are human-readable and editable using a text editor or integrated development environment (IDE). - Python source code is typically saved with the .py extension. .pyc files: - These files are compiled bytecode files generated by the Python interpreter. - They are not human-readable and cannot be edited directly. - The Python interpreter compiles the .py source code into bytecode and saves it as a .pyc file for efficient execution in subsequent runs. - The .pyc files speed up the loading and execution of Python programs since the interpreter can directly execute the bytecode without the need for recompilation.
44
How can you represent a graph in Python?
Reference answer
A graph can be represented in Python using an adjacency list or an adjacency matrix.
45
What are vectorized operations, and why are they important?
Reference answer
Vectorized operations allow you to operate on entire arrays without explicit loops, improving performance (especially with NumPy). Example: import numpy as np a = np.array([1, 2, 3]) b = np.array([4, 5, 6]) # Element-wise addition print(a + b) # [5 7 9]
46
What is pass in Python?
Reference answer
- The pass statement is a placeholder that does nothing. - It is used when a statement is syntactically required but no code needs to run. - Commonly used when defining empty functions, classes or loops during development. def fun(): pass # Placeholder, no functionality yet # Call the function fun() Output Here, fun() does nothing, but the code stays syntactically correct.
47
How do you work with files in Python?
Reference answer
You can open, read, write, and close files using Python's built-in open() function. Make sure to use a with statement for proper file handling.
48
How does indentation work in Python?
Reference answer
Indentation (spaces or tabs) determines code blocks. If the indentation is incorrect, then there will be a syntax error.
49
What is the difference between multiprocessing and threading in python?
Reference answer
Multiprocessing and threading are both ways to achieve parallel computing in Python, but multiprocessing uses multiple processes to execute tasks, while threading uses multiple threads within a single process.
50
Write a Python program to check if a number is even or odd.
Reference answer
Sample Answer: Here is a sample of how to write a Python program to check if a number is even or odd: num = int(input("Enter a number: ")) if num % 2 == 0: print("Even") else: print("Odd")
51
What are the advantages of NumPy over regular Python lists?
Reference answer
There are several advantages of NumPy over regular Python lists, such as: - Memory: NumPy arrays are more memory-efficient than Python lists because they store elements of the same type in contiguous blocks. (Exact memory use depends on element type and system, but you can check with sys.getsizeof or array.nbytes.) - Speed: NumPy uses optimized C implementations, so operations on large arrays are much faster than with lists. - Versatility: NumPy supports vectorized operations (e.g., addition, multiplication) and provides many built-in mathematical functions that Python lists don't support.
52
What are Python's loops?
Reference answer
Python provides two main types of loops: - for loop: Iterates over a sequence. - while loop: Runs as long as a condition is true. Example: # For loop for i in range(3): print(i) # While loop x = 0 while x < 3: print(x) x += 1
53
Write a Python test case using the unittest framework to test a function add(a, b) that returns the sum of two numbers. Include both a passing and a failing test.
Reference answer
import unittest def add(a, b): return a + b class TestAddFunction(unittest.TestCase): def test_addition(self): self.assertEqual(add(1, 2), 3) def test_failed_addition(self): self.assertNotEqual(add(1, 2), 4) if __name__ == '__main__': unittest.main() Explanation of solution: The test class TestAddFunction extends unittest.TestCase. Two test methods are defined: test_addition (a passing test) and test_failed_addition (a failing test), using assertEqual and assertNotEqual to verify the function's output.
54
What is a list in Python and how do you use it?
Reference answer
An organized, editable collection of items is called a list. You can change, add, or remove anything. Example: my_list = [1, 2, 3] my_list.append(4) print(my_list) # [1, 2, 3, 4]
55
How can you check the memory usage of a Python object?
Reference answer
Python provides the sys.getsizeof() function in the sys module to check the memory usage of an object. It returns the size of the object in bytes. Keep in mind that this function only provides an estimate of the memory usage and may not include memory used by referenced objects.
56
What is a Negative Index in Python? Give an Example.
Reference answer
Negative indexing allows us to access elements from the end of a sequence by using negative numbers as their indices. Last element has an index of -1 Second last has an index of -2 Third last has an index of -3 and so on.
57
What is a docstring in Python?
Reference answer
A Python docstring is the first comment in the code object. The docstring for the code object is available on that code object's __doc__ attribute and through the help function. def the_function(): """The is a function docstring"""
58
Explain positive and negative indexing in Python.
Reference answer
The sequences in Python are indexed and it consists of the positive as well as negative numbers. The numbers that are positive uses ‘0' that is uses as first index and ‘1' as the second index and the process goes on like that. The index for the negative number starts from ‘-1' that represents the last index in the sequence and ‘-2' as the penultimate index and the sequence carries forward like the positive number. The negative index is used to remove any new-line spaces from the string and allow the string to except the last character that is given as S[:-1]. The negative index is also used to show the index to represent the string in correct order.
59
What are key PEP 8 style guide rules for writing clean Python code?
Reference answer
Use 4-space indents. Name variables and functions with lowercase_with_underscores. Capitalize class names with CapitalizedWords. Keep line lengths under 79 characters for code and 72 for comments or docstrings. Constants should always be written in UPPERCASE_WITH_UNDERSCORES.
60
Can you remove duplicates from a sorted array?
Reference answer
Given an integer sorted array in increasing order, remove duplicates so each unique element appears only once. Because Python lists don't change length in-place for this problem, place the results in the first k positions of the same array and return k (the new length). Only the first k elements are valid after the call; elements beyond k are stale. Image from LeetCode Example 1: input array is [1,1,2,2], the function should return 2. Example 2: input array is [1,1,2,3,3], the function should return 3. Solution: - Run a loop from index 1 to the end. Compare the current element with the previous unique element; when different, write it at insertIndex and increment insertIndex. Return insertIndex. - Return insertIndex as it is the k. This question is relatively straightforward once you know how. If you put more time into understanding the statement, you can easily come up with a solution. def removeDuplicates(array): size = len(array) if size == 0: return 0 insertIndex = 1 for i in range(1, size): if array[i - 1] != array[i]: array[insertIndex] = array[i] insertIndex += 1 return insertIndex array_1 = [1, 2, 2, 3, 3, 4] k1 = removeDuplicates(array_1) # 4; array_1[:k1] -> [1, 2, 3, 4] array_2 = [1, 1, 3, 4, 5, 6, 6] k2 = removeDuplicates(array_2) # 5; array_2[:k2] -> [1, 3, 4, 5, 6]
61
What are Python's data types?
Reference answer
Python provides various data types for different purposes: - Numeric: int, float, complex. - Text: str. - Sequence: list, tuple, range. - Set Types: set, frozenset. - Mapping: dict. - Boolean: bool.
62
77. How to optimize database queries in Python?
Reference answer
To optimize database queries in Python, use the right database, indexes, and efficient queries. Use a database library to write more maintainable code. Database calls are a bottleneck, especially when dealing with large datasets or complex operations. Developers can create efficient queries, by using Python's ORM tools like SQLAlchemy or Django's ORM. Select only the necessary columns, not the entire table. Fetch data using pagination rather than retrieving all records. Join operations should be used judiciously, and always have indexes on frequently searched or sorted columns. Avoid using Python loops to filter or process data; instead, leverage the database's capabilities. Regularly profile and monitor queries. Tools like Django Debug Toolbar or SQLalchemy's built-in profiler help spot inefficiencies. Do thorough testing with realistic data, and always consider caching results, if the data doesn't change frequently.
63
What is MRO (Method Resolution Order) in Python?
Reference answer
MRO means the order in which Python searches for a method when a class has more than one parent, and this becomes important in multiple inheritance so Python knows exactly which method to call, it follows a fixed rule called C3 linearization to decide this order, so there is no confusion or conflict, you can check this order using ClassName.mro(), and it simply shows the path Python will follow while looking for a method in parent classes. class A: def show(self): print("A") class B(A): pass class C(A): pass class D(B, C): pass print(D.mro())
64
How do you find the longest common prefix in a list of strings?
Reference answer
Sample Answer: The longest common prefix is the longest sequence of characters shared by all strings. You can find it by iteratively comparing each string with the prefix. For example: def longest_common_prefix(strs): if not strs: return "" prefix = strs[0] for s in strs[1:]: while not s.startswith(prefix): prefix = prefix[:-1] return prefix
65
Do you remember a programming project decision you made that was a failure? Why do you think it was a mistake? What did you learn from the experience?
Reference answer
The focus of your answer here shouldn't be on the project you were working on or the bad decision you made, but instead, you should detail how you determined that the decision you made wasn't the right one, how you corrected course after realizing your mistake, and how this lesson changed the way you approached future projects. By this point in the interview, you should have already had opportunities to showcase your skill and knowledge as a Python programmer. This question is more about showing your ability as a critical thinker and someone who is capable of both acknowledging and learning from your errors.
66
How is Python compatible with other programming languages?
Reference answer
Python's ability to integrate with other programming languages is a valuable feature. Key integrations include: - Interoperability with C/C++: Python can directly call C/C++ functions using libraries like ctypes, Cython, and SWIG, allowing performance-critical code in C/C++ while Python handles higher-level operations. - Java Integration: Jython is an implementation of Python that runs on the Java platform, allowing seamless interaction with Java code and libraries. - .NET Integration: IronPython allows Python code to interact with .NET objects and services. - Interfacing with JavaScript: Tools like Pyodide bring Python to the web using WebAssembly, allowing Python code to run in the browser alongside JavaScript. - Communication with R: Python can communicate with R via libraries like rpy2 for using R's statistical capabilities within Python programs. - Interacting with MATLAB: Python can interface with MATLAB using the MATLAB Engine API for Python. - Scripting in PHP: It is possible to execute Python scripts from PHP and vice versa through system calls or running a Python server in the background. Developers often use APIs, foreign function interfaces, and specific libraries for cross-language interaction, demonstrating Python's role as a 'glue' language.
67
What is the use of Floor Division (//) in python?
Reference answer
Result = 10 // 3 print(Result) Output: 3
68
Could you elaborate on the security measures you implemented in the project, especially in terms of protecting against common web vulnerabilities?
Reference answer
Security was a top priority. We used Django's built-in security features like CSRF protection, SQL injection prevention, and input validation. Additionally, we conducted regular security audits and kept dependencies up-to-date.
69
Write a Python function to calculate the average of numbers in a list.
Reference answer
Solution: def find_average(numbers): if not numbers: # If the list is empty return None # Return None since there are no numbers to average total = sum(numbers) # Calculate the sum of numbers in the list average = total / len(numbers) # Calculate the average return average # Example usage number_list = [10, 20, 30, 40, 50] average = find_average(number_list) if average is not None: print("Average of numbers in the list:", average) else: print("The list is empty.") Output: Average of numbers in the list: 30.0
70
Write a Python function to solve the N-Queens problem.
Reference answer
Sample Answer: The N-Queens problem involves placing N queens on an N×N chessboard such that no two queens attack each other. This can be solved using backtracking. Here is an example of how to write a Python function to solve the N-Queens Problem: def solve_n_queens(n): def backtrack(row, cols, diagonals1, diagonals2): if row == n: result.append(board[:]) return for col in range(n): if col in cols or (row - col) in diagonals1 or (row + col) in diagonals2: continue board[row] = col cols.add(col) diagonals1.add(row - col) diagonals2.add(row + col) backtrack(row + 1, cols, diagonals1, diagonals2) cols.remove(col) diagonals1.remove(row - col) diagonals2.remove(row + col) result = [] board = [-1] * n backtrack(0, set(), set(), set()) return result
71
How do you solve a real-world problem using Python (problem-solving scenario)?
Reference answer
Determine the specifications, decompose the problem, select appropriate libraries, and combine multiple concepts (data processing, calls to APIs, error handling). Example: Fetching weather data from an API, processing it, and storing results in a CSV file.
72
What is the purpose of the if __name__ == "__main__": block in a Python script?
Reference answer
The if __name__ == "__main__": block is used to check whether a Python script is being run as the main program or imported as a module. Code within this block will only execute if the script is run directly.
73
What does "duck typing" mean in real projects?
Reference answer
Duck typing means Python doesn't care about object type, only behavior. If it looks like a duck and acts like a duck, treat it as a duck. So, if an object has the needed methods, Python will use it.This makes code flexible and easy to extend.You don't need strict class inheritance.You just need the right methods. class FileLogger: def write(self, msg): print("File:", msg) class ConsoleLogger: def write(self, msg): print("Console:", msg) def log(writer): writer.write("Hello") log(FileLogger()) log(ConsoleLogger())
74
How to add values or remove values to a python array?
Reference answer
Adding values: - append(): Adds an element to the end of the array. - extend(): Appends multiple elements from an iterable to the end of the array. - insert(): Inserts an element at a specific index within the array. Removing values: - remove(): Removes the first occurrence of a specific element from the array. - pop(): Removes and returns an element at a specified index from the array. - del statement: Deletes an element or a slice of elements from the array.
75
How to import text files into NumPy arrays?
Reference answer
To import Text files into Numpy Arrays, we can use the functions numpy.loadtxt( ) in Numpy. Syntax: numpy.loadtxt(fname, dtype = float, comments='#', delimiter=None, converters=None, skiprows=0, usecols=None, unpack=False, ndmin=0, encoding='bytes', max_rows=None, *, like= None) Example: The following ‘example.txt' text file is considered in this example. It contains the following data: import numpy as np # Text file data converted to integer data type File_data = np.loadtxt("example1.txt", dtype=int) print(File_data) Output: [[1 2 3 4] [5 6 7 8] [9 10 11 12]]
76
What Do You Mean by Iterators in Python?
Reference answer
Iterators are objects that contain countable values that can be iterated upon, namely, lists, sets, tuples, and dicts. This means that you can traverse through the different values, and it will remember its state at various points. It is initialized using iter() and uses the next() method for iteration to the next element. The object__next__() puts an end to the iteration by returning the StopIteration exception.
77
What are the benefits of using Python?
Reference answer
Python benefits: - Readable and simple syntax. - Large standard library. - Wide variety of third-party libraries and frameworks. - Easy integration with other languages. - Powerful for data analysis and scientific computing. - Ideal for automation and scripting.
78
The following code is supposed to create a function that takes a list of integers and returns only the even numbers, but it is not working correctly. Fix the code. def get_even_numbers(numbers): even_numbers = [x for x in numbers if x % 2 == 0] return even_numbers
Reference answer
The code looks correct, but it can be improved by using a generator expression instead of a list comprehension to generate the even numbers on the fly and save memory: def get_even_numbers(numbers): even_numbers = (x for x in numbers if x % 2 == 0) return even_numbers
79
11. Can Python be compiled, or is it only interpreted?
Reference answer
Yes, Python can be both compiled and interpreted. Python is known as an interpreted language. This means source code is executed line-by-line by the Python interpreter at runtime. Python code is first translated to bytecode, before execution. This bytecode is then executed by the Python Virtual Machine (PVM). This intermediate compilation step allows for platform-independent execution. There are tools that can convert Python code to machine code or binary executables. Tools like PyInstaller, cx_Freeze, and Py2exe transform Python scripts into standalone executables. This way, the end user doesn't need a Python interpreter to run the application. Tools like Cython and Nuitka offer ways to compile Python into C or C++ code. This can enhance performance and provide a compiled output. There are ways to compile Python, depending on the requirements of the project, while it is primarily interpreted.
80
Write a program to find the Fibonacci series up to n.
Reference answer
Sample Answer: The Fibonacci sequence starts with 0 and 1, and each subsequent number is the sum of the two preceding numbers. You can generate the sequence up to n terms. For example: def fibonacci(n): fib_series = [0, 1] while len(fib_series) < n: fib_series.append(fib_series[-1] + fib_series[-2]) return fib_series[:n]
81
What are metaclasses in Python?
Reference answer
Metaclasses are classes of classes that define how a class behaves. Classes are instances of metaclasses, just like objects are instances of classes. You can use metaclasses to customize class creation, enforce coding standards, or implement Singleton patterns. Example: class Meta(type): def __new__(cls, name, bases, dct): if "mandatory_method" not in dct: raise TypeError("Class must implement 'mandatory_method'") return super().__new__(cls, name, bases, dct) class MyClass(metaclass=Meta): def mandatory_method(self): pass
82
What's the difference between class variables and instance variables?
Reference answer
Class variables are shared by all objects of a class, while instance variables belong to each object separately, this means if you change a class variable, all objects see the change, but if you change an instance variable, only that object changes, this often confuses people when one object's change affects others. class User: role = "guest" # class variable def __init__(self, name): self.name = name # instance variable u1 = User("A") u2 = User("B") User.role = "admin" print(u1.role, u2.role) # admin admin u1.role = "user" print(u1.role, u2.role) # user admin
83
How do you handle multiple exceptions in Python?
Reference answer
You can handle multiple exceptions in Python by using multiple except blocks or by using a single
84
How do you concatenate two DataFrames vertically in Pandas?
Reference answer
You can concatenate two DataFrames vertically using the `pd.concat()` function with the `axis=0` argument.
85
What does the // operator do in Python?
Reference answer
The // operator performs floor division. The result will be the whole number in front of the decimal point. # x equals 2 x=8//3
86
Write a Program to combine two different dictionaries. While combining, if you find the same keys, you can add the values of these same keys. Output the new dictionary
Reference answer
We can use the Counter method from the collections module from collections import Counter d1 = {'key1': 50, 'key2': 100, 'key3':200} d2 = {'key1': 200, 'key2': 100, 'key4':300} new_dict = Counter(d1) + Counter(d2) print(new_dict)
87
What is the purpose of garbage collection in Python?
Reference answer
- Python automatically frees unused memory resources, optimizing memory usage.
88
What is Python?
Reference answer
Python is a high-level, interpreted programming language known for its simplicity and readability. It is widely used in web development, data analysis, artificial intelligence, and more.
89
How can you convert a string to an integer?
Reference answer
You can use the int() function, like this: num = "5" convert = int(num)
90
How can you perform unit testing in Python? Name some popular testing frameworks?
Reference answer
Unit testing in Python can be done using testing frameworks like unittest, pytest, and nose. These frameworks provide a set of tools to write and run test cases for functions and classes, ensuring that individual units of code work as expected.
91
How do you open and read a file in Python?
Reference answer
You can use the open function to open a file and the read method to read its contents. with open('example.txt', 'r') as file: content = file.read() print(content)
92
What is the purpose of the range() function in Python?
Reference answer
The range() function generates a sequence of numbers. It is commonly used in for loops to iterate over a sequence of numbers. for i in range(5): # Generates numbers from 0 to 4 print(i)
93
What are Python's built-in debugging tools?
Reference answer
Tools like pdb for interactive debugging, logging for tracking events, and IDEs with built-in debugging support such as PyCharm or VSCode.
94
What is NumPy?
Reference answer
NumPy is the fundamental package for scientific computing in Python. It is a Python library that provides a multidimensional array object, various derived objects (such as masked arrays and matrices), and an assortment of routines for fast operations on arrays, including mathematical, logical, shape manipulation, sorting, selecting, I/O, discrete Fourier transforms, basic linear algebra, basic statistical operations, random simulation and much more.
95
How will you find the shape of any given NumPy array?
Reference answer
We can use the shape attribute of the numpy array to find the shape. It returns the shape of the array in terms of row count and column count of the array. import numpy as np arr_two_dim = np.array([("x1","x2", "x3","x4"), ("x5","x6", "x7","x8" )]) arr_one_dim = np.array([3,2,4,5,6]) # find and print shape print("2-D Array Shape: ", arr_two_dim.shape) print("1-D Array Shape: ", arr_one_dim.shape) """ Output: 2-D Array Shape: (2, 4) 1-D Array Shape: (5,) """
96
What is the purpose of the .fillna() method in Pandas?
Reference answer
The `.fillna()` method is used to fill missing values (NaN) in a DataFrame or Series with specified values or methods, such as the mean or median.
97
What is the output of the following code? x = 41 if x > 10: print("Above ten,") if x > 20: print("and also above 20!") else: print("but not above 20.")
Reference answer
Above ten, and also above 20!
98
Using pseudo-code, reverse a String iteratively and recursively
Reference answer
To reverse a string iteratively, you can loop through the original string from the last character to the first, appending each character to a new string. To reverse recursively, you can take the last character and prepend it to the result of reversing the substring excluding the last character, with the base case being an empty string.
99
You're working on a team project with other developers. How do you ensure consistent coding style and collaboration on Python code?
Reference answer
- Answer: I'd advocate for using linters and formatters like Black and Pylint for code style standardization. Utilizing Git and code versioning tools like GitHub would facilitate collaboration and version control.
100
How can you use Python's collections module to simplify common tasks?
Reference answer
The collections module in Python provides specialized data structures like defaultdict, Counter, deque, and OrderedDict to simplify various tasks. For instance, Counter is ideal for counting elements in an iterable, while defaultdict can initialize dictionary values without explicit checks. Here is an example: from collections import Counter data = ['a', 'b', 'c', 'a', 'b', 'a'] count = Counter(data) print(count) # Output: Counter({'a': 3, 'b': 2, 'c': 1})
101
78. How can you handle transaction management in Python with databases?
Reference answer
Developers use the built-in module called "sqlite3" for SQLite databases and various third-party libraries for other database management systems like MySQL, PostgreSQL, or Oracle, to handle transaction management in Python with databases. Transactions are crucial for ensuring data integrity, consistency, and reliability when interacting with databases in Python. Execute the `conn.begin()` method on a database connection object, to initiate a transaction in Python. This marks the beginning of the transaction. Subsequent database operations within the same connection are then treated as part of the transaction until explicitly committed using `conn.commit()` or rolled back using `conn.rollback()`. This approach allows developers to wrap multiple database operations into a single transaction and ensures that all changes are either applied together or completely rolled back in case of an error or exception. It's a good practice to use the `with` statement in Python for transaction management. The code ensures that the transaction is correctly committed or rolled back, even if an exception occurs.
102
List some common Python interpreters.
Reference answer
- CPython: The default and most widely used Python interpreter. It is written in C and serves as the reference implementation for the Python language. - Jython: An implementation of Python that runs on the Java Virtual Machine (JVM). It allows seamless integration with Java code and libraries. - IronPython: An implementation of Python targeting the .NET framework. It provides integration with the .NET ecosystem and allows Python code to interact with .NET languages and libraries. - PyPy: A fast and highly optimized implementation of Python. It utilizes a Just-in-Time (JIT) compiler to improve execution speed. - Stackless Python: A variant of CPython that provides support for micro threads, allowing lightweight concurrency without the need for traditional operating system threads. - MicroPython: A lightweight implementation of Python specifically designed for microcontrollers and embedded systems. It provides a reduced subset of the Python language to optimize for limited resources.
103
What is a module in Python with example?
Reference answer
Module is a file containing Python definitions, functions, classes, and variables. It acts as a container for related code and can be imported into other Python programs using the import statement. Modules help in modularizing code and promote code reuse. “Import” is used to get all functionalities of any particular module. Ex- Python provides a wide range of built-in modules that offer various functionalities like: - math: Provides mathematical functions and constants. - random: Offers functions for generating pseudo-random numbers. - datetime: Enables manipulation of dates, times, and time intervals. - os: Allows interaction with the operating system, providing functions for file operations, directory handling, etc. - sys: Provides access to system-specific parameters and functions. - json: Enables encoding and decoding of JSON data. - re: Provides regular expression matching operations. - csv: Offers functionality for reading and writing CSV files. - urllib: Allows making HTTP requests and working with URLs. - sqlite3: Provides a simple and lightweight database interface for SQLite database Example: import math value = math.pi print("Value of Pi = : ",value)
104
What is the purpose of the groupby() function in Pandas?
Reference answer
The groupby() function in Pandas is used to group rows of a dataframe based on one or more columns, and then perform aggregation functions like sum, mean, and count on each group.
105
65. How would you describe the merge sort algorithm?
Reference answer
The merge sort algorithm is a divide-and-conquer sorting technique. It recursively divides an array into two halves, sorts them independently, and then merges the sorted halves. The merging process is pivotal: it takes two smaller sorted arrays and combines them to produce a single, sorted array. You'll often encounter this algorithm when discussing sorting techniques in data structures or when optimizing data processing tasks, in the context of Python. It's efficient, with a time complexity of O(n log n), making it a preferred choice in many scenarios. Its space complexity is O(n), which means it requires additional memory. Do bear this in mind when comparing it with other sorting algorithms, especially in contexts where memory usage is a concern.
106
Write a Python program to sort a list.
Reference answer
The following code can be used to sort a list in Python: list = ["1", "4", "0", "6", "9"] list = [int(i) for i in list] list.sort() print (list)
107
What is NumPy, and why is it important?
Reference answer
NumPy is a library for numerical computations, that can contains large, multi dimensional arrays and matrices with mathematical functions. Example: import numpy as np arr = np.array([1, 2, 3]) print(np.mean(arr)) # 2.0
108
How can you reverse a string in Python?
Reference answer
You can reverse a string in Python using slicing. For example: original_string = Hello, World!; reversed_string = original_string[::-1]
109
Why do Python developers use continue, break, and pass?
Reference answer
Here are the descriptions of how Python developers use these statements: | Statement | Application | | Break | Used to terminate a loop and move on to the next statement. | | Continue | Continue rejects all the latter statements of the loop and moves the control back to the top. | | Pass | Helps bypass a piece of code that's needed only for syntax purposes. At its, pass executes a null operation. |
110
What is the difference between a tuple and a list in Python?
Reference answer
A list is a mutable sequence of elements, while a tuple is an immutable sequence of elements. This means that you can modify a list by adding, removing or changing elements, but you cannot do the same with a tuple.
111
How can you concatenate two lists in Python?
Reference answer
We can concatenate two lists in Python using the +operator or the extend() method. 1. + operator: This creates a new list by joining two lists together. a = [1, 2, 3] b = [4, 5, 6] res = a + b print(res) Output [1, 2, 3, 4, 5, 6] 2. extend() : This adds all the elements of the second list to the first list in-place. a = [1, 2, 3] b = [4, 5, 6] a.extend(b) print(a) Output [1, 2, 3, 4, 5, 6]
112
While importing data from different sources, can the pandas library recognize dates?
Reference answer
Yes, they can, but with some bit of help. We need to add the parse_dates argument while we are reading data from the sources. Consider an example where we read data from a CSV file, we may encounter different date-time formats that are not readable by the pandas library. In this case, pandas provide flexibility to build our custom date parser with the help of lambda functions as shown below: import pandas as pd from datetime import datetime dateparser = lambda date_val: datetime.strptime(date_val, '%Y-%m-%d %H:%M:%S') df = pd.read_csv("some_file.csv", parse_dates=['datetime_column'], date_parser=dateparser)
113
How to generate random numbers in Python?
Reference answer
Random numbers in Python are generated using the random module, which provides functions like random.random() for floats between 0 and 1, random.randint(a, b) for integers in a range, and random.choice() for selecting a random element from a sequence.
114
Python program to print following ‘*' pattern: * ** *** **** *****
Reference answer
def pattern_print(rows): for i in range(1, rows + 1): print("*" * i) # Take input from the user rows = int(input("Enter the number of rows: ")) # Call the function to print the pattern pattern_print(rows)
115
Define Scope in Python.
Reference answer
Every object in Python has its own scope. In Python, a scope is a block of code where an object remains relevant. All objects within a program are uniquely identified by namespaces. These namespaces, however, have a defined scope, enabling you to use their objects without any prefixes. Here are a few examples of Python scope created during code execution: - A local Python scope available in the current function is referred to as local scope. - A global Python scope refers to the objects that have been available throughout the code execution since their inception. - A module Python scope refers to the global objects of the current module that are accessible in the program - An outermost scope covers each of the program's built-in names.
116
What Is the Starting Point of Python Code Execution?
Reference answer
If the Python code is a method, you have to explicitly call the method to start execution. If it is not, it will be executed anytime you run or import the file.
117
49. How to write a Python program to find common items between two lists without using intersection?
Reference answer
Use list comprehension to write a Python program that finds common items between two lists without using intersection. Iterate through one list, and for each item, check if it's present in the second list. If it is, it's a common item. However, ensure that you don't introduce duplicates in the output list. Here's a concise code to accomplish this: This approach is simple and efficient for smaller lists. Consider converting one of the lists to a set for faster membership checking, for larger lists. Do remember, the above solution might have a higher time complexity in cases of longer lists due to nested loops. 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.
118
48. How to write a Python program to check whether a number is prime or not?
Reference answer
You would use a simple algorithm to test divisibility, to write a Python program to check if a number is prime or not. A prime number is greater than 1 and divisible only by 1 and itself. Begin by checking if the number is less than 2; if so, it's not prime. Iterate from 2 to the square root of the number, for numbers 2 and above. The number is not prime, if it is divisible by any of these values. The number is prime, if you complete the loop without finding a divisor. In practice, this translates to a function where you use a loop to check divisibility. Return `False` if a divisor is found, and `True` at the end if no divisor is identified.
119
What is the difference between an array and a list?
Reference answer
Arrays can store only one data type while lists store any data type.
120
How do you apply secure coding practices in Python?
Reference answer
- Do ensure to validate and sanitize any and all user inputs. - Do not hardcode credentials; instead, use environment variables to store them. - Make sure to maintain updated dependencies. - Handle all exceptions properly so that sensitive information is not revealed.
121
Explain how else can be used with loops in Python.
Reference answer
In Python, the else clause in a loop is executed when the loop finishes execution normally (without encountering any breaks).
122
What is a DataFrame and a Series in Pandas?
Reference answer
- Series: One-dimensional labelled array. - DataFrame: Two-dimensional labelled data structure (like a table). Example: import pandas as pd # Creating a Pandas Series s = pd.Series([1, 2, 3]) # Creating a Pandas DataFrame df = pd.DataFrame({'a': [1, 2], 'b': [3, 4]}) print(s) print(df)
123
How do you check if a given MAC address is valid in Python?
Reference answer
You can use a regular expression in Python to check if a given MAC address is valid.
124
How can Python script be executable on Unix?
Reference answer
The script file must begin with #!/usr/bin/env Python. This means that the first line must always begin with ‘#'.
125
What is the difference between mutable and immutable objects in Python?
Reference answer
Mutable objects allow their internal state to be changed in-place after creation without changing their identity (id()). Examples include list, set, dict, bytearray, and most user-defined classes. Immutable objects cannot be altered once created; any operation that appears to modify them actually creates a new object with a new identity. Examples include int, float, complex, str, tuple, frozenset, bytes, and bool. Immutable objects provide data integrity, are inherently thread-safe, and are hashable (can be used as dictionary keys). Mutable objects are more memory-efficient for frequent updates. Python uses pass-by-assignment: modifications to mutable objects inside functions persist in the original object, while immutable objects remain unchanged.
126
36. How to write a Python function to sort a list of numbers in ascending order?
Reference answer
To write a Python function that sorts a list of numbers in ascending order, use Python's built-in `sorted` function. Here's a simple example of such a function: The function returns a new list with the numbers sorted in ascending order, when this function is called with a list of numbers. Use the function in your application by passing the list you want to sort. The original list remains unchanged, ensuring data integrity. If you wish to sort the original list in-place, use the `sort` method of the list.
127
What is the purpose of the "yield" keyword in Python, and how is it used in generator functions?
Reference answer
The yield keyword is used in generator functions to return a value and temporarily suspend the function's execution. When the generator function is called again, it resumes execution from the point it left off and continues generating values one-at-a-time.
128
What is the difference between shallow and deep copies in Python?
Reference answer
A shallow copy, created with copy.copy(), duplicates only the outer container, leaving references to nested objects intact. In contrast, a deep copy, made with copy.deepcopy(), recursively duplicates all contained objects. Choosing the right method is key to avoiding side effects and conserving memory.
129
What is Docstring in Python?
Reference answer
A Docstring is a multiline string used to document a specific code segment. Therefore, developers using Python can easily understand what the code does without having to study the implementation details.
130
What are slots in Python, and when would you use it?
Reference answer
The __slots__ feature limits which attributes can be added to instances of a class to save memory, since a dict is not created for each instance Example: class MyClass: __slots__ = ['x', 'y'] def __init__(self, x, y): self.x = x self.y = y # Example usage obj = MyClass(10, 20) print(obj.x, obj.y) # 10 20
131
What is type conversion in Python? Explain with examples.
Reference answer
Type conversion refers to the conversion of one data type into another. int() – converts any data type into integer type float() – converts any data type into float type ord() – converts characters into integer hex() – converts integers to hexadecimal oct() – converts integer to octal tuple() – This function is used to convert to a tuple. set() – This function returns the type after converting to set. list() – This function is used to convert any data type to a list type. dict() – This function is used to convert a tuple of order (key, value) into a dictionary. str() – Used to convert integer into a string. complex(real,imag) – This function converts real numbers to complex(real,imag) number.
132
The following code is supposed to remove all the even numbers from a list. What is wrong with the code, and how can it be fixed? numbers = [1, 2, 3, 4, 5] for number in numbers: if number % 2 == 0 numbers.remove(number) print(numbers)
Reference answer
The code is modifying the list while iterating over it, which can lead to unexpected results. The fixed code is to create a new list instead: numbers = [1, 2, 3, 4, 5] odd_numbers = [] for number in numbers: if number % 2 != 0: odd_numbers.append(number) print(odd_numbers)
133
73. How to use SQLAlchemy?
Reference answer
SQLAlchemy is a popular SQL toolkit and Object-Relational Mapping (ORM) library for Python. It allows developers to interact with relational databases in an efficient and Pythonic manner. Start by installing SQLAlchemy with the command pip install sqlalchemy. Create an engine that connects to your database using the create_engine function. Define your models by extending the Base class and create a session to query the database. Perform CRUD operations using this session. Close the session once done, to ensure proper resource management. Use transactions for atomic operations: commit your changes to persist them, or roll back, if an error occurs. Always remember to handle exceptions, as database operations can fail for various reasons.
134
Write a Python program to calculate the factorial of a number
Reference answer
def factorial(n): if n == 0: return 1 return n * factorial(n - 1) print(factorial(5)) # 120
135
What is pickling and unpickling?
Reference answer
Pickling is the process of converting a Python object into a byte stream for storage or transmission, using the pickle module. Unpickling is the reverse process, converting the byte stream back into the original object.
136
21. What is a lambda function?
Reference answer
A lambda function is a small, anonymous function in Python. A lambda function cannot contain any statements, and it returns a function object which can be reassigned to any variable. Lambda functions don't have a name, unlike regular functions defined using the `def` keyword. They can take any number of arguments but can only have one expression. The expression's value is returned when the lambda function is called. Lambda functions are often used for short, simple operations that can be defined in a single line. For example, a lambda function to add two numbers looks like this: `add = lambda x, y: x + y` . You call it with `add(5, 3)` to get the result `8` . They are frequently used in situations where a full function definition would be overly verbose, such as in sorting or filtering operations.
137
Is Python a case-sensitive programming language?
Reference answer
Yes, Python is a case-sensitive programming language meaning that Variable and variable have different values.
138
What is the extension of the Python source file?
Reference answer
Python source file has a .py extension like test.py, is a Python file.
139
Write Python code to remove the whitespace from the following string – ‘abc def geh ijk'.
Reference answer
s= ‘abc def geh ijk'.replace(‘ ‘,'')
140
Modify your function to calculate the total revenue for each Product within the filtered data.
Reference answer
def filter_and_aggregate_revenue(df, start_date, end_date, region): filtered_df = df[(df['Date'] >= start_date) & (df['Date'] <= end_date) & (df['Region'] == region)] revenue_by_product = filtered_df.groupby('Product')['Revenue'].sum().reset_index() return revenue_by_product
141
Why is Python good for data analysis?
Reference answer
Python works great for data analysis especially for data mining, data processing and data visualization.
142
39. How to implement a stack in Python?
Reference answer
A stack is implemented in Python using the built-in list type. The list's `append()` method provides the functionality of a stack's push operation. It adds elements to the top of the stack. Conversely, the list's `pop()` method removes the topmost element, mimicking the stack's pop operation.Use the indexing operation with `-1` as the index, to check the top element without removing it. Care must be taken when using lists as stacks. Ensure not to use operations that access or modify elements from the middle or start of the list. This guarantees the Last In, First Out (LIFO) property of stacks is maintained. Always check for an empty stack before popping to avoid IndexError
143
47. How to write a Python program to count the number of even and odd numbers in a list?
Reference answer
Use a loop to iterate through each number, to write a Python program that counts the number of even and odd numbers in a list. Initialize two counters, one for even numbers and one for odd numbers, both set to zero. Traverse the list, and for each number, use the modulus operator (`%`) to determine its type. Increment the even counter, if the number % 2 is 0. Otherwise, increment the odd counter. You will have the counts of even and odd numbers in the respective counters, after iterating through the list. This approach ensures that you go through the list only once, making it efficient for larger lists.
144
Can you explain what is unittest in Python?
Reference answer
Unittest or unit testing is a way to test various codes in Python to ascertain whether they can be used safely or not. This framework is in-built in Python and helps to ensure the quality of code in Python. All the criteria, that are found to be useful and practical during the development process, are coded into the test script by the Python developer. This is done to ensure unit preciseness and accuracy. If any criterion fails, it is reported in the summary.
145
Explain the use of super() function in Python.
Reference answer
The super() function is used to call the parent class's methods and constructors. It helps to avoid directly referencing the parent class.
146
What does it mean to be dynamically typed in Python?
Reference answer
It means Python type-checks data types during execution. This implies that the Python interpreter type checks as the code runs.
147
Write a Python code to remove duplicates from a list
Reference answer
list1 = [1, 2, 2, 3, 4, 4] unique_list1 = list(set(list1)) print(unique_list1) # [1, 2, 3, 4]
148
10. What is PEP 8, and why is it important?
Reference answer
PEP 8 is a document that provides guidelines and best practices on how to write Python code, to enhance the readability and consistency of code. Consistency is the primary reason behind PEP 8. Multiple developers working on the same project can have different coding styles. This leads to code that's hard to read and maintain. PEP 8 provides a standard, ensuring everyone writes code that looks familiar. PEP 8 ensures that the code is clean and easy to understand. PEP 8 covers aspects like indentation, variable naming, and where to put spaces. For example, you should use four spaces for each indentation level, not tabs. Following PEP8 makes code easier to read. Readable code is crucial as it reduces the risk of bugs and makes maintenance easier. Developers spend more time reading code than writing it. PEP 8 also touches upon more complex topics, such as how to structure imports or how to format long expressions or statements. Covering a wide range of scenarios that Python developers might encounter. Many companies adopt PEP 8 as a part of their coding standards. Knowing and following PEP 8 can give a competitive edge in technical interviews and daily work. Code reviews often check for PEP 8 compliance, ensuring a unified codebase. PEP 8 plays a pivotal role in Python development. It ensures consistency, readability, and maintainability in Python code.
149
Write a program in Python to find the maximum subarray sum.
Reference answer
def max_subarray_sum(arr): max_sum = current_sum = arr[0] for num in arr[1:]: current_sum = max(num, current_sum + num) max_sum = max(max_sum, current_sum) return max_sum print(max_subarray_sum([-2, 1, -3, 4, -1, 2, 1, -5, 4])) # 6
150
How does Python implement multithreading?
Reference answer
Python's threading module provides support for threads, but due to the GIL, threads are not executed in parallel for CPU-bound tasks. They are effective for I/O-bound tasks. For true parallelism, use the multiprocessing module or external libraries like joblib.
151
How does continue, break, and pass work?
Reference answer
Continue, break, and pass are three control flow statements in Python that allow you to change the flow of your program under certain conditions. Continue statement: When continue is used inside a loop, it tells Python to skip the current iteration and move on to the next one. Any code after the continue statement within the loop for that iteration will be ignored, and the loop will continue with the next iteration. Break statement: When break is used inside a loop, it tells Python to immediately exit the loop, regardless of any remaining iterations. Any code after the break statement within the loop will be skipped, and the program will continue executing from the next statement after the loop. Pass statement: pass is used as a placeholder when you need to have a statement for syntactic reasons, but you don't want to do anything in that part of the code. It doesn't do anything and is mainly used to avoid syntax errors when you're still working on implementing certain parts of your code.
152
What Are Python Modules? Name the Most Popular
Reference answer
Python modules are files with the Python code, it helps to put a huge code to different files and folders to organize it better. Among the most commonly used Python packages are NumPy, Pandas, Matplotlib and Seaborn
153
What are the benefits of using Python as a programming language?
Reference answer
- High-level and interpreted: Easy to learn, write, and debug compared to compiled languages. - Object-oriented: Supports clean and modular code design with classes and objects. - Extensive libraries: Rich ecosystem of libraries for various tasks, reducing development time. - Dynamically typed: No need for explicit type declarations, offering flexibility. - Large and active community: Abundant resources, tutorials, and support available.
154
What is the difference between a while loop and a for loop in Python?
Reference answer
A for loop is used to iterate over a sequence, such as a list or a string, while a while loop is used to repeat a block of code as long as a certain condition is true.
155
What is the purpose of the os module in Python?
Reference answer
The os module provides functions for interacting with the operating system, such as working with files and directories, managing processes, and accessing environment variables.
156
Could you share a specific example where you optimized data processing with Pandas for a memory-intensive operation? How did you manage memory constraints?
Reference answer
Certainly. In one project, we used Pandas to process a large CSV file that couldn't fit into memory. We read the data in chunks, processed each chunk, and aggregated the results. This approach allowed us to handle the data efficiently without running out of memory.
157
What methods are commonly used to detect and prevent performance bottlenecks in data manipulation processes?
Reference answer
Methods include profiling code with cProfile or line_profiler, benchmarking with timeit, analyzing and refactoring hotspots, optimizing data structures and algorithms, parallelizing computations if possible, and reducing redundancy in data processing workflows.
158
What are some features of the Python language?
Reference answer
• Python is an interpreted language, meaning that Python code does not need to compile before running. • Python is a dynamically typed language. This means you don't need to declare the type of variable when you create it. Python will determine its type dynamically. • Python is object-oriented. With Python, you can define classes and use composition and inheritance. Python does not support access specifiers like public and private. • Functions in Python are first-class objects. This means that you can assign them to a variable. Python functions can also return other functions or accept them as parameters. • Python is a general-purpose language, which is very popular in many industries. Developers use it in automation, web applications, machine learning, big data, and more. • It is easy and quick to write code in Python, but Python code generally runs slower than compiled languages.
159
How do you create custom exceptions in Python, and why would you use them in your code?
Reference answer
Custom exceptions are created by defining new classes that inherit from built-``in exception classes. They are used to raise specific errors in your code.
160
How do you create a Python function?
Reference answer
In Python, functions can be created/defined using the def statement. To create these functions, firstly we declare them and name them. Then, we start a function definition.
161
How can you create a custom exception class in Python?
Reference answer
To create a custom exception class, inherit from the built-in `Exception` class or one of its subclasses.
162
How would you sort a dictionary in Python?
Reference answer
We can sort this type of data by either the key or the value and this is done by using the sorted() function. First, we need to know how to retrieve data from a dictionary to be passed on to this function. There are two basic ways to get data from a dictionary: Dictionary.keys() : Returns only the keys in an arbitrary order. Dictionary.values() : Returns a list of values. Dictionary.items() : Returns all of the data as a list of key-value pairs. Sorted() syntax This method takes one mandatory and two optional arguments: Data (mandatory): The data to be sorted. We will pass the data we retrieved using one of the above methods. Key (optional): A function (or criteria) based on which we would like to sort the list. For example, the criteria could be sorting strings based on their length or any other arbitrary function. This function is applied to every element of the list and the resulting data is sorted. Leaving it empty will sort the list based on its original values. Reverse (optional): Setting the third parameter as true will sort the list in descending order. Leaving this empty sorts in ascending order. keys() dict = {} dict['1'] = 'apple' dict['3'] = 'orange' dict['2'] = 'pango' lst = dict.keys() # Sorted by key print("Sorted by key: ", sorted(lst)) values() dict = {} dict['1'] = 'apple' dict['3'] = 'orange' dict['2'] = 'pango' lst = dict.values() #Sorted by value print("Sorted by value: ", sorted(lst)) items() dict = {} dict['1'] = 'apple' dict['3'] = 'orange' dict['2'] = 'strawberry' lst = dict.items() # Sorted by key print("Sorted by key: ", sorted(lst, key = lambda x : x[0])) #Sorted by value print("Sorted by value: ", sorted(lst, key = lambda x : x[1]))
163
Can we perform parallel computing in python?
Reference answer
Parallel computing can be performed in Python using various libraries such as multiprocessing, threading, concurrent.futures, and asyncio.
164
Find the first non-repeating integer in a list
Reference answer
Here you can use a Python dictionary to keep count of repetitions. Sample input: [9,2,3,2,6,6] def findFirstUnique(lst): counts = {} # Creating a dictionary # Initializing dictionary with pairs like (lst[i],(count,order)) counts = counts.fromkeys(lst, (0,len(lst))) order = 0 for ele in lst: # counts[ele][0] += 1 # Incrementing for every repitition # counts[ele][1] = order counts[ele] = (counts[ele][0]+1 , order) order += 1 # increment order answer = None answer_key = None # filter non-repeating with least order for ele in lst: if (counts[ele][0] is 1) and (answer is None): answer = counts[ele] answer_key = ele elif answer is None: continue elif (counts[ele][0] is 1) and (counts[ele][1] < answer[1]): answer = counts[ele] answer_key = ele return answer_key print(findFirstUnique([1, 1, 1, 2])) Output: 2 The keys in the counts dictionary are the elements of the given list and the values are the number of times each element appears in the list. We return the element that appears at most once in the list on line 23. We need to maintain the order of update for each key in a tuple value. Time Complexity Since the list is only iterated over only twice and the counts dictionary is initialized with linear time complexity, therefore the time complexity of this solution is linear, i.e., O(n).
165
What are the two primary data structures in Pandas?
Reference answer
The two primary data structures in Pandas are Series and DataFrame.
166
How would you handle missing values in a Dataset?
Reference answer
Handling missing values in a dataset is crucial for ensuring the quality and reliability of analysis. There are several approaches, depending on the context and the nature of the data: 1. Understanding the Context: - 1.1 Analyze the Missing Data: Investigate why the values are missing. Are they missing at random, or is there a systematic reason? This understanding can influence how we handle them. 2. Types of Missing Data: - MCAR (Missing Completely at Random): The missingness is unrelated to the data. In this case, we might remove the affected rows without bias. - MAR (Missing at Random): The missingness relates to other observed data. Here, imputation methods can be used. - MNAR (Missing Not at Random): The missingness is related to the missing values themselves. This requires more complex handling, often involving modeling. 3. Handling Strategies for missing values: 3.1 Removal: - Listwise Deletion: Remove rows with missing values if they constitute a small portion of the dataset and their removal won't affect the results. - Column Removal: Eliminate columns that have a high percentage of missing values, as they may not contribute meaningful information. - 3.2 Imputation: - Mean/Median/Mode Imputation: For numerical features, replace missing values with the mean or median; for categorical features, use the mode. This is simple but can introduce bias. - K-Nearest Neighbors (KNN) Imputation: Use the values from the nearest neighbors to fill in the missing values, which can preserve data relationships. - Regression Imputation: Predict missing values using regression models based on other available features. 3.3 Using Algorithms That Handle Missing Values: - Some algorithms, like decision trees or random forests, can handle missing values intrinsically without requiring imputation. 4. Creating Indicator Variables: For certain analyses, create a new binary column indicating whether a value was missing, which can help capture potential patterns in the data. - Data Enrichment: If feasible, explore augmenting the dataset with additional sources of data to fill in gaps. 5. Documenting the Process: It's essential to document the decisions made regarding missing values, including the rationale and methods used, as this transparency is vital for reproducibility.
167
What Is the Difference Between Pickling and Unpickling?
Reference answer
Pickling is transforming any Python object into a string representation and dumping it into a file by using the dump function. Unpickling is a reverse process of retrieving Python objects from the string representation.
168
69. What are AVL trees?
Reference answer
AVL trees, also known as Adelson-Velsky and Landis trees, are a type of self-balancing binary search tree. In the context of Python developer interview questions, AVL trees are essential data structures used to maintain a balanced tree structure, ensuring efficient operations like insertion, deletion, and searching. An AVL tree is structured in a way that the height difference between the left and right subtrees (known as the balance factor) of any node is limited to one, making it a height-balanced binary search tree. AVL trees perform rotations when necessary during insertion and deletion operations, To achieve this balance. These rotations maintain the balance of the tree and ensure that the tree remains efficient, with logarithmic time complexity for operations. 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.
169
Write a function to find all valid parentheses combinations for a given number of pairs.
Reference answer
Sample Answer: Generating all valid combinations of parentheses for a given number of pairs can be approached using backtracking. It systematically explores all possible combinations while ensuring they remain valid. In this case, valid combinations must have matching opening and closing parentheses. Here's how you can code a function to find all valid parentheses combinations for n pairs: def generate_parentheses(n): def backtrack(s='', left=0, right=0): if len(s) == 2 * n: result.append(s) return if left < n: backtrack(s + '(', left + 1, right) if right < left: backtrack(s + ')', left, right + 1) result = [] backtrack() return result
170
Are access specifiers used in python?
Reference answer
Python does not make use of access specifiers specifically like private, public, protected, etc. However, it does not derive this from any variables. It has the concept of imitating the behaviour of variables by making use of a single (protected) or double underscore (private) as prefixed to the variable names. By default, the variables without prefixed underscores are public. Example: # to demonstrate access specifiers class InterviewbitEmployee: # protected members _emp_name = None _age = None # private members __branch = None # constructor def __init__(self, emp_name, age, branch): self._emp_name = emp_name self._age = age self.__branch = branch #public member def display(): print(self._emp_name +" "+self._age+" "+self.__branch)
171
Explain the purpose of the requests library in Python.
Reference answer
The requests library is used for making HTTP requests to web services or websites. It simplifies tasks like sending GET and POST requests.
172
In an integrated system, what strategies do you employ to ensure data consistency and prevent data loss or duplication when dealing with unreliable external services?
Reference answer
We often use idempotent operations and transactional semantics. For example, when interacting with a message queue, we ensure that processing a message is an idempotent operation so that reprocessing doesn't lead to data inconsistencies.
173
What built-in types are available in Python?
Reference answer
The built-in types in Python include: - Strings - Integer - Complex numbers - Floating-point numbers - Built-in functions
174
Explain the difference between lists and tuples.
Reference answer
- Lists: Mutable (can be changed), indexed by position (e.g., list[0] accesses the first element). - Tuples: Immutable, indexed by position, often used for fixed data or named sets.
175
How can you find and install third-party packages in Python using pip?
Reference answer
Pip is a package manager for Python that allows you to find, install, and manage third-party packages easily. To install a package, you can use the pip install command followed by the package name. For example: pip install requests This command will install the requests; package, which is commonly used for making HTTP requests.
176
Write a program in Python to determine whether a number is a palindrome.
Reference answer
def is_palindrome(number): return str(number) == str(number)[::-1] print(is_palindrome(121)) # True print(is_palindrome(123)) # False
177
Enhance the previous function to check if the given string is a palindrome. A palindrome is a word that reads the same backward as forward, e.g., "radar".
Reference answer
def is_palindrome(s): reversed_s = s[::-1] return s == reversed_s Explanation of solution: This solution first reverses the input string using the slicing method s[::-1]. It then compares the original string s with the reversed string. If they are identical, it means the string is a palindrome.
178
In your work with data-driven business logic, how do you apply and evaluate the use of assertions?
Reference answer
Assert business rules or assert data integrity when processing data. Example: def process_order(order): assert order['quantity'] > 0, "Order quantity must be positive" # further processing
179
What is the Pass by Value and Pass by Reference?
Reference answer
Whenever arguments are passed to the function, they are always passed by reference. It means if you change the value of the function inside the parameter, it will also change the value of the original parameter. However, if you are passing an immutable variable then it will be passing by value. Hence original copy of the variable will not be changed.
180
What are Arbitrary Arguments?
Reference answer
Arbitrary Arguments are often shortened to *args in Python documentations. If you do not know how many arguments that will be passed into your function, add a * before the parameter name in the function definition. This way the function will receive a tuple of arguments, and can access the items accordingly.
181
What is the difference between Django and Flask?
Reference answer
Django and Flask map the URL's or addresses typed in the web browsers to functions in Python. Flask is much simpler compared to Django but, Flask does not do a lot for you meaning you will need to specify the details, whereas Django does a lot for you wherein you would not need to do much work. Django consists of prewritten code, which the user will need to analyze whereas Flask gives the users to create their own code, therefore, making it simpler to understand the code. Technically both are equally good and both contain their own pros and cons.
182
Implement a decorator to measure the execution time of a function?
Reference answer
- Here's how to implement a decorator in Python to measure the execution time of a function import time def timer_decorator(func): def wrapper(*args, **kwargs): start = time.time() result = func(*args, **kwargs) end = time.time() print(f'{func.__name__} took {end - start:.4f} seconds') return result return wrapper
183
How can you convert a string to all uppercase or all lowercase in Python?
Reference answer
You can use the upper() method to convert a string to uppercase and the lower() method to convert it to lowercase. For example: original_string = Hello, World!; upper_case_string = original_string.upper() lower_case_string = original_string.lower() print(upper_case_string) # Output: HELLO, WORLD!; print(lower_case_string) # Output: hello, world!;
184
What are Django templates?
Reference answer
The template is a simple text file. It can create any text-based format like XML, CSV, HTML, etc. A template contains variables that get replaced with values when the template is evaluated and tags (% tag %) that control the logic of the template.
185
Explain the difference between global and local variables.
Reference answer
- Global variables: Defined outside functions and are accessible everywhere within the program. - Python Example: x = 10 # global variable def func(): print(x) - Local variables: Defined inside functions and have their scope limited to the specific function they are defined in. Local variables take precedence over global variables with the same name within their scope. Accessing a global variable inside a function requires explicit declaration using global keyword. - Python Example: def func(): x = 5 # local variable print(x)
186
What Are the Advantages of Python Over Other Scripting Languages Such as Javascript?
Reference answer
The answer is personal for every candidate, it shows how well they know Python peculiarities and what they value in their work. The example of the answer may look like this: Python is easy to learn, write, and understand since it has syntax, close to this of the English language. It has numerous libraries and frameworks to fit different projects and make the development faster.
187
What is the purpose of the .rolling() method in Pandas?
Reference answer
The `.rolling()` method is used for rolling window calculations on time series data. It allows you to calculate moving averages and other statistics over a specified window of data.
188
How do you handle date and time in Python?
Reference answer
Python's datetime module provides classes and functions for working with date and time, including parsing, formatting, and arithmetic operations.
189
The following code is supposed to find the sum of the even numbers in a list. What is wrong with the code, and how can it be fixed? numbers = [1, 2, 3, 4, 5] total = 0 for number in numbers: if number % 2 == 0 total += number print(total)
Reference answer
The code is missing a colon after the if statement. The fixed code is: numbers = [1, 2, 3, 4, 5] total = 0 for number in numbers: if number % 2 == 0: total += number print(total)
190
What is Slicing ?
Reference answer
Slicing is a technique used to extract a part or a subsequence of a sequence, such as a string, list, or tuple. It allows you to retrieve a specific range of elements or specific element from the sequence based on indices. Basic syntax for slicing = “sequence_name[start:stop:step]” Code Ex- my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] sliced = my_list[2:6] print(sliced) #Output: [3, 4, 5, 6] # Slicing with negative indices to get the last three elements sliced = my_list[-3:] print(sliced) #Output: [8, 9, 10]
191
What does the Python continue statement do?
Reference answer
The Python continue statement causes a loop to skip the rest of its body and continue at the beginning of the loop.
192
Compared to Java, How is Exception Handling Differently in Python?
Reference answer
Python follows a try-except approach, which allows developers to view the error in the code without terminating its execution. In some cases, it may even suggest ways to resolve the problem. Python follows two types of try-except, namely, try-except-finally and try-except-else.
193
How do you monitor performance metrics in a Python application?
Reference answer
Monitor response time, throughput, and memory usage with monitoring tools or custom logging. Example: import time # Start the timer start = time.time() # Code to measure # ... # End the timer end = time.time() print(f"Execution time: {end - start} seconds")
194
What is regression?
Reference answer
Regression is a statistical method used to model the relationship between a dependent variable and one or more independent variables. In machine learning, it is used for predicting continuous outcomes, such as housing prices or temperature.
195
What does it mean when we say that Python is interpreted language?
Reference answer
Python is an interpreted language, meaning its code is executed line by line by the Python interpreter at runtime, rather than being compiled into machine code beforehand. This allows for easier debugging and cross-platform compatibility.
196
Differentiate between new and override modifiers.
Reference answer
The new modifier is used to instruct the compiler to use the new implementation and not the base class function. The Override modifier is useful for overriding a base class function inside the child class.
197
How do you debug Python code? Explain some common debugging techniques.
Reference answer
- Use the built-in debugger (pdb) for step-by-step execution and variable inspection. - Print statements can be strategically placed to track program flow. - Error messages should be carefully analyzed and interpreted.
198
What are common testing frameworks in Python and how are they used?
Reference answer
Familiarity with testing frameworks like unittest and pytest is crucial for writing reliable, production-ready code. Interviewers may ask you to write unit tests, isolate external dependencies using unittest.mock, or test asynchronous code with asyncio.
199
How to check the Google Webcache age of a website?
Reference answer
Use the following URL format: http://webcache.googleusercontent.com/search?q=cache:URLGOESHERE Be sure to replace “URLGOESHERE” with the proper web address of the page or site whose cache you want to retrieve and see the time for. For example, to check the Google Webcache age of edureka.co you'd use the following URL: http://webcache.googleusercontent.com/search?q=cache:edureka.co
200
How do you achieve multithreading in Python?
Reference answer
- Python has a multi-threading package but if you want to multi-thread to speed your code up, then it's usually not a good idea to use it. - Python has a construct called the Global Interpreter Lock (GIL). The GIL makes sure that only one of your ‘threads' can execute at any one time. A thread acquires the GIL, does a little work, then passes the GIL onto the next thread. - This happens very quickly so to the human eye it may seem like your threads are executing in parallel, but they are really just taking turns using the same CPU core. - All this GIL passing adds overhead to execution. This means that if you want to make your code run faster then using the threading package often isn't a good idea.