Top Python Interview Questions

FREE Online Courses: Transform Your Career – Enroll for Free!

Python is one of the widely used programming languages. Its features like simplicity, user-friendly, collection of libraries, etc. are increasing the number of coders using it to develop applications. In this article, we will cover different basic concepts of Python and these can help you in exam or interview preparation.

Python Interview Questions

1. Why is Python called an interpreter language?

Ans. In Python, the code gets executed line by line. Also, the programs run directly from the source code, and there is no need for any intermediary compilation step. This is the reason it is an interpreter language.

2. Can you name some of the applications of Python?

Ans. Python is a versatile language and has its application in a wide range of domains. Some of these include:

a. Data Science
b. Web Development
c. Software Development
d. Network Programming, etc.

3. Define a set and write a program to create an empty set?

Ans. Set is a Python data structure that stores unique values of different data types. The elements of a set are enclosed between curly brackets.

Example of creating an empty set:

set1=set()
print(f"Set1={set1} and its type is {type(set1)}")

Output:

Set1=set() and its type is <class ‘set’>

4. Classify the following identifiers into valid and invalid names. (a) 1name (b) class_1 (c) del (d) section@3 (e) age__1

Ans. The valid ones are:
class_1
age__1

The invalid ones are :
1name (starting with a number)
del (keyword)
section@3 (@ is not allowed)

5. What is a data type and what are different data types in Python?

Ans. A data type is a classification of data that tells the interpreter what type of value is stored in the variable. In Python, we have the following data types:

a. Numeric data types

  • int
  • float
  • complex

b. Sequence

  • list
  • tuple
  • string

c. Boolean

d. Set

e. Dictionary

f. Range

6. Give the output of the below code with explanation.

def func1(var):
    var=5
    def func2(var):
        var=6
    func2(var)
    return var

var=3
print(func1(var),end=' ')
print(var)

Ans. The output is 5 3. This var=3 is a global variable, inside the func1 var=5 is a local variable and inside func2 var=6 is an enclosed variable. So, these variables have different scopes. So, when var is returned by func1, 5 is returned. In the second print statement global variable’s value,i.e. 3 is printed.

7. Write a program to create a tuple with 10 elements. Print alternate elements from third to last element and print all of the elements in reverse order.

Ans. Example of tuples:

tup=(1,2,3,4,5,6,7,8,9,10)
print(tup[2::2])
print(tup[::-1])

Output:

(3, 5, 7, 9)
(10, 9, 8, 7, 6, 5, 4, 3, 2, 1)

8. What is a lambda function and write a program with a lambda function that gives the square of the input?

Ans. Lambda function is a regular python function defined without any def keyword and name. These functions are created using the lambda keyword.

Example of lambda function:

sq=lambda a:a**2
print(sq(9))

Output:

81

9. Write a program to create a list, remove the first occurrence of the value ‘2’ in the list.

Ans. Example of lists:

list1=[1,2,1,1,3,4,1,2,2,8]
ind=list1.index(2)
list1.pop(ind)
print(list1)

Output:

[1, 1, 1, 3, 4, 1, 2, 2, 8]

10. Write a program to print a Fibonacci series recursively.

Ans. Example of Fibonacci series with recursion:

def recur_fibo(n):
    if n<0:
        return 0
    elif n <= 1:
        return n
    else:
        return(recur_fibo(n-1) + recur_fibo(n-2))

for i in range(10):
    print(recur_fibo(i),end=" ")

Output:

0 1 1 2 3 5 8 13 21 34

11. Name different string formatting and give examples for each?

Ans. We have three string formattings:

  • % operator
  • f-string
  • format() method

Example of string formattings:

var=1
print("Var=%d"%var)

print(f"Var={var}")

print("Var={0}".format(var))

Output:

Var=1
Var=1
Var=1

12. What is indentation in Python?

Ans. Indentation in Python refers to spaces or tabs that represent that the set of lines belong to the same group, like a loop, function, etc. Indentation is compulsory in Python and is a part of its syntax.

It also defines the scope and extent of the code blocks and gives better readability to the program.

13. Write a code to swap the values of the two variables using bitwise operators.

Ans. Example of bitwise operators:

a=-3
b=5
a=a^b
b=a^b
a=a^b
print("a=",a,",b=",b)

Output:

a= 5 ,b= -3

14. Is Python case sensitive? Use one of the operators to show it.

Ans. Python is case-sensitive. And ‘Python’ and ‘python’ are treated differently in Python. Let us use the equal to operator to check this.

Example of comparison operators:

print('Python'=='python')

Output:

False

15. Show the calculation of 3+5/2==4*3%3 using operator precedence.

