A complete collection of 50 essential python interview questions in 2022 (with answers) [recommended collection]

I have sorted out 50 Python interview questions and corresponding answers for you to help you better understand and learn Python.

1. What is Python? Why is it so popular?

Python is an interpreted, high-level, general-purpose programming language.

Python's design philosophy is to enhance the readability of code by using necessary spaces and blank lines.

Its popularity is due to its simple and easy-to-use syntax.

2. Why is Python slow and how can we improve it?

The reason Python code executes slowly is because it is an interpreted language. Its code is interpreted at runtime, rather than compiled into a native language.

To increase the speed of the Python code, we can use CPython, Numba, or we can also make some modifications to the code.

1. 减少内存占用。

2. 使用内置函数和库。

3. 将计算移到循环外。

4. 保持小的代码库。

5. 避免不必要的循环

3. What are the characteristics of Python?

1. 易于编码

2. 免费和开源语言

3. 高级语言

4. 易于调试

5. OOPS支持

6. 大量的标准库和第三方模块

7. 可扩展性(我们可以用C或C++编写Python代码)

8. 用户友好的数据结构

4. What are the applications of Python?

1. Web开发

2. 桌面GUI开发

3. 人工智能和机器学习

4. 软件开发

5. 业务应用程序开发

6. 基于控制台的应用程序

7. 软件测试

8. Web自动化

9. 基于音频或视频的应用程序

10. 图像处理应用程序

5. What are the limitations of Python?

1. 速度

2. 移动开发

3. 内存消耗(与其他语言相比非常高)

4. 两个版本的不兼容(2,3)

5. 运行错误(需要更多测试,并且错误仅在运行时显示)

6. 简单性

Heading 6. How is Python code executed?

First, the interpreter reads the Python code and checks for syntax or formatting errors.

Execution is halted if an error is found. If no errors are found, the interpreter converts the Python code into an equivalent form or byte code.

The bytecode is then sent to the Python Virtual Machine (PVM), where the Python code will be executed, and execution will be halted if any errors are found, otherwise the results will be displayed in the output window.
The results show

7. How to manage memory in Python?

Python memory is managed by Python's private headspace.

All Python objects and data structures reside in a private heap. Allocation of the private heap is the responsibility of the Python memory manager.

Python also has a built-in garbage collector that reclaims unused memory and frees memory so it can be used for headspace.

8. Explain Python's built-in data structures?

There are mainly four types of data structures in Python.

List: A list is a collection of heterogeneous data items ranging from integers to strings or even another list. Lists are mutable. Lists do what most collection data structures do in other languages. Lists are defined within [ ] square brackets.

For example: a = [1,2,3,4]

Sets: A set is an unordered collection of unique elements. Set operations such as union |, intersection &, and difference, can be applied to sets. {} is used to represent a collection.

For example: a = {1,2,3,4}

Tuples: Python tuples work exactly like Python lists, except they are immutable. () is used to define tuples.

For example: a = (1,2,3,4)

Dictionary: A dictionary is a collection of key-value pairs. It is similar to hash map in other languages. In a dictionary, keys are unique and immutable objects.

For example: a = {'number': [1,2,3,4]}

9. Explain //, %, * * operators?

//(Floor Division) - This is a division operator which returns the integer part of the division.

Example: 5 // 2 = 2

%(modulus) - Returns the remainder of the division.

Example: 5 % 2 = 1

**(exponentiation) - It performs exponential calculation on the operator. a ** b means a raised to the bth power.

For example: 5 ** 2 = 25, 5 ** 3 = 125

10. What is the difference between single quotes and double quotes in Python?

There is no difference between using single quotes (' ') or double quotes (" ") in Python, both can be used to represent a string.

In addition to simplifying the programmer's development and avoiding mistakes, these two general expressions also have the advantage of reducing the use of escape characters and making the program look more concise and clear.

11. What is the difference between append, insert and extend in Python?

append: Adds a new element at the end of the list.

insert: Adds an element at a specific position in the list.

extend: Extends the list by adding a new list.

numbers = [1,2,3,4,5]
numbers.append(6)
print(numbers)
>[1,2,3,4,5,6]

