by BehindJava

Python Interview Questions Part 2

Home » python » Python Interview Questions Part 2

In this tutorial we are going to see important Python Interview Questions.

Q. What are the key features of Python?

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

Q. Explain the ternary operator in Python.

Unlike C++, 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.

Below is how you would use it: ex 1.

a,b=2,3
min=a if a<b else b
print(min)

Ans: 2

ex 2.

print("Hi") if a<b else print("Bye")

Ans: Hi

Q. What is multithreading? Give an example.

It means running several different programs at the same time concurrently by invoking multiple threads. Multiple threads within a process refer the data space with main thread and they can communicate with each other to share information more easily.Threads are light-weight processes and have less memory overhead. Threads can be used just for quick task like calculating results and also running other processes in the background while the main program is running.

  • Thread Is a functionality or logic which can execute simultaneously along with the other part of the program.
  • Thread is a light weight process.
  • Any program which is under execution is known as process.
  • We can define the threads in python by overwriting run method of thread class.
  • Thread class is a predefined class which is defined in threading module.
  • Thread in module is a predefined module.
  • If we call the run method directly the logic of the run method will be executed as a normal method logic.
  • In order to execute the logic of the run method as a we use start method of thread class. Example

    import threading
    class x (threading.Thread):
      def run(self):
         for p in range(1, 101):
              print(p)
    class y (threading.Thread):
      def run(self):
           for q in range(1, 101):
              print(q)
    x1=x()
    y1=y()
    x1.start()
    y1.start()

    A thread is a lightweight process and multithreading allows us to execute multiple threads at once. As you know, Python is a multithreaded language. It has a multithreading package. The GIL (Global Interpreter Lock) ensures that a single thread executes at a time. A thread holds the GIL and does a little work before passing it on to the next thread. This makes for an illusion of parallel execution. But in reality, it is just threaded taking turns at the CPU. Of course, all the passing around adds overhead to the execution.

Q. Explain help() and dir() functions in Python.

The help() function displays the documentation string and help for its argument.

import copy
help(copy.copy)
Help on function copy in module copy: copy(x)
Shallow copy operation on arbitrary Python objects.
See the module's doc string for more info.
The dir() function displays all the members of an object(any kind).

dir(copy.copy)

['__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']

Dictionary

Q. What is a dictionary in Python?

The built-in datatypes in Python is called dictionary. It defines one-to-one relationship between keys and values. Dictionaries contain pair of keys and their corresponding values. Dictionaries are indexed by keys.

Let’s take an example:

The following example contains some keys. Country, Capital & PM. Their corresponding values are India, Delhi and Modi respectively.

dict={'Country':'India','Capital':'Delhi','PM':'Modi'}

print dict[Country]

roots={25:5,16:4,9:3,4:2,1:1}
type(roots)
<class 'dict;>

roots[9]
3

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

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

Q. How do you get a list of all the keys in a dictionary?

Be specific in these type of Python Interview Questions and Answers.

For this, we use the function keys().

mydict={'a':1,'b':2,'c':3,'e':5}
mydict.keys()
print(dict_keys)
(['a', 'b', 'c', 'e'])

Q. Write Python logic to count the number of capital letters in a file.

import os
os.chdir('C:\\Users\\lifei\\Desktop')
with open('Today.txt') as today:
    count = 0
    for i in today.read():
        if i.isupper():
            count+=1
    print(count)
26

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

For this, we’ll import the function shuffle() from the module random.

from random import shuffle
shuffle(mylist)
mylist
[3, 4, 8, 0, 5, 7, 6, 2, 1]

Q. Explain join() and split() in Python.

.join([]) It takes any iterables into this method. Join method is used to concatenate the elements of any list. join() lets us join characters from a string together by a character we specify.

','.join('12345')
'1,2,3,4,5'

split() lets us split a string around the character we specify.

'1,2,3,4,5'.split(',')
['1', '2', '3', '4', '5']

Q. Is Python case-sensitive?