Ans. The precedence order is
%
*,/
+,-
==

So,

3+5/2==4*3%3
3+2.5==4*0
5.5==0
False

Example of operator precedence:

3+5/2==4*3%3

Output:

False

16. Write a program to create a new list with even elements of a list using list comprehension.

Ans. Example of list comprehension:

list1=[1,2,3,4,5,6,7,8,9,10]
list2=[ i for i in list1 if i%2==0]
list2

Output:

[2, 4, 6, 8, 10]

17. Create a dictionary and delete a key-value pair using the key.

Ans. Example of dictionary:

dic1={1:'one',2:'two',3:'three',4:'four',5:'five'}

dic1.pop(3)

dic1

Output:

{1: ‘one’, 2: ‘two’, 4: ‘four’, 5: ‘five’}

Ans.18. Show some of the differences between tuples and lists.

Tuples Lists
The elements are enclosed by circular brackets. The elements are enclosed by square brackets.
Tuples are immutable Lists are mutable
Occupy less memory and are faster Comparatively, the lists occupy more memory and are slower.
Work in read-only mode. Allow insertion, deletion, etc.
The occurrence of unexpected changes and errors is less  There is a higher chance of the occurrence of unexpected errors and changes.

19. Name different collections in Python. Also, name the module which includes the collections.

Ans. Collections are data structures, alternative to the built-in data types. The module named Collections stores these special structures. These are:

a. Counters

b. DefaultDict

c. OrderedDict

d. ChainMap

e. NamedTuple

f. DeQue

g. UserList

h. UserString

i. UserDict

20. Write a program to create an empty dictionary, add different elements and get all the keys of the dictionary.

Ans. Example of dictionary:

dic1={}

dic1[1]=1
dic1[2]=4
dic1[3]=9

dic1.keys()

Output:

dict_keys([1, 2, 3])

21. Write a program to remove all the spaces in the string.

Ans. We can use the replace function to change all the spaces.

Example of removing spaces in the string:

string='12abc prq 23'
string.replace(" ","")

Output:

’12abcprq23′

22. Write a function to print the smallest number using the if-else ladder.

Ans. Example of if-else ladder:

a=5
b=2
c=-4

if(a<b and a<c):
    print("a:",a)
elif(b<a and b<c):
    print("b:",b)
else:
    print("c:",c)

Output:

c: -4

23. Write a program to check if a number is divisible by 2 and 3 using nested if-else.

Ans. Example of nested if-else:

n=9
if(n%2==0):
    if(n%3==0):
        print("Divisible by 2 and 3")
    else:
        print("Divisible by 2")
else:
    if(n%3==0):
        print("Divisible by 3")
    else:
        print("Not divisible by 2 and 3")

Output:

Divisible by 3

24. Write a program to either print double, square, or cube of a number based on the input using the switch statement.

Ans. Example of switch statement:

def func(choice,x):
    switch={
        1: 2*x ,
        2: x**2 ,
        3: x**3 ,
        }
    return switch.get(choice)

func(2,4)

Output:

16

25. Print factorial of a number using a for loop.

Ans. Example of for loop:

n=5
fact=1
for i in range(1,n+1):
    fact*=i
print(fact)

Output:

120

26. Print all the factors of a number using a while loop.

Ans. Example of while loop:

n=10
i=1
while(i<=(n/2)):
    if(n%i==0):
        print(i)
    i=i+1

Output:

1
2
5

27. Write a function that can take a variable number of numbers and print the sum.

Ans. Example of function with a variable number of arguments:

def func(*vars):
    sum=0
    for i in vars:
        sum+=i
    return sum

func(1,2,-3,4,1,3)

Output:

8

28. What is the union of the sets and write code to print the union of two sets?

Ans. Union returns all the values of the sets, ignoring the duplicates.

Example of union of sets:

set1={1,2,3,5}
set2={0.8,1,5,7}

print("set1|set2:",set1|set2)

Output:

set1|set2: {0.8, 1, 2, 3, 5, 7}

29. Use a built function to get the quotient and reminder of division.

Ans. Example of divmod:

divmod(5,3)

Output:

(1, 2)

30. Write a code that uses a built in function to dynamically execute the program
x=5
y=8
print(x*y)

Ans. We can use the exec() method to run the code by giving the code in the form of a string.

Example of exec:

exec('x=5;y=8;print(x*y)')

Output:

40

Conclusion

We are at the end of the article. I hope this article was informative as well as helpful for your interview preparations. Happy learning!

We work very hard to provide you quality material
Could you take 15 seconds and share your happy experience on Google | Facebook


Leave a Reply

Your email address will not be published. Required fields are marked *