1. What is Python, what are the benefits of using it, and what do you understand of PEP 8?
Python is one of the most successful interpreted languages. When you write a Python script, it doesn’t need to get compiled before execution. Few other interpreted languages are PHP and Javascript.
Benefits of Python Programming
- Python is a dynamic-typed language. It means that you don’t need to mention the data type of variables during their declaration. It allows to set variables like var1=101 and var2 =” You are an engineer.” without any error.
- Python supports object-orientated programming as you can define classes along with the composition and inheritance. It doesn’t use access specifiers like public or private).
- Functions in Python are like first-class objects. It suggests you can assign them to variables, return from other methods, and pass as arguments.
- Developing using Python is quick but running it is often slower than compiled languages. Luckily, Python enables you to include the “C” language extensions so you can optimize your scripts.
- Python has several usages like web-based applications, test automation, data modeling, big data analytics, and much more. Alternatively, you can utilize it as a “glue” layer to work with other languages.
PEP 8
PEP 8 is the latest Python coding standard, a set of coding recommendations. It guides to deliver more readable Python code.
2. What are the built-in types available in Python?
Here is the list of most commonly used built-in types that Python supports:
- Immutable built-in datatypes of Python
- Numbers
- Strings
- Tuples
- Mutable built-in datatypes of Python
- List
- Dictionaries
- Sets
3. How to find bugs or perform static analysis in a Python application?
- You can use PyChecker, which is a static analyzer. It identifies the bugs in the Python project and also reveals the style and complexity of related bugs.
- Another tool is Pylint, which checks whether the Python module satisfies the coding standard.
4. When is the Python decorator used?
Python decorator is a relative change that you do in Python syntax to adjust the functions quickly.
5. What is the principal difference between a list and the tuple?
List vs. Tuple.
The principal difference between a list and the tuple is that the former is mutable while the tuple is not.
A tuple is allowed to be hashed, for example, using it as a key for dictionaries.
6. How does Python handle memory management?
- Python uses private heaps to maintain its memory. So the heap holds all the Python objects and the data structures. This area is only accessible to the Python interpreter; programmers can’t use it.
- And it’s the Python memory manager that handles the Private heap. It does the required allocation of the memory for Python objects.
- Python employs a built-in garbage collector, which salvages all the unused memory and offloads it to the heap space.
7. What are the principal differences between the lambda and def?
Lambda vs. def.
- Def can hold multiple expressions while lambda is a uni-expression function.
- Def generates a function and designates a name to call it later. Lambda forms a function object and returns it.
- Def can have a return statement. Lambda can’t have return statements.
- Lambda supports to get used inside a list and dictionary.
8. Is there a switch or case statement in Python? If not then what is the reason for the same?
No, Python does not have a Switch statement, but you can write a Switch function and then use it.
9. What are the optional statements possible inside a try-except block in Python?
There are two optional clauses you can use in the try-except block.
- The “else” clause
- It is useful if you want to run a piece of code when the try block doesn’t create an exception.
- The “finally” clause
- It is useful when you want to execute some steps which run, irrespective of whether there occurs an exception or not.
10. What is a string in Python?
A string in Python is a sequence of alphanumeric characters. They are immutable objects. It means that they don’t allow modification once they get assigned a value. Python provides several methods, such as join(), replace(), or split() to alter strings. But none of these change the original object.
11. What is slicing in Python?
Slicing is a string operation for extracting a part of the string, or some part of a list. In Python, a string (say text) begins at index 0, and the nth character stores at position text[n-1]. Python can also perform reverse indexing, i.e., in the backward direction, with the help of negative numbers. In Python, the slice() is also a constructor function that generates a slice object. The result is a set of indices mentioned by range(start, stop, step). The slice() method allows three parameters. 1. start – starting number for the slicing to begin. 2. stop – the number which indicates the end of slicing. 3. step – the value to increment after each index (default = 1).
12. What is %s in Python?
Python has support for formatting any value into a string. It may contain quite complex expressions.
One of the common usages is to push values into a string with the %s format specifier. The formatting operation in Python has the comparable syntax as the C function printf() has.
13. Is a string immutable or mutable in Python?
Python strings are indeed immutable.
Let’s take an example. We have an “str” variable holding a string value. We can’t mutate the container, i.e., the string, but can modify what it contains which means the value of the variable.
14. What is Docstring in Python?
A docstring is a unique text that happens to be the first statement in the following Python constructs:
Module, Function, Class, or Method definition.
A docstring gets added to the __doc__ attribute of the string object.
Now, read some of the Python interview questions on functions.
15. What is a function in Python programming?
A function is an object which represents a block of code and is a reusable entity. It brings modularity to a program and a higher degree of code reusability.
Python has given us many built-in functions such as print() and provides the ability to create user-defined functions.
16. How many basic types of functions are available in Python?
Python gives us two basic types of functions.
- Built-in, and
- User-defined.
The built-in functions happen to be part of the Python language. Some of these are print(), dir(), len(), and abs() etc.
17. How do we write a function in Python?
We can create a Python function in the following manner.
Step-1: to begin the function, start writing with the keyword def and then mention the function name.
Step-2: We can now pass the arguments and enclose them using the parentheses. A colon, in the end, marks the end of the function header.
Step-3: After pressing an enter, we can add the desired Python statements for execution.
18. What is a function call or a callable object in Python?
A function in Python gets treated as a callable object. It can allow some arguments and also return a value or multiple values in the form of a tuple. Apart from the function, Python has other constructs, such as classes or the class instances which fit in the same category.
19. What is the return keyword used in Python?
The purpose of a function is to receive the inputs and return some output.
The return is a Python statement which we can use in a function for sending a value back to its caller.
20. What is “Call by Value” in Python?
In call-by-value, the argument of whether expression or value gets bound to the respective variable in the function.
Python will treat that variable as local in the function-level scope. Any changes made to that variable will remain local and will not reflect outside the function.
21. What is “Call by Reference” in Python?
We use both “call-by-reference” and “pass-by-reference” interchangeably. When we pass an argument by reference, then it is available as an implicit reference to the function, rather than a simple copy. In such a case, any modification to the argument will also be visible to the caller.
This scheme also has the advantage of bringing more time and space efficiency because it leaves the need for creating local copies.
On the contrary, the disadvantage could be that a variable can get changed accidentally during a function call. Hence, the programmers need to handle in the code to avoid such uncertainty.
22. What is the return value of the trunc() function?
The Python trunc() function performs a mathematical operation to remove the decimal values from a particular expression and provides an integer value as its output.
23. Is it mandatory for a Python function to return a value?
It is not at all necessary for a function to return any value. However, if needed, we can use None as a return value.
24. What does the continue do in Python?
The continue is a jump statement in Python which moves the control to execute the next iteration in a loop leaving all the remaining instructions in the block unexecuted.
The continue statement is applicable for both the “while” and “for” loops.
25. What does the __ Name __ do in Python?
The __name__ is a unique variable. Since Python doesn’t expose the main() function, so when its interpreter gets to run the script, it first executes the code which is at level 0 indentation.
To see whether the main() gets called, we can use the __name__ variable in an if clause compares with the value “__main__.”
26. When should you use the “break” in Python?
Python provides a break statement to exit from a loop. Whenever the break hits in the code, the control of the program immediately exits from the body of the loop.
The break statement in a nested loop causes the control to exit from the inner iterative block.
27. What is the difference between a pass and continue in Python?
The continue statement makes the loop to resume from the next iteration.
On the contrary, the pass statement instructs to do nothing, and the remainder of the code executes as usual.
28. What does the chr() function do in Python?
The chr() function got re-added in Python 3.2. In version 3.0, it got removed.
It returns the string denoting a character whose Unicode code point is an integer.
For example, the chr(122) returns the string ‘z’ whereas the chr(1212) returns the string ‘Ҽ’.
29. What is whitespace in Python?
Whitespace represents the characters that we use for spacing and separation.
They possess an “empty” representation. In Python, it could be a tab or space.
30. What is isalpha() in Python?
Python provides this built-in isalpha() function for the string handling purpose.
It returns True if all characters in the string are of alphabet type, else it returns False.
31. What does the join method do in Python?
Python provides the join() method which works on strings, lists, and tuples. It combines them and returns a united value.
32. What makes the CPython different from Python?
CPython has its core developed in C. The prefix ‘C’ represents this fact. It runs an interpreter loop used for translating the Python-ish code to C language.
33. Which package is the fastest form of Python?
PyPy provides maximum compatibility while utilizing CPython implementation for improving its performance.
The tests confirmed that PyPy is nearly five times faster than the CPython. It currently supports Python 2.7.
34. What is GIL in Python language?
Python supports GIL (the global interpreter lock) which is a mutex used to secure access to Python objects, synchronizing multiple threads from running the Python bytecodes at the same time.
35. How is Python thread-safe?
Python ensures safe access to threads. It uses the GIL mutex to set synchronization. If a thread loses the GIL lock at any time, then you have to make the code thread-safe.
For example, many of the Python operations execute as atomic such as calling the sort() method on a list.
36. How does Python manage memory?
Python implements a heap manager internally which holds all of its objects and data structures.
This heap manager does the allocation/de-allocation of heap space for objects.
37. What is a tuple in Python?
A tuple is a collection type data structure in Python which is immutable.
They are similar to sequences, just like the lists. However, there are some differences between a tuple and list; the former doesn’t allow modifications whereas the list does.
Also, the tuples use parentheses for enclosing, but the lists have square brackets in their syntax.
38. What is a dictionary in Python programming?
A dictionary is a data structure known as an associative array in Python which stores a collection of objects.
The collection is a set of keys having a single associated value. We can call it a hash, a map, or a hashmap as it gets called in other programming languages.
39. What is the set object in Python?
Sets are unordered collection objects in Python. They store unique and immutable objects. Python has its implementation derived from mathematics.
40. What is the use of the dictionary in Python?
A dictionary has a group of objects (the keys) map to another group of objects (the values). A Python dictionary represents a mapping of unique Keys to Values.
They are mutable and hence will not change. The values associated with the keys can be of any Python types.
41. Is Python list a linked list?
A Python list is a variable-length array which is different from C-style linked lists.
Internally, it has a contiguous array for referencing to other objects and stores a pointer to the array variable and its length in the list head structure.
Here are some Python interview questions on classes and objects.
42. What are Errors and Exceptions in Python programs?
Errors are coding issues in a program which may cause it to exit abnormally.
On the contrary, exceptions happen due to the occurrence of an external event that interrupts the normal flow of the program.
43. What are Python Iterators?
Iterators in Python are array-like objects which allow moving on the next element. We use them in traversing a loop, for example, in a “for” loop.
Python library has a no. of iterators. For example, a list is also an iterator and we can start a for loop over it.
44. What is the difference between an Iterator and Iterable?
The collection type like a list, tuple, dictionary, and set are all iterable objects whereas they are also iterable containers that return an iterator while traversing.
Here are some advanced-level Python interview questions.
45. What does the “self” keyword do?
The self is a Python keyword that represents a variable that holds the instance of an object.
In almost, all the object-oriented languages, it is passed to the methods as a hidden parameter.
46. What are the different methods to copy an object in Python?
There are two ways to copy objects in Python.
- copy() function
- It makes a copy of the file from source to destination.
- It’ll return a shallow copy of the parameter.
- deepcopy() function
- It also produces a copy of an object from the source to the destination.
- It’ll return a deep copy of the parameter that you can pass to the function.
47. What is the purpose of docstrings in Python?
In Python, the docstring is what we call the docstrings. It sets a process of recording Python functions, modules, and classes.
48. How do you debug a program in Python? Is it possible to step through the Python code?
Yes, we can use the Python debugger (pdb) to debug any Python program. And if we start a program using pdb, then it let us even step through the code.
49. List down some of the PDB commands for debugging Python programs?
Here are a few PDB commands to start debugging Python code.
- Add breakpoint (b)
- Resume execution (c)
- Step by step debugging (s)
- Move to the next line (n)
- List source code (l)
- Print an expression (p)
50. Why and when do you use generators in Python?
A generator in Python is a function that returns an iterable object. We can iterate on the generator object using the yield keyword. But we can only do that once because their values don’t persist in memory, they get the values on the fly.
Generators give us the ability to hold the execution of a function or a step as long as we want to keep it. However, here are a few examples where it is beneficial to use generators.
- We can replace loops with generators for efficiently calculating results involving large data sets.
- Generators are useful when we don’t want all the results and wish to hold back for some time.
- Instead of using a callback function, we can replace it with a generator. We can write a loop inside the function doing the same thing as the callback and turns it into a generator.
51. What is NumPy and how is it better than a list in Python?
NumPy is a Python package for scientific computing that can deal with large data sizes. It includes a powerful N-dimensional array object and a set of advanced functions.
Also, the NumPy arrays are superior to the built-in lists. There are a no. of reasons for this.
- NumPy arrays are more compact than lists.
- Reading and writing items is faster with NumPy.
- Using NumPy is more convenient than to the standard list.
- NumPy arrays are more efficient as they augment the functionality of lists in Python.