0% found this document useful (0 votes)
26 views

17 - Python Interview Last V

The document provides a table of contents covering various Python topics such as features, data types, operators, functions, classes and more with descriptions of each.

Uploaded by

xavi life
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

17 - Python Interview Last V

The document provides a table of contents covering various Python topics such as features, data types, operators, functions, classes and more with descriptions of each.

Uploaded by

xavi life
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 36

Projects Scrum Java Verbal Java Code Selenium Verbal SQL

Selenium Code Cucumber TestNG Rest Assured SOAP


Postman JMeter Maven Jenkins GitHub
Mobile Testing Python Verbal PyTest Python Code PyTest Code

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

What are the key features of Python?


Top
If it makes for an introductory language to programming, Python must mean something. These
are its qualities:

Interpreted
Dynamically typed
Object-oriented
Concise and simple
Free
Has a large community

What is Scope in Python?


Top
Every object in Python functions within a scope. A scope is a block of code where an object in
Python remains relevant. Namespaces uniquely identify all the objects inside a program.
However, these namespaces also have a scope defined for them where you could use their
objects without any prefix. A few examples of scope created during code execution in Python
are as follows:
• A local scope refers to the local objects available in the current function.
• A global scope refers to the objects available throught the code execution since their
inception.
• A module-level scope refers to the global objects of the current module accessible in
the program.
• An outermost scope refers to all the built-in names callable in the program. The
objects in this scope are searched last to find the name referenced.
Note: Local scope objects can be synced with global scope objects using keywords such as
global

Python collections (Arrays)


Top

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.

Differentiate between lists and tuples.


Top

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.

How to change tuple values


Top
Once a tuple is created, you cannot change its values. Tuples are unchangeable, or immutable
as it also is called.
But there is a workaround. You can convert the tuple into a list, change the list, and convert the
list back into a tuple.
How to check if item exits in tuple
Top

To determine if a specified item is present in a tuple use the <in> keyword:

How to create a tuple using one item


Top

Loop tuple (print tuple)


Top

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

Check if Item Exists in List


Top

How will you convert a list into a string?


Top

We will use the join() method for this.

How will you remove a duplicate element from a list?


Top

We can turn it into a set to do that.

Explain the ternary operator in Python


Top

We don’t have ?: in Python, but we have this:

[on true] if [expression] else [on false]


If the expression is True, the statement under [on true] is executed. Else, that under [on false] is
executed.

What are negative indices?


Top

A negative index, unlike a positive one, begins searching from the right.

This also helps with slicing from the back.

How would you convert a string into lowercase?


Top

Lower and upper method can be used.

Also, to check if a string is in all uppercase or all lowercase, we use the methods isupper() and
islower().

What is the pass statement in Python?


Top

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.

Why do we need break and continue in Python?


Top

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.

Explain help() and dir() functions in Python


Top

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

A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries


are written with curly brackets, and they have keys and values.

How to print keys in dictionary


Top
How to print values in dictionary
Top

Print key and values in dictionary


Top

Check if key exits in dictionary


Top

To determine if a specified key is present in a dictionary use the in keyword:


Dictionary methods
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 [].

How will you check if all characters in a string are alphanumeric?


Top

For this, we use the method isalnum().

How will you capitalize the first letter of a string?


Top
Simply using the method capitalize().
How do you find out which directory you are currently in?
Top

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

complex()- Creates a complex number.


filter()- Filters in items for which the condition is true.
format()- Lets us format a string.
hash()- Returns the hash value of an object.
hex()- Converts an integer to a hexadecimal.
input()- Reads and returns a line of string.
len()- Returns the length of an object.
locals()- Returns a dictionary of the current local symbol table.
open()- Opens a file.

Explain the //, %, and ** operators in Python.


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.

What do you know about relational operators in Python


Top
What are assignment operators in Python?
Top

Explain logical operators in Python.


Top
We have three logical operators- and, or, not.

What are membership operators?


Top

With the operators ‘in’ and ‘not in’, we can confirm if a value is a member in another.

Bitwise operators in Python.


Top

What data types does Python support?