## insert(position,value)
numbers.insert(2,7)  
print(numbers)
>[1,2,7,3,4,5,6]

numbers.extend([7,8,9])
print(numbers)
>[1,2,7,3,4,5,6,7,8,9]

numbers.append([4,5])
>[1,2,7,3,4,5,6,7,8,9,[4,5]]

12. What are break, continue, and pass?

break: It will cause the program to exit the loop when the condition is met.

continue: will return to the beginning of the loop, which causes the program to skip all remaining statements in the current loop iteration.

pass: Makes the program pass all remaining statements without executing them.

13. Distinguish between remove, del and pop in Python?

remove: will remove the first matching value in the list, it takes a value as an argument.

del: deletes an element using an index, it does not return any value.

pop: will remove the top element in the list and return the top element of the list.

numbers = [1,2,3,4,5]
numbers.remove(5)
> [1,2,3,4]

del numbers[0]
>[2,3,4]

numbers.pop()
>4

14. What is a switch statement. How to create a switch statement in Python?

The switch statement is to implement the multi-branch selection function and test the variables according to the list value.

Each value in a switch statement is called a case.

In Python, there is no built-in switch function, but we can create a custom switch statement.

switcher = {
    
    
   1: "January",
   2: "February",
   3: "March",
   4: "April",
   5: "May",
   6: "June",
   7: "July",
   8: "August",
   9: "September",
   10: "October",
   11: "November",
   12: "December"
}
month = int(input())
print(switcher.get(month))

> 3
march

15. Give an example of the range function in Python?

range: The range function returns a series of sequences from the start point to the end point.

range(start, end, step), the third parameter is used to define the number of steps in the range.

# number
for i in range(5):
    print(i)
> 0,1,2,3,4

# (start, end)
for i in range(1, 5):
    print(i)
> 1,2,3,4

# (start, end, step)
for i in range(0, 5, 2):
    print(i)
>0,2,4

16. What is the difference between == and is?

== compares two objects or values ​​for equality.

is operator is used to check if two objects belong to the same memory object.

lst1 = [1,2,3]
lst2 = [1,2,3]

lst1 == lst2
>True

lst1 is lst2
>False

17. How to change the data type of the list?

To change the data type of a list, use tuple() or set().

lst = [1,2,3,4,2]

# 更改为集合
set(lst)    ## {1,2,3,4}
# 更改为元组
tuple(lst)  ## (1,2,3,4,2)

18. What are the methods of commenting code in Python?