A language is case-sensitive if it distinguishes between identifiers like myname and Myname. In other words, it cares about case- lowercase or uppercase. Let’s try this with Python.

myname='Ramayan'
Myname
Traceback (most recent call last):
File "<pyshell#3>", line 1, in  Myname
NameError: name 'Myname' is not defined

As you can see, this raised a NameError. This means that Python is indeed case-sensitive.

Q.How long can an identifier be in Python?

In Python, an identifier can be of any length. Apart from that, there are certain rules we must follow to name one:

  • It can only begin with an underscore or a character from A-Z or a-z.
  • The rest of it can contain anything from the following: A-Z/a-z/_/0-9.
  • Python is case-sensitive, as we discussed in the previous question.
  • Keywords cannot be used as identifiers.

Python has the following keywords:

  • and def False import not True
  • as del finally in or try
  • assert elif for is pass while
  • break else from lambda print with
  • class except global None raise yield
  • continue exec if nonlocal return

Q. How do you remove the leading whitespace in a string?

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 lstrip().

'   Ram '.lstrip()
'Ram   '

As you can see, this string had both leading and trailing whitespaces. lstrip() stripped the string of the leading whitespace. If we want to strip the trailing whitespace instead, we use rstrip().

'   Ram '.rstrip()
'   Ram'

Q.How would you convert a string into lowercase? We use the lower() method for this.

'Ramayan'.lower()
'ramayan'

To convert it into uppercase, then, we use upper().

'Ramayan'.upper()
'RAMAYAN'

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

'Ramayan'.isupper()
False

'Ramayan'.isupper()
True

'Ramayan'.islower()
True

'$hrir@m'.islower()
True

'$HRIR@M'.isupper()
True

So, characters like @ and $ will suffice for both cases.

Also, istitle() will tell us if a string is in title case.

'Arrested Development'.istitle()
True

Q. What is the pass statement in Python?

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.

def func(*args):
    pass 

Similarly, the break statement breaks out of a loop.

for i in range(7):
    if i==3: break
        print(i)
0
1
2

Finally, the continue statement skips to the next iteration.

for i in range(7):
    if i==3: continue
        print(i)
0
1
2
4
5
6

Q. What is a closure in Python?

A closure is said to occur when a nested function references a value in its enclosing scope. The whole point here is that it remembers the value.

def A(x):
    def B():
        print(x)
    return B

A(7)()
7

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

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

7//2
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
1024

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

13 % 7
6

3.5 % 1.5
0.5

Q. How many kinds of operators do we have in Python? Explain arithmetic operators.

This type of Python Interview Questions and Answers can decide your knowledge in Python. Answer the Python Interview Questions with some good Examples.

Here in Python, we have 7 kinds of operators: arithmetic, relational assignment, logical, membership, identity, and bitwise.

We have seven arithmetic operators. These allow us to perform arithmetic operations on values:

Addition (+) This adds two values.

7+8
7-8
7*8
7/8  # 0.875
7//8 # 0

Q. Explain relational operators in Python.

Relational operators compare values.

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

'hi'<'Hi'
False

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

 1.1 + 2.2 > 3.3
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
True

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

 True >= False
True

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

 {1,3,2,2} == {1,2,3}
True

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

 True!=0.1
True

 False!=0.1
True

Q. What are assignment operators in Python?

This one is an Important Interview question in Python Interview.

We can combine all arithmetic operators with the assignment symbol.

 a = 7
 a += 1
 a
8

 a -= 1
 a
7

 a*=2
 a
14

 a/=2
 a
7.0

 a**=2
 a
49.0

 a//=3
 a
16.0

 a%=4
 a
0.0

Q. Explain logical operators in Python.

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

 False and True
False

 7<7 or True
True

 not 2==2
False

Q. 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'
True

'us' not in 'disappointment'
True

Q. Explain identity operators in Python.

This is one of the very commonly asked Python Interview Questions and answers it with examples. The operators ‘is’ and ‘is not’ tell us if two values have the same identity.

10 is '10'
False

True is not False
True

