Python Interview questions and answers for experienced


1. What is a dictionary in Python?

A python dictionary is something I have never seen in other languages like C++ or Java programming. It holds key-value pairs.

>>> roots={25:5,16:4,9:3,4:2,1:1}
>>> type(roots) - Output: <class ‘dict’>

>>> roots[9] - Output: 3

A dictionary is mutable, and we can also use a comprehension to create it.

>>> roots={x**2 for x in range(5,0,-1)}
>>> roots
{25: 5, 16: 4, 9: 3, 4: 2, 1: 1}


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

The // operator performs floor division. It will return the integer part of the result on division.

>>> 7//2 - Output: 3

Normal division would return 3.5 here.

Similarly, ** performs exponentiation. a**b returns the value of a raised to the power b.

>>> 2**10 - Output: 1024

Finally, % is for modulus. This gives us the value left after the highest achievable division.

>>> 13%7 - Output: 6
>>> 3.5%1.5 - Output: 0.5


3. What do you know about relational operators in Python. 

Relational operators compare values.

Less than (<) If the value on the left is lesser, it returns True.

>>> 'hi'<'Hi' - Output: False

Greater than (>) If the value on the left is greater, it returns True.

>>> 1.1+2.2>3.3 - Output: True

This is because of the flawed floating-point arithmetic in Python, due to hardware dependencies.

Less than or equal to (<=) If the value on the left is lesser than or equal to, it returns True.

>>> 3.0<=3 - Output: True

Greater than or equal to (>=) If the value on the left is greater than or equal to, it returns True.

>>> True>=False - Output: True

Equal to (==) If the two values are equal, it returns True.

>>> {1,3,2,2}=={1,2,3} - Output: True

Not equal to (!=) If the two values are unequal, it returns True.

>>> True!=0.1 - Output: True

>>> False!=0.1 - Output: True


4. Explain logical operators in Python.

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

>>> False and True - Output: False

>>> 7<7 or True - Output: True

>>> not 2==2 - Output: False

5. What are membership operators?

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

>>> 'me' in 'disappointment' - Output: True

>>> 'us' not in 'disappointment' - Output: True


6. Explain identity operators in Python.

The operators ‘is’ and ‘is not’ tell us if two values have the same identity.

>>> 10 is '10' - Output: False

>>> True is not False - Output: True


7. What data types does Python support?

Python provides us with five kinds of data types:

Numbers – Numbers use to hold numerical values.

>>> a=7.0

Strings – A string is a sequence of characters. We declare it using single or double quotes.

>>> title="Ayushi's Book"

Lists – A list is an ordered collection of values, and we declare it using square brackets.

>>> colors=['red','green','blue']
>>> type(colors)

Output: <class ‘list’>

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.

>>> name=('Ayushi','Sharma')
>>> name[0]='Avery'

Traceback (most recent call last):

File “<pyshell#129>”, line 1, in <module>

name[0]=’Avery’

TypeError: ‘tuple’ object does not support item assignment

Dictionary – A dictionary is a data structure that holds key-value pairs. We declare it using curly braces.

>>> squares={1:1,2:4,3:9,4:16,5:25}
>>> type(squares)
<class ‘dict’>

>>> type({})
<class ‘dict’>

We can also use a dictionary comprehension:

>>> squares={x:x**2 for x in range(1,6)}
>>> squares
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}



8. What is a docstring?

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.

>>> def sayhi():

Output:

"""
The function prints Hi
"""

print("Hi")
>>> sayhi() - Output: Hi

To get a function’s docstring, we use its __doc__ attribute.

>>> sayhi.__doc__
‘\n\tThis function prints Hi\n\t’

A docstring, unlike a comment, is retained at runtime.



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

If a string contains only numerical characters, you can convert it into an integer using the int() function.

>>> int('227') - Output: 227

Let’s check the types:

>>> type('227') - Output: <class ‘str’>

>>> type(int('227')) - Output: <class ‘int’>


10. How do you take input in Python?

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:

>>> a=input('Enter a number')
Enter a number 7

But if you have paid attention, you know that it takes input in the form of a string.

>>> type(a)
<class ‘str’>

Multiplying this by 2 gives us this:

>>> a*=2
>>> a
’77’

So, what if we need to work on an integer instead?

We use the int() function for this.

>>> a=int(input('Enter a number'))
Enter a number7

Now when we multiply it by 2, we get this:

>>> a*=2
>>> a
14


11. What is a function?

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.

>>> def greater(a,b):
return a is a>b else b

>>> greater(3,3.5)
3.5


12. What is recursion?

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.

Let’s take an example.

>>> def facto(n):
if n==1: return 1
return n*facto(n-1)

>>> facto(4)
24


13. What does the function zip() do?

One of the less common functions with beginners, zip() returns an iterator of tuples.

>>> list(zip(['a','b','c'],[1,2,3]))
[(‘a’, 1), (‘b’, 2), (‘c’, 3)]

Here, it pairs items from the two lists and creates tuples with those. But it doesn’t have to be lists.

>>> list(zip(('a','b','c'),(1,2,3)))
[(‘a’, 1), (‘b’, 2), (‘c’, 3)]


14. How do you calculate the length of a string?

This is simple. We call the function len() on the string we want to calculate the length of.

>>> len('Ayushi Sharma') - Output: 13


15. Explain Python List Comprehension.

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.

>>> [i for i in range(1,11,2)] - Output: [1, 3, 5, 7, 9]

>>> [i*2 for i in range(1,11,2)] - Output: [2, 6, 10, 14, 18]


16. How do you get all values from a Python dictionary?

We saw previously, to get all keys from a dictionary, we make a call to the keys() method. Similarly, for values, we use the method values().

>>> 'd' in {'a':1,'b':2,'c':3,'d':4}.values() - Output: False

>>> 4 in {'a':1,'b':2,'c':3,'d':4}.values() - Output: True


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

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

>>> 'AyuShi'.swapcase() - Output: ‘aYUsHI’

Let’s apply some concepts now, shall we? Questions 50 through 52 assume the string ‘I love Python’. You need to do the needful.


18. Write code to print only upto the letter t.

>>> i=0
>>> while s[i]!='t':
print(s[i],end=’’)
i+=1
I love Py


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

>>> for i in s:
if i==' ': continue
print(i,end='')

IlovePython


20. What is the purpose of bytes() in Python?

bytes() is a built-in function in Python that returns an immutable bytes object. Let’s take an example.

>>> bytes([2,4,8]) - Output: b’\x02\x04\x08′

>>> bytes(5) - Output: b’\x00\x00\x00\x00\x00′

>>> bytes('world','utf-8') - Output: b’world’


21. What is a control flow statement?

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.


22. Create a new list to convert the following list of number strings to a list of numbers.

nums=[‘22’,’68’,’110’,’89’,’31’,’12’]

We will use the int() function with a list comprehension to convert these strings into integers and put them in a list.

>>> [int(i) for i in nums]
[22, 68, 110, 89, 31, 12]


23. Given the first and last names of all employees in your firm, what data type will you use to store it?

I can use a dictionary to store that. It would be something like this-