In Python, we can comment in the following two ways.

  1. Triple quotes ''', for multi-line comments.

  2. Single pound sign #, used for single-line comments.

19. What is the difference between != and is not operators?

!= Returns true if the values ​​of two variables or objects are not equal.

is not is used to check whether two objects belong to the same memory object.

lst1 = [1,2,3,4]
lst2 = [1,2,3,4]

lst1 != lst2
>False

lst1 is not lst2
>True

20. Does Python have a main function?

Yes, it has. It will be executed automatically whenever we run the Python script.

21. What is a lambda function?

Lambda functions are single-line functions without a name, which can have n parameters, but only one expression. Also known as an anonymous function.

a = lambda x, y:x + y 
print(a(5, 6))

> 11

22. What is the difference between iterables and iterators?

iterable: An iterable is an object that can be iterated over. In the iterable case, the entire data is stored in memory at once.

iterators: Iterators are objects used to iterate over objects. It is only initialized or stored in memory when called. The iterator uses next to retrieve elements from the object.

# List is an iterable
lst = [1,2,3,4,5]
for i in lst:
    print(i)

# iterator
lst1 = iter(lst)
next(lst1)
>1
next(lst1)
>2
for i in lst1:
    print(i)
>3,4,5 

23. What is the Map Function in Python?

The map function returns a map object after applying a specific function to each item of the iterable.

24. Explain the Filter in Python?

A filter function that filters values ​​from an iterable based on some criteria.

# iterable
lst = [1,2,3,4,5,6,7,8,9,10]

def even(num):
    if num%2==0:
        return num

# filter all even numbers
list(filter(even,lst))
---------------------------------------------
[2, 4, 6, 8, 10] 

25. Explain the usage of reduce function in Python?

The reduce() function takes a function and a sequence and returns the value after computation.

from functools import reduce

a = lambda x,y:x+y
print(reduce(a,[1,2,3,4]))

> 10 

26. What is pickling and unpickling?

Pickling is the process of converting Python objects (or even Python code) into strings.

Unpickling is the reverse process of converting a string into an original object.

27. Explain *args and **kwargs?

*args, is used when we are not sure about the number of arguments to pass to the function.

def add(* num):
    sum = 0 
    for val in num:
        sum = val + sum 
    printsum


add(4,5
add(7,4,6
add(10,34,23--------------------- 
9 
17 
67

**kwargs, is used when we want to pass a dictionary as an argument to a function.

def intro(**data):
    print("\nData type of argument:",type(data))
    for key, value in data.items():
        print("{} is {}".format(key,value))


intro(name="alex",Age=22, Phone=1234567890)
intro(name="louis",Email="[email protected]",Country="Wakanda", Age=25)
--------------------------------------------------------------
Data type of argument: <class 'dict'>
name is alex
Age is 22
Phone is 1234567890

Data type of argument: <class 'dict'>
name is louis
Email is a@gmail.com
Country is Wakanda
Age is 25

28. Explain the split(), sub(), subn() methods of the re module?

split(): This method will split the string whenever the pattern matches.

sub(): This method is used to replace certain patterns in a string with other strings or sequences.

subn(): Similar to sub(), except that it returns a tuple with the total replacement count and the new string as output.

import re
string = "There are two ball in the basket 101"


re.split("\W+",string)
---------------------------------------
['There', 'are', 'two', 'ball', 'in', 'the', 'basket', '101']

re.sub("[^A-Za-z]"," ",string)
----------------------------------------
'There are two ball in the basket'

re.subn("[^A-Za-z]"," ",string)
-----------------------------------------
('There are two ball in the basket', 10)

29. What is a generator in Python?

The definition of a generator (generator) is similar to a normal function, and the generator uses the yield keyword to generate a value.

If a function contains the yield keyword, then the function will automatically become a generator.

# A program to demonstrate the use of generator object with next() A generator function 
def Fun(): 
   yield 1
   yield 2
   yield 3

# x is a generator object 
x = Fun()
print(next(x))
-----------------------------
1
print(next(x))
-----------------------------
2

30. How to reverse a string in Python using indexing?

string = 'hello'

string[::-1]
>'olleh'

31. What is the difference between a class and an object?

Classes are considered blueprints for objects. The first line of string in a class is called the doc string and contains a short description of the class.

In Python, a class is created using the class keyword. A class contains combinations of variables and members, called class members.

Object (Object) is a real entity. To create an object for a class in Python we can use obj = CLASS_NAME()

For example: obj = num()

Using an object of a class, we can access all members of the class and operate on them.

class Person:
    """ This is a Person Class"""
    # varable
    age = 10
    def greets(self):
        print('Hello')


# object
obj = Person()
print(obj.greet)
----------------------------------------
Hello

32. What do you know about self in Python classes?

self represents an instance of the class.

By using the self keyword, we can access the properties and methods of a class in Python.

Note that within a class function, self must be used because there is no explicit syntax for declaring variables in a class.

33. What is the use of _init_ in Python?

" init " is a reserved method in Python classes.

It is called constructor and it is called automatically whenever the code is executed and it is mainly used to initialize all the variables of the class.

34. Explain inheritance in Python?

Inheritance allows one class to acquire all the members and properties of another class. Inheritance provides code reusability, making it easier to create and maintain applications.

The inherited class is called superclass and the inherited class is called derived class/subclass.

35. What is OOPS in Python?

Object-Oriented Programming, Abstraction, Encapsulation, Inheritance, Polymorphism

36. What is abstraction?

Abstraction is the process of showing the essence or necessary characteristics of an object to the outside world and hiding all other irrelevant information.

37. What is encapsulation?

Encapsulation (Encapsulation) means packaging data and member functions together into a unit.

It also implements the concept of data hiding.

38. What is polymorphism?

Polymorphism means "many forms".

A subclass can define its own unique behavior and still share the same functionality or behavior of its parent/base class.

39. What is monkey patching in Python?

Monkey patching refers to dynamically modifying classes or modules at runtime.

from SomeOtherProduct.SomeModule import SomeClass

def speak(self):
    return "Hello!"

SomeClass.speak = speak

40. Does Python support multiple inheritance?

Python can support multiple inheritance. Multiple inheritance means that a class can be derived from more than one parent class.

41. What is the zip function used in Python?

The zip function takes iterable objects, aggregates them into a tuple, and returns the result.

The syntax of the zip() function is zip(*iterables)

numbers = [1, 2, 3]
string = ['one', 'two', 'three'] 
result = zip(numbers,string)

print(set(result))
-------------------------------------
{
    
    (3, 'three'), (2, 'two'), (1, 'one')}

42. Explain the map() function in Python?

The map() function applies the given function to an iterable object (list, tuple, etc.) and returns the result (a map object).

We can also pass multiple iterable objects at the same time in the map() function.

numbers = (1, 2, 3, 4)
result = map(lambda x: x + x, numbers)

print(list(result))

43. What is a decorator in Python?

Decorators are an interesting feature in Python.

It is used to add functionality to existing code. This is also known as metaprogramming because one part of the program, when compiled, tries to modify another part of the program.

def addition(func):
    def inner(a,b):
        print("numbers are",a,"and",b)
        return func(a,b)
    return inner

@addition
def add(a,b):
   print(a+b)

add(5,6)
---------------------------------
numbers are 5 and 6
sum: 11

44. Write a program to find the longest word in a text file

def longest_word(filename):
    with open(filename, 'r') as infile:
              words = infile.read().split()
    max_len = len(max(words, key=len))
    return [word for word in words if len(word) == max_len]

print(longest_word('test.txt'))
----------------------------------------------------
['comprehensions']

45. Write a program to check whether the sequence is a palindrome

a = input("Enter The sequence")
ispalindrome = a == a[::-1]

ispalindrome
>True

46. ​​Write a program to print the first ten items of the Fibonacci sequence

fibo = [0,1]
[fibo.append(fibo[-2]+fibo[-1]) for i in range(8)]

fibo
> [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

47. Write a program to calculate the frequency of words in a file

from collections import Counter

def word_count(fname):
        with open(fname) as f:
                return Counter(f.read().split())

print(word_count("test.txt"))

48. Write a program to output all prime numbers in a given sequence

lower = int(input("Enter the lower range:"))
upper = int(input("Enter the upper range:"))
list(filter(lambda x:all(x % y != 0 for y in range(2, x)), range(lower, upper)))

-------------------------------------------------
Enter the lower range:10
Enter the upper range:50
[11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]

49. Write a program to check whether the number is Armstrong

Write a program that checks if a number is Armstrong

Separate each number in turn, and add up its cube (number of digits).

Finally, if the sum is found to be equal to the original number, it is called an Armstrong number.

num = int(input("Enter the number:\n"))
order = len(str(num))

sum = 0
temp = num

while temp > 0:
   digit = temp % 10
   sum += digit ** order
   temp //= 10

if num == sum:
   print(num,"is an Armstrong number")
else:
   print(num,"is not an Armstrong number")

50. Use one line of Python code to extract all even and odd numbers from a given list

a = [1,2,3,4,5,6,7,8,9,10]
odd, even = [el for el in a if el % 2==1], [el for el in a if el % 2==0]

print(odd,even)
> ([1, 3, 5, 7, 9], [2, 4, 6, 8, 10])

By the way, I would like to recommend some Python video tutorials for you, hoping to help you:

Python zero-based teaching collection

If you have any questions about the article, or have other questions about python, you can leave a message in the comment area or private me

If you think the article I shared is good, you can follow me, or give the article a thumbs up (/≧▽≦)/

Guess you like

Origin blog.csdn.net/Modeler_xiaoyu/article/details/128151666