Q. Finally, tell us about bitwise operators in Python.

These operate on values bit by bit.

AND (&) This performs & on each bit pair.

 0b110 & 0b010
2

OR (|) This performs | on each bit pair.

 3|2
3

XOR (^) This performs an exclusive-OR operation on each bit pair.

 3^2
1

Binary One's Complement (~) This returns the one's complement of a value.

 ~2
-3

Binary Left-Shift (<<) This shifts the bits to the left by the specified amount.

 1<<2
4

Here, 001 was shifted to the left by two places to get 100, which is binary for 4.

Binary Right-Shift (>>)

 4>>2
1

For more insight on operators, refer to Operators in Python.

Q. 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)
10

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

 bin(0xf)
'0b1111'

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

 oct(8)
'0o10'

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

 hex(16)
'0x10'

 hex(15)
'0xf'

Q. Why are identifier names with a leading underscore disparaged?

Since Python does not have a concept of private variables, it is a convention to use leading underscores to declare a variable private. This is why we mustn’t do that to variables we do not want to make private.

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

There are two ways to do this:

     a,b,c=3,4,5     #This assigns 3, 4, and 5 to a, b, and c resp.
     a = b = c =3         #This assigns 3 to a, b, and c

Q. What is tuple unpacking?

First, let’s discuss tuple packing. It is a way to pack a set of values into a tuple.

mytuple=3,4,5
mytuple
(3, 4, 5)

This packs 3, 4, and 5 into mytuple.

Now, we will unpack the values from the tuple into variables x, y, and z.

x,y,z=mytuple
x+y+z

Q. What data types does Python support?