Top
Numbers – Numbers use to hold numerical values.
Strings – A string is a sequence of characters. We declare it using single or double quotes.
Lists – A list is an ordered collection of values, and we declare it using square brackets.
Tuples – A tuple, like a list, is an ordered collection of values. The difference. However, is that a
tuple is immutable. This means that we cannot change a value in it.
Dictionary – A dictionary is a data structure that holds key-value pairs. We declare it using curly
braces.

What are the built-in types available in Python?


Top
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

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

How would you convert a string into an int in Python?


Top

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 “Call by Value” in Python?


Top
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.

What is “Call by Reference” in Python?


Top
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.

What is the purpose of id() function in Python?


Top
The id() is one of the built-in functions in Python.
It accepts one parameter and returns a unique identifier associated with the input object.
Does Python have a Main() method?
Top
The main() is the entry point function which happens to be called first in most programming
languages.
Since Python is interpreter-based, so it sequentially executes the lines of the code one-by-one.
Python also does have a Main() method. But it gets executed whenever we run our Python
script either by directly clicking it or starts it from the command line.
We can also override the Python default main() function using the Python if statement. Please
see the below code.

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.

What is the return value of the trunc() function?


Top
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.

What good is recursion?


Top

With recursion, we observe the following:

Need to put in less efforts.


Smaller code than that by loops.
Easier-to-understand code.

What does the function zip() do?


Top

zip() returns an iterator of tuples.

Explain Python List Comprehension.


Top
The list comprehension in python is a way to declare a list in one line of code. Let’s take a look
at one such example.

What if you want to toggle case for a Python string?


Top

We have the swapcase() method from the str class to do just that.

Write code to print only up to the letter t.


Top

Write code to print everything in the string except the spaces.


Top

Print this string five times in a row


Top
What is isalpha() in Python?
Top
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.

What is the purpose of bytes() in Python?


Top

bytes() is a built-in function in Python that returns an immutable bytes object

What is a control flow statement?


Top

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’}

How many arguments can the range() function take?


Top

The range() function in Python can take up to 3 arguments.


What is PEP 8?
Top

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

How do we execute Python?


Top

Python files first compile to bytecode. Then, the host executes them.

Explain Python’s parameter-passing mechanism.


Top

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.

What is the with statement in Python?


Top

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.

What makes Python object-oriented?


Top

Python is object-oriented because it follows the Object-Oriented programming paradigm. This


is a paradigm that revolves around classes and their instances (objects). With this kind of
programming, we have the following features:

Encapsulation
Abstraction
Inheritance
Polymorphism
Data hiding

How many types of objects does Python support?


Top
Objects in Python are mutable and immutable.
Immutable objects- Those which do not let us modify their contents. Examples of these will be
tuples, booleans, strings, integers, floats, and complexes. Iterations on such objects are faster.
Mutable objects – Those that let you modify their contents. Examples of these are lists, sets,
and dicts. Iterations on such objects are slower.

When is the else part of a try-except block executed?


Top

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.

What is the PYTHONPATH variable?


Top

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

join() lets us join characters from a string together by a character we specify.


split() lets us split a string around the character we specify. Python’s split() function works on
strings to cut a large piece into smaller chunks, or sub-strings. We can specify a separator to
start splitting, or it uses the space as one by default.

What does the Title() method do in Python?


Top
Python provides the title() method to convert the first letter in each word to capital format
while the rest turns to Lowercase.

map()
Top
Map applies a function to every element in an iterable.

What does the map() function do?


Top

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.

How do you open a file for writing?


Top

What is the different file-processing modes with Python?


Top

We have the following modes-

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’.

Differentiate between the append() and extend() methods of a list.


Top
The methods append() and extend() work on lists. While append() adds an element to the end
of the list, extend adds another list to the end of a list.

What are Errors and Exceptions in Python programs?


Top
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 which
interrupts the normal flow of the program.

Explain try, raise, and finally.


Top
These are the keywords we use with exception-handling. We put risky code under a try block,
use the raise statement to explicitly raise an error, and use the finally block to put code that we
want to execute anyway.
How do you handle exceptions with Try/Except/Finally in Python?
Top
Python lay down Try, Except, Finally constructs to handle errors as well as Exceptions. We
enclose the unsafe code indented under the try block. And we can keep our fall-back code
inside the except block. Any instructions intended for execution last should come under the
finally block.