{‘first_name’:’Ayushi’,’second_name’:’Sharma’


24. How would you work with numbers other than those in the decimal number system?

With Python, it is possible to type numbers in binary, octal, and hexadecimal.

Binary numbers are made of 0 and 1. To type in binary, we use the prefix 0b or 0B.

>>> int(0b1010) - Output: 10

To convert a number into its binary form, we use bin().

>>> bin(0xf) - Output: ‘0b1111’

Octal numbers may have digits from 0 to 7. We use the prefix 0o or 0O.

>>> oct(8) - Output: ‘0o10’

Hexadecimal numbers may have digits from 0 to 15. We use the prefix 0x or 0X.

>>> hex(16) - Output: ‘0x10’

>>> hex(15) - Output: ‘0xf’


25. What does the following code output?

>>> def extendList(val, list=[]):
list.append(val)
return list

>>> list1 = extendList(10)
>>> list2 = extendList(123,[])
>>> list3 = extendList('a')
>>> list1,list2,list3

([10, ‘a’], [123], [10, ‘a’])

You’d expect the output to be something like this:

([10],[123],[‘a’])

Well, this is because the list argument does not initialize to its default value ([]) every time we make a call to the function. Once we define the function, it creates a new list. Then, whenever we call it again without a list argument, it uses the same list. This is because it calculates the expressions in the default arguments when we define the function, not when we call it.

26. How many arguments can the range() function take?

The range() function in Python can take up to 3 arguments. Let’s see this one by one.

a. One argument

When we pass only one argument, it takes it as the stop value. Here, the start value is 0, and the step value is +1.

>>> list(range(5)) - Output: [0, 1, 2, 3, 4]

>>> list(range(-5)) - Output: []

>>> list(range(0)) - Output: []

b. Two arguments

When we pass two arguments, the first one is the start value, and the second is the stop value.

>>> list(range(2,7)) - Output: [2, 3, 4, 5, 6]

>>> list(range(7,2)) - Output: []

>>> list(range(-3,4)) - Output: [-3, -2, -1, 0, 1, 2, 3]

c. Three arguments

Here, the first argument is the start value, the second is the stop value, and the third is the step value.

>>> list(range(2,9,2)) - Output: [2, 4, 6, 8]

>>> list(range(9,2,-1)) - Output: [9, 8, 7, 6, 5, 4, 3]


27. What is PEP 8?

PEP 8 is a coding convention that lets us write more readable code. In other words, it is a set of recommendations.

28. How is Python different from Java?

Following is the comparison of Python vs Java –

  • Java is faster than Python
  • Python mandates indentation. Java needs braces.
  • Python is dynamically-typed; Java is statically typed.
  • Python is simple and concise; Java is verbose
  • Python is interpreted
  • Java is platform-independent
  • Java has stronger database-access with JDBC


29. What is the best code you can write to swap two numbers?

I can perform the swapping in one statement.

>>> a,b=b,a
Here’s the entire code, though-

>>> a,b=2,3
>>> a,b=b,a
>>> a,b
(3, 2)


30. How can you declare multiple assignments in one statement?

This is one of the most asked interview questions for Python freshers –

There are two ways to do this:

First –
>>> a,b,c=3,4,5 #This assigns 3, 4, and 5 to a, b, and c respectively

Second –
>>> a=b=c=3 #This assigns 3 to a, b, and c


31. If you are ever stuck in an infinite loop, how will you break out of it?

For this, we press Ctrl+C. This interrupts the execution. Let’s create an infinite loop to demonstrate this.

>>> def counterfunc(n):
while(n==7):print(n)

>>> counterfunc(7)
7
7
7
7
7
7
7
7
7
7
7
7
7
7
7
7
7

Traceback (most recent call last):

File “<pyshell#332>”, line 1, in <module>

counterfunc(7)

File “<pyshell#331>”, line 2, in counterfunc

while(n==7):print(n)

KeyboardInterrupt


32.  How do we execute Python?

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


33. Explain Python’s parameter-passing mechanism.

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.


34. What is the with statement in Python?

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 cleanup 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. The with statement is like syntactic sugar for that.

The syntax of this control-flow structure is:

with expression [as variable]:
….with-block

>>> with open('data.txt') as data:
#processing statements


35. How is a .pyc file different from a .py file?

While both files hold bytecode, .pyc is the compiled version of a Python file. It has platform-independent bytecode. Hence, we can execute it on any platform that supports the .pyc format. Python automatically generates it to improve performance(in terms of load time, not speed).


36. What makes Python object-oriented?

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

37. How many types of objects does Python support?

Objects in Python are mutable and immutable. Let’s talk about these.

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.

>>> tuple=(1,2,4)
>>> tuple - Output: (1, 2, 4)

>>> 2+4j - Output: (2+4j)

Mutable objects – Those that let you modify their contents. Examples of these are lists, sets, and dicts. Iterations on such objects are slower.

>>> [2,4,9] - Output: [2, 4, 9]

>>> dict1={1:1,2:2}
>>> dict1 - Output: {1: 1, 2: 2}

While two equal immutable objects’ reference variables share the same address, it is possible to create two mutable objects with the same content.



Comments

Post a Comment

Popular posts from this blog

Create Desktop Application with PHP

Insert pandas dataframe into Mongodb

Add and delete columns dynamically in an HTML table