Python provides us with five kinds of data types:

     a=7.0
     title="Ramayan's Book"
     colors=['red','green','blue']
     type(colors)
        <class 'list'>
     name=('Ramayan','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
     squares={1:1,2:4,3:9,4:16,5:25}
     type(squares)
        <class 'dict'>
     type({})
        <class 'dict'>
     squares={x:x**2 for x in range(1,6)}
     squares
        {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Q. 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():
    """
    The function prints Hi
    """
    print("Hi")

sayhi()
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.

Q. What is the PYTHONPATH variable?

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.

Q. What is slicing?

These are the types of basic Python interview questions for freshers.

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

     (1,2,3,4,5)[2:4]
        (3, 4)
     [7,6,8,5,9][2:]
        [8, 5, 9]
     'Hello'[:-1]
        'Hell'

Q. What is a namedtuple?

A namedtuple will let us access a tuple’s elements using a name/label. We use the function namedtuple() for this, and import it from collections.

 from collections import namedtuple
 result=namedtuple('result','Physics Chemistry Maths') #format
 Ramayan=result(Physics=86,Chemistry=95,Maths=86) #declaring the tuple
 Ramayan.Chemistry
95

As you can see, it let us access the marks in Chemistry using the Chemistry attribute of object Ramayan.

Q. How would you declare a comment in Python?

Unlike languages like C++, Python does not have multiline comments. All it has is octothorpe (#). Anything following a hash is considered a comment, and the interpreter ignores it.

 #line 1 of comment
 #line 2 of comment

In fact, you can place a comment anywhere in your code. You can use it to explain your code.

Q. 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')
227

Let’s check the types:

 type('227')
<class 'str'>

 type(int('227'))
<class 'int'>

Q. How do you take input in Python?

For taking input from 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 number7

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

Q. What is a frozen set in Python?

Answer these type of Python Interview Questions with Examples.

First, let’s discuss what a set is. A set is a collection of items, where there cannot be any duplicates. A set is also unordered.

 myset={1,3,2,2}
 myset
{1, 2, 3}

This means that we cannot index it.

 myset[0]
Traceback (most recent call last):
File "<pyshell#197>", line 1, in  myset[0]
TypeError: 'set' object does not support indexing

However, a set is mutable. A frozen set is immutable. This means we cannot change its values. This also makes it eligible to be used as a key for a dictionary.

 myset=frozenset([1,3,2,2])
 myset
frozenset({1, 2, 3})

 type(myset)
<class 'frozenset'>

Q. How would you generate a random number in Python?

This kind of Python interview Questions and Answers can Prove your depth of knowledge.

To generate a random number, we import the function random() from the module random.

 from random import random
 random()
0.7931961644126482

Let’s call for help on this.

 help(random)

Help on built-in function random:

random() method of random.Random instance

random() -> x in the interval [0, 1).

This means that it will return a random number equal to or greater than 0, and less than 1.

We can also use the function randint(). It takes two arguments to indicate a range from which to return a random integer.

     from random import randint
     randint(2,7)
6

     randint(2,7)
5

 randint(2,7)
7

 randint(2,7)
6

 randint(2,7)
2

Q. How will you capitalize the first letter of a string?

Simply using the method capitalize().

 'Ramayan'.capitalize()
'Ramayan'

 type(str.capitalize)
<class 'method_descriptor'>

However, it will let other characters be.

 '$hrir@m'.capitalize()
'$HRIR@M'

*Q. How will you check if all characters in a string are alphanumeric? * For this, we use the method isalnum().

 'Ramayan123'.isalnum()
True

 'Ramayan123!'.isalnum()
False

Other methods that we have include:

 '123.3'.isdigit()
False

 '123'.isnumeric()
True

 'Ramayan'.islower()
True

 'Ramayan'.isupper()
False

 'Ramayan'.istitle()
True

 '   '.isspace()
True

 '123F'.isdecimal()
False

Q. What is the concatenation?

This is very basic Python Interview Question, try not to make any mistake in this.

Concatenation is joining two sequences. We use the + operator for this.

 '32'+'32'
'3232'

 [1,2,3]+[4,5,6]
[1, 2, 3, 4, 5, 6]

 (2,3)+(4)
Traceback (most recent call last):
File "<pyshell#256>", line 1, in <module> (2,3)+(4)
TypeError: can only concatenate tuple (not "int") to tuple

Here, 4 is considered an int. Let's do this again.

 (2,3)+(4,)  # (obj,) is way to declare single empty
(2, 3, 4)

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

You can create your own function or use one of Python’s many built-in functions.

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

Q. 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)]

Q. 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
.
.
.
.
.
Traceback (most recent call last):
File "<pyshell#332>", line 1, in  counterfunc(7)
File "<pyshell#331>", line 2, in counterfunc
while(n==7):print(n)
KeyboardInterrupt

Q. With Python, how do you find out which directory you are currently in?

To find this, we use the function/method getcwd(). We import it from the module os.

 import os
 os.getcwd()
'C:\Users\lifei\AppData\Local\Programs\Python\Python36-32'

 type(os.getcwd)
<class 'builtin_function_or_method'>

We can also change the current working directory with chdir().

 os.chdir('C:\\Users\\lifei\\Desktop')
 os.getcwd()
'C:\Users\lifei\Desktop'

Q. How will you find, in a string, the first word that rhymes with ‘cake’?

For our purpose, we will use the function search(), and then use group() to get the output.

 import re
 rhyme=re.search('.ake','I would make a cake, but I hate to bake')
 rhyme.group()
'make'

And as we know, the function search() stops at the first match. Hence, we have our first rhyme to ‘cake’.

Q. What is Tkinter?

Tkinter is a famous Python library with which you can craft a GUI. It provides support for different GUI tools and widgets like buttons, labels, text boxes, radio buttons, and more. These tools and widgets have attributes like dimensions, colors, fonts, colors, and more.

You can also import the tkinter module.

 import tkinter
 top=tkinter.Tk()

This will create a new window for you:

This creates a window with the title ‘My Game’. You can position your widgets on this.

Follow this link to know more about Python Libraries

Q. 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).