How do you raise exceptions for a predefined condition in Python?


Top
We can raise an exception based on some condition.
For example, if we want the user to enter only odd numbers, else will raise an exception.

What happens if we do not handle an error in the except block?


Top

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

How will you convert an integer to a Unicode character?


Top

This is simple. All we need is the chr(x) built-in function.

Can you remove the whitespaces from the string “aaa bbb ccc ddd eee”?
Top

First way:

Second way:

Third way:

How would you randomize the contents of a list in-place?


Top

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

Does Python have a switch-case statement?


Top
Python, we do not have a switch-case statement. Here, you may write a switch function to use.
Else, you may use a set of if-elif-else statements. To implement a function for this, we may use
a dictionary.

Can I dynamically load a module in Python?


Top
Dynamic loading is where we do not load a module till we need it. This is slow, but lets us utilize
the memory more efficiently. In Python, you can use the importlib module for this:

What is a Python module?


Top
A module is a script in Python that defines import statements, functions, classes, and variables.
It also holds runnable Python code. ZIP files and DLL files can be modules too. The module holds
its name as a string that is in a global variable.
Which methods/functions do we use to determine the type of instance
and inheritance?
Top
We talk about three methods/functions- type(), isinstance(), and issubclass().
type(): This tells us the type of object we’re working with.
isinstance(): This takes in two arguments- a value and a type. If the value is of the kind of the
specified type, it returns True. Else, it returns False.
issubclass(): This takes two classes as arguments. If the first one inherits from the second, it
returns True. Else, it returns False.

Constructor and methods


Top
We must name a constructor in the name of the class; a method name can be anything.
Whenever we create an object, it executes a constructor; whenever we call a method, it
executes a method.
For one object, a constructor executes only once; a method can execute any number of times
for one object.
We use constructors to define and initialize non-static variables; we use methods to represent
business logic to perform operations.

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.

Explain inheritance in Python.


Top
Inheritance lets us reuse our code, and also makes it easier to create and maintain applications.
Python supports the following kinds of inheritance:

Single Inheritance- A class inherits from a single base class.


Multiple Inheritance- A class inherits from multiple base classes.
Multilevel Inheritance- A class inherits from a base class, which, in turn, inherits from another
base class.
Hierarchical Inheritance- Multiple classes inherit from a single base class.
Hybrid Inheritance- Hybrid inheritance is a combination of two or more types of inheritance.

What is Composition in Python?


Top
The composition is also a type of inheritance in Python. It intends to inherit from the base class
but a little differently, i.e., by using an instance variable of the base class acting as a member of
the derived class.

Explain memory management in Python.


Top
Objects and data structures in Python lie on a private heap. The Python memory manager
internally manages this. It delegates some work to object-specific allocators while ensuring they
operate only within the private heap. Actually, the interpreter manages this heap; the user has
no control over it- not even if they manipulate object pointers to memory blocks inside the
heap. The Python memory manager allocates heap space to objects and other internal buffers
on demand.

Explain garbage collection with Python.


Top
Python maintains a count of how many references there are to each object in memory
When a reference count drops to zero, it means the object is dead and Python can free the
memory it allocated to that object
The garbage collector looks for reference cycles and cleans them up
Python uses heuristics to speed up garbage collection
Recently created objects might as well be dead
The garbage collector assigns generations to each object as it is created
It deals with the younger generations first.
When you exit Python, is all memory deallocated?
Top
Exiting Python deallocates everything except:

modules with circular references


Objects referenced from global namespaces
Parts of memory reserved by the C library

Explain lambda expressions. When would you use one?


Top
When we want a function with a single expression, we can define it anonymously. A lambda
expression may take input and returns a value. To define the above function as a lambda
expression, we type the following code in the interpreter:

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.

Why and when do you use generators in Python?


Top
A generator in Python is a function which 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.

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 are Python Iterators?


Top
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.

What is the difference between an Iterator and Iterable?


