17 - Python Interview Last V
17 - Python Interview Last V
Python
Table of Contents
What are the key features of Python?.....................................................................................5
What is Scope in Python?........................................................................................................5
Python collections (Arrays)......................................................................................................6
Differentiate between lists and tuples.....................................................................................6
How to change tuple values....................................................................................................6
How to check if item exits in tuple...........................................................................................7
How to create a tuple using one item......................................................................................7
Loop tuple (print tuple)...........................................................................................................7
List..........................................................................................................................................7
Change an item in list..............................................................................................................8
Check if Item Exists in List........................................................................................................8
How will you convert a list into a string?.................................................................................8
How will you remove a duplicate element from a list?.............................................................8
Explain the ternary operator in Python....................................................................................8
What are negative indices?.....................................................................................................9
How would you convert a string into lowercase?.....................................................................9
What is the pass statement in Python?...................................................................................9
Why do we need break and continue in Python?.....................................................................9
Break and continue...............................................................................................................10
Will the do-while loop work if you don’t end it with a semicolon?.........................................10
Explain help() and dir() functions in Python...........................................................................10
What is dictionary?...............................................................................................................10
How to print keys in dictionary..............................................................................................10
How to print values in dictionary...........................................................................................11
Print key and values in dictionary..........................................................................................11
Check if key exits in dictionary...............................................................................................11
Dictionary methods...............................................................................................................12
What is slicing?.....................................................................................................................12
How will you check if all characters in a string are alphanumeric?.........................................12
How will you capitalize the first letter of a string?.................................................................12
How do you find out which directory you are currently in?....................................................13
Can you name ten built-in functions in Python and explain each in brief?..............................13
Explain the //, %, and ** operators in Python........................................................................13
What do you know about relational operators in Python......................................................13
What are assignment operators in Python?...........................................................................14
Explain logical operators in Python.......................................................................................14
What are membership operators?.........................................................................................14
Bitwise operators in Python..................................................................................................14
What data types does Python support?.................................................................................15
What are the built-in types available in Python?...................................................................15
What is a docstring?..............................................................................................................15
How would you convert a string into an int in Python?..........................................................15
How do you take input in Python?.........................................................................................16
What is a function?...............................................................................................................16
What is “Call by Value” in Python?........................................................................................16
What is “Call by Reference” in Python?.................................................................................16
What is the purpose of id() function in Python?.....................................................................17
Does Python have a Main() method?.....................................................................................17
What is recursion?.................................................................................................................17
What is the return value of the trunc() function?...................................................................17
What good is recursion?........................................................................................................17
What does the function zip() do?...........................................................................................17
Explain Python List Comprehension.......................................................................................18
What if you want to toggle case for a Python string?............................................................18
Write code to print only up to the letter t..............................................................................18
Write code to print everything in the string except the spaces...............................................18
Print this string five times in a row........................................................................................19
What is isalpha() in Python?..................................................................................................19
What is the purpose of bytes() in Python?.............................................................................19
What is a control flow statement?.........................................................................................19
Given the first and last names of all employees in your firm, what data type will you use to
store it?.................................................................................................................................19
How many arguments can the range() function take?...........................................................19
What is PEP 8?......................................................................................................................20
What is the best code you can write to swap two numbers?..................................................20
How do we execute Python?..................................................................................................20
Explain Python’s parameter-passing mechanism...................................................................20
What is the with statement in Python?..................................................................................20
What makes Python object-oriented?...................................................................................21
How many types of objects does Python support?.................................................................21
When is the else part of a try-except block executed?............................................................21
What is the PYTHONPATH variable?......................................................................................21
Explain join() and split() in Python.........................................................................................22
What does the Title() method do in Python?..........................................................................22
map()....................................................................................................................................22
What does the map() function do?........................................................................................22
filter()....................................................................................................................................22
reduce().................................................................................................................................22
Is del the same as remove()? What are they?........................................................................23
How do you open a file for writing?.......................................................................................23
What is the different file-processing modes with Python?.....................................................23
Differentiate between the append() and extend() methods of a list.......................................23
What are Errors and Exceptions in Python programs?...........................................................23
Explain try, raise, and finally.................................................................................................23
How do you handle exceptions with Try/Except/Finally in Python?.......................................24
How do you raise exceptions for a predefined condition in Python?.......................................24
What happens if we do not handle an error in the except block?...........................................25
Is there a way to remove the last object from a list?..............................................................25
How will you convert an integer to a Unicode character?......................................................25
Can you remove the whitespaces from the string “aaa bbb ccc ddd eee”?.............................25
How would you randomize the contents of a list in-place?....................................................25
What is the enumerate() function in Python?........................................................................26
How will you create the following pattern using Python? (steps stars)..................................26
Does Python have a switch-case statement?.........................................................................26
Can I dynamically load a module in Python?..........................................................................26
What is a Python module?.....................................................................................................27
Which methods/functions do we use to determine the type of instance and inheritance?.....27
Constructor and methods......................................................................................................27
What is __init__?..................................................................................................................27
Explain inheritance in Python................................................................................................28
What is Composition in Python?............................................................................................28
Explain memory management in Python...............................................................................28
Explain garbage collection with Python.................................................................................28
When you exit Python, is all memory deallocated?................................................................29
Explain lambda expressions. When would you use one?........................................................29
What are the principal differences between the lambda and def?.........................................29
What is a generator?.............................................................................................................29
Why and when do you use generators in Python?.................................................................30
What is an iterator?..............................................................................................................30
What are Python Iterators?...................................................................................................30
What is the difference between an Iterator and Iterable?......................................................30
What is the iterator protocol?...............................................................................................30
What is a decorator?.............................................................................................................31
What is Monkey Patching?....................................................................................................31
Why did you use config.py for this project on breast cancer classification?............................31
What do you mean by *args and **kwargs?.........................................................................31
How is Python thread safe?...................................................................................................32
What is the set object in Python?..........................................................................................32
What are Closures in Python?................................................................................................32
What is the use of globals() function in Python?....................................................................33
What are global, protected and private attributes in Python?...............................................34
What are Class or Static Variables in Python programming?.................................................34
What does the “self” keyword do?........................................................................................34
What does the yield keyword do in Python?..........................................................................35
What are the different methods to copy an object in Python (copy and deepcopy)?..............35
Which Python function will you use to convert a number to a string?....................................35
What is pickling and unpickling?...........................................................................................35
What are unittests in Python?...............................................................................................36
Python
Interpreted
Dynamically typed
Object-oriented
Concise and simple
Free
Has a large community
There are four collection data types in the Python programming language:
List is a collection which is ordered and changeable. Allows duplicate members.
Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
Set is a collection which is unordered and unindexed. No duplicate members.
Dictionary is a collection which is unordered, changeable and indexed. No duplicate members.
A tuple is a collection of values, and we declare it using parentheses. However, we can also use
tuple packing to do the same and unpacking to assign its values to a sequence of variables.
We don’t have arrays to work with in Python. Here, we have a list instead. List is created using
square brackets.
The major difference between tuples and lists is that a list is mutable, and a tuple is immutable.
This means that a list can be changed, but a tuple cannot.
We can store tuples in a list when we want to. Likewise, we can also use a tuple to store lists.
Use a tuple when you know what information goes in the container that it is. For example,
when you want to store a person’s credentials for your website.
But when you want to store similar elements, like in an array in Java, you should use a list.
List
Top
A list is a collection which is ordered and changeable. In Python lists are written with square
brackets. A list is mutable. when you want to store similar elements, like in an array in Java, you
should use a list.
Change an item in list
Top
A negative index, unlike a positive one, begins searching from the right.
Also, to check if a string is in all uppercase or all lowercase, we use the methods isupper() and
islower().
There may be times in our code when we haven’t decided what to do yet, but we must type
something for it to be syntactically correct. In such a case, we use the pass statement.
Both break and continue are statements that control flow in Python loops. break stops the
current loop from executing further and transfers the control to the next block. continue jumps
to the next iteration of the loop without exhausting it.
Break and continue
Top
Will the do-while loop work if you don’t end it with a semicolon?
Top
Python does not support an intrinsic do-while loop. Secondly, to terminate do-while loops is a
necessity for languages like Java.
The help() function displays the documentation string and help for its argument.
The dir() function displays all the members of an object(any kind).
What is dictionary?
Top
What is slicing?
Top
Slicing is a technique that allows us to retrieve only a part of a list, tuple, or string. For this, we
use the slicing operator [].
To find this, we use the function/method getcwd(). We import it from the module os.
Can you name ten built-in functions in Python and explain each in brief?
Top
The // operator performs floor division. It will return the integer part of the result on division.
Similarly, ** performs exponentiation. a**b returns the value of a raised to the power b.
Finally, % is for modulus. This gives us the value left after the highest achievable division.
With the operators ‘in’ and ‘not in’, we can confirm if a value is a member in another.
What is a docstring?
Top
A docstring is a documentation string that we use to explain what a construct does. We place it
as the first thing under a function, class, or a method, to describe what it does. We declare a
docstring using three sets of single or double-quotes
If a string contains only numerical characters, you can convert it into an integer using the int()
function.
How do you take input in Python?
Top
For taking input from the user, we have the function input(). In Python 2, we had another
function raw_input().
The input() function takes, as an argument, the text to be displayed for the task:
What is a function?
Top
When we want to execute a sequence of statements, we can give it a name. Let’s define a
function to take two numbers and return the greater number.
What is recursion?
Top
When a function makes a call to itself, it is termed recursion. But then, in order for it to avoid
forming an infinite loop, we must have a base condition.
We have the swapcase() method from the str class to do just that.
A Python program usually starts to execute from the first line. From there, it moves through
each statement just once and as soon as it’s done with the last statement, it transactions the
program. However, sometimes, we may want to take a more twisted path through the code.
Control flow statements let us disturb the normal execution flow of a program and bend it to
our will.
Given the first and last names of all employees in your firm, what data
type will you use to store it?
Top
I can use a dictionary to store that. It would be something like this-
{‘first_name’:’Ayushi’,’second_name’:’Sharma’}
PEP 8 is a coding convention that lets us write more readable code. In other words, it is a set of
recommendations.
What is the best code you can write to swap two numbers?
Top
Python files first compile to bytecode. Then, the host executes them.
To pass its parameters to a function, Python uses pass-by-reference. If you change a parameter
within a function, the change reflects in the calling function. This is its default behavior.
However, when we pass literal arguments like strings, numbers, or tuples, they pass by value.
This is because they are immutable.
The with statement in Python ensures that cleanup code is executed when working with
unmanaged resources by encapsulating common preparation and cleanup tasks. It may be used
to open a file, do something, and then automatically close the file at the end. It may be used to
open a database connection, do some processing, then automatically close the connection to
ensure resources are closed and available for others. with will clean up the resources even if an
exception is thrown. This statement is like the using statement in C#.
Consider you put some code in a try block, then in the finally block, you close any resources
used.
Encapsulation
Abstraction
Inheritance
Polymorphism
Data hiding
In an if-else block, the else part is executed when the condition in the if-statement is False. But
with a try-except block, the else part executes only if no exception is raised in the try part.
PYTHONPATH is the variable that tells the interpreter where to locate the module files
imported into a program. Hence, it must include the Python source library directory and the
directories containing Python source code. You can manually set PYTHONPATH, but usually, the
Python installer will preset it.
Explain join() and split() in Python.
Top
map()
Top
Map applies a function to every element in an iterable.
map() executes the function we pass to it as the first argument; it does so on all elements of the
iterable in the second argument.
filter()
Top
Filter lets us filter in some values based on conditional logic.
reduce()
Top
Reduce repeatedly reduces a sequence pair-wise until we reach a single value.
Is del the same as remove()? What are they?
Top
del and remove() are methods on lists/ ways to eliminate elements.
While del lets us delete an element at a certain index, remove() lets us remove an element by
its value.
read-only – ‘r’
write-only – ‘w’
read-write – ‘rw’
append – ‘a’
We can open a text file with the option ‘t’. So, to open a text file to read it, we can use the
mode ‘rt’. Similarly, for binary files, we use ‘b’.
If we don’t do this, the program terminates. Then, it sends an execution trace to sys.stderr.
Is there a way to remove the last object from a list?
Top
Can you remove the whitespaces from the string “aaa bbb ccc ddd eee”?
Top
First way:
Second way:
Third way:
Leading whitespace in a string is the whitespace in a string before the first non-whitespace
character. To remove it from a string, we use the method rstrip().
What is the enumerate() function in Python?
Top
enumerate() iterates through a sequence and extracts the index position and its corresponding
value too.
How will you create the following pattern using Python? (steps stars)
Top
What is __init__?
Top
__init__ is a contructor method in Python and is automatically called to allocate memory when
a new object/instance is created. All classes have a __init__ method associated with them. It
helps in distinguishing methods and attributes of a class from local variables.
What are the principal differences between the lambda and def?
Top
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.
What is a generator?
Top
Python generator produces a sequence of values to iterate on. This way, it is kind of an iterable.
We define a function that ‘yields’ values one by one, and then use a for loop to iterate on it.
What is an iterator?
Top
An iterator returns one object at a time to iterate on. To create an iterator, we use the iter()
function.
odds=iter([1,3,5,7,9])
Then, we call the next() function on it every time we want an object.
What is a decorator?
Top
A decorator is a function that adds functionality to another function without modifying it. It
wraps another function to add functionality to it.
What is Monkey Patching?
Top
Monkey patching refers to modifying a class or module at runtime (dynamic modification). It
extends Python code at runtime.
Why did you use config.py for this project on breast cancer
classification?
Top
I created a config file for this project to keep every setting at one place. This made it easy to
change the settings once and for all. This held the path to the input dataset, and the base path.
It also held the relative paths to the training, validation, and testing sets.
**kwargs takes keyword arguments when we don’t know how many there will be.
How is Python thread safe?
Top
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.