Q. 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('Adi Shakara')
Q. 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
Ans. ([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.

Let’s revise the Basis of Python Programming

Q. What is a decorator? How do I define my own?

Ans. A decorator is a function that adds functionality to another function without modifying it. It wraps another function to add functionality to it. A Python decorator is a specific change that we make in Python syntax to alter functions easily.

def decor(func):
    def wrap():
        print("$$$$$$$$$$$$$$$$$")
        func()
            print("$$$$$$$$$$$$$$$$$")
    return wrap

@decor
def sayhi():
    print("Hi")

sayhi()
$$$$$$$$$$$$$$$$$
Hi
$$$$$$$$$$$$$$$$$

Decorators are an example of metaprogramming, where one part of the code tries to change another. For more on decorators, read Python Decorators.

Q. Why use function decorators? Give an example.

A decorator is essentially a callable Python object that is used to modify or extend a function or class definition.

One of the beauties of decorators is that a single decorator definition can be applied to multiple functions (or classes). Much can thereby be accomplished with decorators that would otherwise require lots of boilerplate (or even worse redundant!) code.

Flask, for example, uses decorators as the mechanism for adding new endpoints to a web application. Examples of some of the more common uses of decorators include adding synchronization, type enforcement,logging, or pre/post conditions to a class or function.

Basic Python Programming Interview Questions Below are some Basic Python Programming Interview Questions and answers for freshers.

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

Ans. 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))
[0, 1, 2, 3, 4]

 list(range(-5))
[]

 list(range(0))
[]

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))
[2, 3, 4, 5, 6]

 list(range(7,2))
[]

 list(range(-3,4))
[-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))
[2, 4, 6, 8]

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

Q. How do you debug a program in Python? Answer in brief.

Ans. To debug a Python program, we use the module. This is the Python debugger; we will discuss it in a tutorial soon. If we start a program using pdb, it will let us step through the code.

Q. List some pdb commands.

Some pdb commands include

- <b> — Add breakpoint
- <c> — Resume execution
- <s> — Debug step by step
- <n> — Move to next line
- <l> — List source code
- <p> — Print an expression

Q. What command do we use to debug a Python program?

Ans. To start debugging, we first open the command prompt, and get to the location the file is at.

Microsoft Windows [Version 10.0.16299.248]

(c) 2017 Microsoft Corporation. All rights reserved.

C:\Users\lifei> cd Desktop

C:\Users\lifei\Desktop>

Then, we run the following command (for file try.py):

C:\Users\lifei\Desktop>python -m pdb try.py

c:\users\lifei\desktop\try.py(1)()
-> for i in range(5):

(Pdb)

Then, we can start debugging.

Q. What is a Counter in Python?

Ans. The function Counter() from the module ‘collections’. It counts the number of occurrences of the elements of a container.

from collections import Counter
Counter([1,3,2,1,4,2,1,3,1])
Counter({1: 4, 3: 2, 2: 2, 4: 1})

Python provides us with a range of ways and methods to work with a Counter. Read Python Counter.

Q. What is NumPy? Is it better than a list?

Python Programming Interview Questions - Numpy vs List

Python Programming Interview Questions – Numpy vs List

Ans. NumPy, a Python package, has made its place in the world of scientific computing. It can deal with large data sizes, and also has a powerful N-dimensional array object along with a set of advanced functions.

Yes, a NumPy array is better than a Python list. This is in the following ways:

  • It is more compact.
  • It is more convenient.
  • It Is more efficiently.
  • It is easier to read and write items with NumPy.

Q. How would you create an empty NumPy array?

Ans. To create an empty array with NumPy, we have two options:

a. Option 1

 import numpy
 numpy.array([])
array([], dtype=float64)

b. Option 2

 numpy.empty(shape=(0,0))
array([], shape=(0, 0), dtype=float64)

Q. Explain the use of the ‘nonlocal’ keyword in Python.

Ans. First, let’s discuss the local and global scope. By example, a variable defined inside a function is local to that function. Another variable defined outside any other scope is global to the function.

Suppose we have nested functions. We can read a variable in an enclosing scope from inside he inner function, but cannot make a change to it. For that, we must declare it nonlocal inside the function. First, let’s see this without the nonlocal keyword.

 def outer():
    a=7
    def inner():
        print(a)
    inner()
 outer()