Top
The collection type like a list, tuple, dictionary, and set are all iterable objects whereas they are
also iterable containers which return an iterator while traversing.
Here are some advanced-level Python interview questions.

What is the iterator protocol?


Top
The iterator protocol for Python declares that we must make use of two functions to build an
iterator- iter() and next().

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.

What do you mean by *args and **kwargs?


Top
In cases when we don’t know how many arguments will be passed to a function, like when we
want to pass a list or a tuple of values, we use *args.

**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.

What is the set object in Python?


Top
Sets are unordered collection objects in Python. They store unique and immutable objects.
Python has its implementation derived from mathematics.

What are Closures in Python?


Top
Python closures are function objects returned by another function. We use them to eliminate
code redundancy.
In the example below, we’ve written a simple closure for multiplying numbers.

What is the use of globals() function in Python?


Top
The globals() function in Python returns the current global symbol table as a dictionary object.
Python maintains a symbol table to keep all necessary information about a program. This info
includes the names of variables, methods, and classes used by the program.
All the information in this table remains in the global scope of the program and Python allows
us to retrieve it using the globals() method.

What are global, protected and private attributes in Python?


Top
• Global variables are public variables that are defined in the global scope. To use the
variable in the global scope inside a function, we use the global keyword.
• Protected attributes are attributes defined with a underscore prefixed to their
identifier eg. _sara. They can still be accessed and modified from outside the class
they are defined in but a responsible developer should refrain from doing so.
• Private attributes are attributes with double underscore prefixed to their identifier
eg. __ansh. They cannot be accessed or modified from the outside directly and will
result in an AttributeError if such an attempt is made.

What are Class or Static Variables in Python programming?


Top
In Python, all the objects share common class or static variables.
But the instance or non-static variables are altogether different for different objects.
The programming languages like C++ and Java need to use the static keyword to make a
variable as the class variable. However, Python has a unique way to declare a static variable.
All names initialized with a value in the class declaration becomes the class variables. And those
which get assigned values in the class methods becomes the instance variables.

What does the “self” keyword do?


Top
The self is a Python keyword which 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.

What does the yield keyword do in Python?


Top
The yield keyword can turn any function into a generator. It works like a standard return
keyword. But it’ll always return a generator object. Also, a method can have multiple calls to
the yield keyword.
See the example below.
What are the different methods to copy an object in Python (copy and
deepcopy)?
Top
There are two ways to copy objects in Python.
copy.copy() function
It makes a copy of the file from source to destination.
It’ll return a shallow copy of the parameter.
copy.deepcopy() function
It also produces the copy of an object from the source to destination.
It’ll return a deep copy of the parameter that you can pass to the function.

Which Python function will you use to convert a number to a string?


Top
For converting a number into a string, you can use the built-in function str(). If you want an
octal or hexadecimal representation, use the inbuilt function oct() or hex().

What is pickling and unpickling?


Top
Python library offers a feature - serialization out of the box. Serializing an object refers to
transforming it into a format that can be stored, so as to be able to deserialize it later on, to
obtain the original object. Here, the pickle module comes into play.
Pickling
Pickling is the name of the serialization process in Python. Any object in Python can be
serialized into a byte stream and dumped as a file in the memory. The process of pickling is
compact but pickle objects can be compressed further. Moreover, pickle keeps track of the
objects it has serialized and the serialization is portable across versions.
The function used for the above process is pickle.dump().
Unpickling
Unpickling is the complete inverse of pickling. It deserializes the byte stream to recreate the
objects stored in the file, and loads the object to memory.
The function used for the above process is pickle.load().
Note: Python has another, more primitive, serialization module called marshall, which exists
primarily to support .pyc files in Python and differs significantly from pickle.

What are unittests in Python?


Top
• unittest is a unit testing framework of Python.
• Unit testing means testing different components of software separately. Can you
think why unit testing is important? Imagine a scenario, you are building software
which uses three components namely A, B, and C. Now, suppose your software
breaks at a point time. How will you find which component was responsible for
breaking the software? Maybe it was component A that failed, which in turn failed
component B, and this actually failed the software. There can be many such
combinations.
• This is why it is necessary to test each and every component properly so that we
know which component might be highly responsible for the failure of the software.

You might also like