1) What is Python?
Python is a high-level, interpreted, interactive, and object-oriented scripting language. Python is designed to be highly readable. It uses English keywords frequently, whereas the other languages use punctuation, and it has fewer syntactical constructions than the other languages.
2) What is the purpose of PYTHONPATH environment variable?
PYTHONPATH has a role similar to PATH. This variable tells Python Interpreter where to locate the module files imported into a program. It should include Python source library directory and the directories containing Python source code. PYTHONPATH is sometimes preset by Python Installer.
3) What is the purpose of PYTHONSTARTUP, PYTHONCASEOK, and PYTHONHOME environment variables?
PYTHONSTARTUP: It contains the path of an initialization file having Python source code. It is executed every time we start the interpreter. It is named as .pythonrc.py in Unix, and it contains commands that load utilities or modify PYTHONPATH.
PYTHONCASEOK: It is used in Windows to instruct Python to find the first case-insensitive match in an import statement. We can set this variable with any value to activate it.
PYTHONHOME: It is an alternative module search path. It is usually embedded in PYTHONSTARTUP or PYTHONPATH directories to make switching of module libraries easy.
4) 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
Mutable built-in datatypes of Python
5) How is memory managed in Python?
Memory in Python is managed by Python private heap space. All Python objects and data structures are located in a private heap. This private heap is taken care of by Python Interpreter itself, and a programmer doesn’t have access to this private heap.
Python memory manager takes care of the allocation of Python private heap space.
Memory for Python private heap space is made available by Python’s in-built garbage collector, which recycles and frees up all the unused memory.
6) Define pickling and unpickling in Python.
Pickling is the process of converting Python objects, such as lists, dicts, etc., into a character stream. This is done using a module named ‘pickle’, hence the name pickling.
The process of retrieving the original Python objects from the stored string representation, which is the reverse of the pickling process, is called unpickling.
7) 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 Python project and also reveals the style and complexity related bugs.
Another tool is Pylint, which checks whether the Python module satisfies the coding standard.
8) 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.
9) 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.
10) 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.
11) What do file-related modules in Python do? Can you name some file-related modules in Python?
Python comes with some file-related modules that have functions to manipulate text files and binary files in a file system. These modules can be used to create text or binary files, update their content, copy, delete, and more.
Some file-related modules are os, os.path, and shutil.os. The os.path module has functions to access the file system, while the shutil.os module can be used to copy or delete files.
12) 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.
13) What is a string in Python?
A string in Python is a sequence of alpha-numeric 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.
14) 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 which 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).
15) 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.
16) Explain all file processing modes supported in Python.
Python has various file processing modes.
For opening files, there are three modes:
read-only mode (r)
write-only mode (w)
read–write mode (rw)
For opening a text file using the above modes, we will have to append ‘t’ with them as follows:
read-only mode (rt)
write-only mode (wt)
read–write mode (rwt)
Similarly, a binary file can be opened by appending ‘b’ with them as follows:
read-only mode (rb)
write-only mode (wb)
read–write mode (rwb)
To append the content in the files, we can use the append mode (a):
For text files, the mode would be ‘at’
For binary files, it would be ‘ab’
17) 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 that means the value of the variable.
18) 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.
19) 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.
20) How many basic types of functions are available in Python?
Python gives us two basic types of functions.
1. Built-in, and
The built-in functions happen to be part of the Python language. Some of these are print(), dir(), len(), and abs() etc.
21) 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.
22) 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 fits in the same category.
23) What is the return keyword used for 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.
24) What is “Call by Value” in Python?
In call-by-value, the argument whether an expression or a 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.
25) 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.
26) 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.
27) 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.
28) 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.
29) 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.
30) What is the difference between 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.
31) What is self-keyword in Python?
Self-keyword is used as the first parameter of a function inside a class that represents the instance of the class. The object or the instance of the class is automatically passed to the method that it belongs to and is received in the ‘self-keyword.’ Users can use another name for the first parameter of the function that catches the object of the class, but it is recommended to use ‘self-keyword’ as it is more of a Python convention.
32) What is the difference between append() and extend() methods?
Both append() and extend() methods are methods used to add elements at the end of a list.
append(element): Adds the given element at the end of the list that called this append() method
extend(another-list): Adds the elements of another list at the end of the list that called this extend() method
33) Is multiple inheritance supported in Python?
Yes, unlike Java, Python provides users with a wide range of support in terms of inheritance and its usage. Multiple inheritance refers to a scenario where a class is instantiated from more than one individual parent class. This provides a lot of functionality and advantages to users.