7

 def outer():
    a=7
    def inner():
        print(a)
        a+=1
        print(a)
    inner()

 outer()
Traceback (most recent call last):
File "<pyshell#462>", line 1, in  outer()
File "<pyshell#461>", line 7, in outer inner()
File "<pyshell#461>", line 4, in inner print(a)
UnboundLocalError: local variable 'a' referenced before assignment

So now, let’s try doing this with the ‘nonlocal’ keyword:

 def outer():
    a=7
    def inner():
        nonlocal a
        print(a)
        a+=1
        print(a)
inner()

 outer()

Q. What is the global keyword?

Ans. Like we saw in the previous question, the global keyword lets us deal with, inside any scope, the global version of a variable.

The problem:

 a=7
 def func():
    print(a)
    a+=1
    print(a)
The solution:

 a=7
 def func():
    global a
    print(a)
    a+=1
    print(a)
 func()

Q. How would you make a Python script executable on Unix?

Ans. For this to happen, two conditions must be met:

The script file’s mode must be executable The first line must begin with a hash(#). An example of this will be: #!/usr/local/bin/python

Q. What functions or methods will you use to delete a file in Python?

Ans. For this, we may use remove() or unlink().

 import os
 os.chdir('C:\\Users\\lifei\\Desktop')
 os.remove('try.py')

When we go and check our Desktop, the file is gone. Let’s go make it again so we can delete it again using unlink().

 os.unlink('try.py')

Both functions are the same, but unlink is the traditional Unix name for it.

Q. What are accessors, mutators, and @property?

Ans. What we call getters and setters in languages like Java, we term accessors and mutators in Python. In Java, if we have a user-defined class with a property ‘x’, we have methods like getX() and setX(). In Python, we have @property, which is syntactic sugar for property(). This lets us get and set variables without compromising on the conventions. For a detailed explanation on property, refer to Python property.

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

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

Let’s take two lists.

list1,list2=[1,2,3],[5,6,7,8]

This is how append() works:

list1.append(4)
list1
[1, 2, 3, 4]

And this is how extend() works:

list1.extend(list2)
list1
[1, 2, 3, 4, 5, 6, 7, 8]

Q. What do you mean by overriding methods? Ans. Suppose class B inherits from class A. Both have the method sayhello()- to each, their own version. B overrides the sayhello() of class A. So, when we create an object of class B, it calls the version that class B has.

class A:
    def sayhello(self):
        print("Hello, I'm A")
class B(A):
    def sayhello(self):
        print("Hello, I'm B")
a=A()
b=B()
a.sayhello()
Hello, I'm A

b.sayhello()
Hello, I'm B

Q. What is JSON? Describe in brief how you’d convert JSON data into Python data?

Ans. JSON stands for JavaScript Object Notation. It is a highly popular data format, and it stores data into NoSQL databases. JSON is generally built on the following two structures:

  • A collection of <name,value> pairs
  • An ordered list of values.
  • Python supports JSON parsers. In fact, JSON-based data is internally represented as a dictionary in Python. To convert JSON data into Python data, we use the load() function from the JSON module.

Q. How do you execute a Python Script?

From the command line, type python .py or pythonx.y .py where the x.y is the version of the Python interpreter desired. Learn how to use Python, from beginner basics to advanced techniques, with online video tutorials taught by industry experts. Enroll for Free Python Training Demo!

Q. Explain the use of try: except: raise, and finally:

Try, except and finally blocks are used in Python error handling. Code is executed in the try block until an error occurs. One can use a generic except block, which will receive control after all errors, or one can use specific exception handling blocks for various error types. Control is transferred to the appropriate except block. In all cases, the finally block is executed. Raise may be used to raise your own exceptions.

Q. Illustrate the proper use of Python error handling.

Code Example:

try:.#This can be any code
except:
    …# error handling code goes here
finally:
    …# code that will be executed regardless of exception handling goes here.