Python interview questions accumulation

Q1. What is the difference between a list and a tuple in Python?

  • The list is dynamic, the length is not fixed, you can add, delete, and modify elements at will
  • The tuple is static, and the length is determined when it is initialized and cannot be changed, and it is also impossible to add, delete, or modify elements.

If the data is unlikely to change, use tuples to store it. If the data requires frequent data modification and increase, use a list.

Q2. What are the main functions of Python?

  • Python is an interpreted language. Unlike languages ​​such as C, Python does not need to be compiled before running.

  • Python is a dynamic language. When you declare variables or similar variables, you don't need to declare the type of the variable.

  • Python is suitable for object-oriented programming because it allows class definition and composition and inheritance. Python has no access instructions (such as public and private in C++).

  • In Python, functions are the first class of objects. They can be assigned to variables. Class is also a first-class object

  • Writing Python code is fast, but it runs slowly. Python allows C-based extensions, such as the numpy library.

  • Python can be used in many fields. Web application development, automation, mathematical modeling, big data applications, etc. It is also often used as a "glue" code.

Q3. Is Python a general-purpose programming language?

Python can write scripts, but in a general sense, it is considered a general-purpose programming language.

Q4. How does Python interpret the language?

Python does not need to interpret the program before running. Therefore, Python is an interpreted language.

Q5. What is pep?

PEP stands for Python Enhancement Proposal. It is a set of rules that specify how to format Python code for maximum readability.

Q6. How to manage memory in Python?

The memory management in python is managed by the Python private heap space. All Python objects and data structures are located in the private heap. The programmer does not have access to this private heap. The python interpreter is responsible for handling this problem.

The heap space allocation of Python objects is done by Python's memory manager. The core API provides some tools for programmers to write code.

Python also has a built-in garbage collector, which can reclaim all unused memory and make it available for heap space.

Memory management in Python is carried out from three aspects, one is the object reference counting mechanism bai, the second is the garbage collection mechanism, and the third is the memory pool mechanism.

1. Object reference counting mechanism

Python uses reference counting internally to keep track of objects in memory. All objects have reference counts.
The situation where the reference count increases:
1. Assign a new name to an object
2. Put it into a container (such as a list, tuple or dictionary)
The situation where the reference count decreases:
1. Use the del statement to destroy the object alias display
2. , The reference is out of scope or is reassigned to the
sys.getrefcount() function to obtain the current reference count of the object. In
most cases, the reference count is much larger than you guessed. For immutable data (such as numbers and strings), the interpreter will share memory in different parts of the program in order to save memory.

Two, garbage collection

1. When the reference count of an object returns to zero, it will be disposed of by the garbage collection mechanism.
2. When two objects a and b refer to each other, the del statement can reduce the reference count of a and b, and destroy the name used to refer to the underlying object. However, since each object contains an application to other objects, the reference count will not be reset to zero, and the object will not be destroyed. (Thus causing a memory leak). To solve this problem, the interpreter periodically executes a loop detector to search for loops of inaccessible objects and delete them.

Third, the memory pool mechanism

Python provides a garbage collection mechanism for memory, but it stores the unused memory in the memory pool instead of returning it to the operating system.
1. Pymalloc mechanism. In order to speed up the execution efficiency of Python, Python introduced a memory pool mechanism to manage the application and release of small blocks of memory.
2. All objects smaller than 256 bytes in Python use the allocator implemented by pymalloc, while large objects use the system malloc.
3. For Python objects, such as integers, floating-point numbers, and List, there are independent private memory pools, and their memory pools are not shared between objects. In other words, if you allocate and release a large number of integers, the memory used to cache these integers can no longer be allocated to floating-point numbers.

Q7. What is the namespace in Python?

Namespace is a naming system used to ensure that names are unique to avoid naming conflicts.

In Python, all names exist in a space, where they exist and are manipulated-this is the namespace. It is like a box, and each variable name contains an object. When querying variables, the corresponding object will be found in the box.

[Definition]
The mapping from name to object. The namespace is the realization of a dictionary, the key is the variable name, and the value is the value corresponding to the variable. It doesn't matter if each namespace is independent. A namespace cannot have the same name, but different namespaces can have the same name without any impact.

[Classification]
During the execution of the python program, there will be 2 or 3 active namespaces (3 when the function is called, and 2 after the function is called). According to the location of the variable definition, it can be divided into the following three categories:

  • Local, the local namespace, the namespace owned by each function, records all the variables defined in the function, including the input parameters of the function and the internally defined local variables.

  • Global, the global namespace, created when each module is loaded and executed, records the variables defined in the module, including functions and classes defined in the module, other imported modules, module-level variables and constants.

  • Built-in, python's built-in namespace, can be accessed by any module, and contains built-in functions and exceptions.

【life cycle】

  • Local (local namespace) is created when the function is called, but deleted when the function returns a result or throws an exception. (Each recursive function has its own namespace).

  • Global (global namespace) is created when the module is loaded, and is usually kept until the python interpreter exits.

  • Built-in (built-in namespace) is created when the python interpreter starts and remains until the interpreter exits.

The order of creation of each namespace: python interpreter startup -> create built-in namespace -> load module -> create global namespace -> function is called -> create local namespace

The order of destruction of each namespace: the end of the function call -> the local namespace corresponding to the function is destroyed -> the python virtual machine (interpreter) exits -> the global namespace is destroyed -> the built-in namespace is destroyed

The python interpreter loading phase will create a built-in namespace and a global namespace for the module. The local namespace is dynamically created when the function is called in the runtime phase, and is dynamically destroyed when the function is called.

Q8. What is PYTHONPATH?

It is the environment variable used when importing the module. Whenever a module is imported, PYTHONPATH is also searched to check whether the imported module exists in each directory. The interpreter uses it to determine which module to load.

Q9. What is a python module? What are the commonly used built-in modules in Python?

Python modules are .py files that contain Python code. This code can be a function class or a variable. Some commonly used built-in modules include: sys, math, random, data time, and JSON.

Q10. What are local variables and global variables in Python?

Global variables: Variables declared outside the function or in the global space are called global variables. These variables can be accessed by any function in the program.

Local variable: Any variable declared in a function is called a local variable. This variable exists in local space, not in global space.

Q11. Is python case sensitive?

Yes. Python is a case-sensitive language.

Q11. Is python case sensitive?

Yes. Python is a case-sensitive language.

Q12. What is type conversion in Python?

Type conversion refers to the conversion of one data type to another data type.

int()-Convert any data type to an integer type

float()-Convert any data type to float type

ord()-convert characters to integers

hex()-Convert integer to hexadecimal

oct()-Convert an integer to octal

tuple()-This function is used to convert to tuples.

set()-This function returns the type after conversion to set.

list()-This function is used to convert any data type to a list type.

dict()-This function is used to convert sequential tuples (keys, values) into a dictionary.

str()-Used to convert integers to strings.

complex (real, imag)-This function converts a real number to a complex (real number, image) number.

Q14. Is indentation required in python?

Indentation is required by Python. It specifies a code block. All code in loops, classes, functions, etc. are specified in indented blocks. It is usually done using four space characters. If your code does not need to be indented, it will not execute accurately and will also throw errors.

Q15. What is the difference between a Python array and a list?

Arrays and lists in Python have the same way of storing data. However, an array can only contain a single data type element, and a list can contain any data type element.

Q16. What are the functions in Python?

A function is a block of code that will only be executed when it is called. To define a function in Python, you need to use the def keyword.

Q17. What is __init__?

__init__ is a method or structure in Python. When creating a new object/instance of the class, this method will be automatically called to allocate memory. All classes have __init__ methods.
Code example

class Person:
    def __init__(self,name,age):
        self.name=name
        self.age=age
    def show(self):
        print("我的名字叫%s,我今年%d岁"%(self.name,self.age))

person1=Person("小米",25)
person1.show()

Output:

我的名字叫小米,我今年25

Q18. What is a lambda function?

A lambda function is also called an anonymous function. The function can contain any number of parameters, but there can only be one statement to perform an operation.

Q19. What is self in Python?

self is an instance or object of the class. In Python, self is included in the first parameter. However, this is not the case in Java, it is optional. It helps to distinguish methods and properties of classes with local variables. The self variable in the init method refers to the newly created object, while in other methods, it refers to the object whose method is called.

Q20. What is the distinction between break, continue and pass?

Reference:
[Python] The difference between pass, continue and break

Q21. What does [::-1} mean?

[::-1] is used to reverse the order of an array or sequence.
Sample code:

a='python'
b=a[::-1]
print(b) #nohtyp
c=a[::-2]
print(c) #nhy
#从后往前数的话,最后一个位置为-1
d=a[:-1]  #从位置0到位置-1之前的数
print(d)  #pytho
e=a[:-2]  #从位置0到位置-2之前的数
print(e)  #pyth

Reference: [:-1] and [::-1] in python

Q22. How to randomize the elements in a list in Python?

You can use the shuffle function to randomize list elements. Examples are as follows:

import random

words = ["python", "java", "constant", "immutable"]
random.shuffle(words)
print(words)

Output

['java', 'constant', 'python', 'immutable']

Q23. What is a python iterator?

Iterators are objects that can be traversed or iterated.

Iterator: An iterator can be regarded as a special object. Each time the object is called, it will return its next element. From an implementation point of view, an iterator object must define the __iter__() method and The object of the next() method.

Q24. How to generate random numbers in Python?

The random module is a standard module for generating random numbers. The method is defined as:

# 导入 random(随机数) 模块
import random
print(random.random()) #random.random()方法返回[0,1]范围内的浮点数
print(random.randint(0, 9))

The random.random() method returns a floating point number in the range [0,1]. This function generates random floating point numbers. The method used by the random class is the binding method of hiding the instance. You can use an instance of Random to show a multithreaded program that creates different thread instances. The other random generators used are:

randrange(a,b): It selects an integer and defines the range between [a,b]. It returns elements by randomly selecting elements from the specified range. It does not build scope objects.

uniform(a,b): It selects a floating point number defined in the range of [a,b)

normalvariate(mean,sdev): It is used for normal distribution, where mean is the mean and sdev is the sigma used for standard deviation.

Use and instantiate the Random class to create an independent multiple random number generator.

Q29. How do you capitalize the first letter of a string?

In Python, the capitalize() function can capitalize the first letter of a string. If the string already contains uppercase letters at the beginning, then it will return the original string.

Sample code:

#!/usr/bin/python3
str = "this is string EXAMPLE from runoob....wow!!!"
print ("str.capitalize() : ", str.capitalize())#首字母大写,其他小写
print ("str.capitalize() : ", str.lower())#全部小写

Output:

str.capitalize() :  This is string example from runoob....wow!!!
str.capitalize() :  this is string example from runoob....wow!!!

Q38. Why use *args, **kwargs?

When we are not sure how many parameters to pass to the function, or we want to pass the stored list or parameter tuple to the function, we * args,**kwargsuse kwargs when we don’t know how many keyword arguments are passed to the function, or it can Used to pass the value of the dictionary as a keyword parameter. The identifiers args and kwargs are a convention, you can also use* bob和** billy。

Q46. How to add value to python array?

You can use append(), extend() and insert(i, x) functions to add elements to the array.

member = ['a','b','c','1','2',3]
print(member)
member.append("python")#可以在列表后方添加一个元素:
print(member)
member1 = ['one','two','three']
member.extend(member1)#可以在列表后方添加一个列表:
print(member)
member.insert(1,"h")#可以根据索引位置在指定的地方插入元素:注意索引起始值是0
print(member)

Output

['a', 'b', 'c', '1', '2', 3]
['a', 'b', 'c', '1', '2', 3, 'python']
['a', 'b', 'c', '1', '2', 3, 'python', 'one', 'two', 'three']
['a', 'h', 'b', 'c', '1', '2', 3, 'python', 'one', 'two', 'three']

Q47. How to delete the value of python array?

You can use pop() or remove() to delete array elements. The difference between these two functions is that the former returns the deleted value, while the latter does not.

a = ["a", "b",  "c","d", "e"]
print(a)
for item in a[:]:
    print(item)
    if item == "b":
        a.remove(item)#匹配删除
print(a)
a.pop(1)#根据索引删除,列表第二个数删除
print(a)

Q50. How to implement multithreading in Python?

Python has a multi-threaded library, but the effect of using multi-threading to speed up the code is not so good.

Python has a structure called Global Interpreter Lock (GIL). The GIL ensures that only one "thread" can be executed at a time. One thread obtains the GIL to perform related operations, and then passes the GIL to the next thread.

Although it looks like programs are executed in parallel by multiple threads, they actually just use the same CPU cores in turns.

All these GIL transfers increase the cost of execution. This means that multithreading does not make the program run faster.

Q51, python symbols //,% and / operations

% Is the remainder
// is the integer
/ is the quotient (floating point)

Sample code:

a = 9
print('这是%运算的结果'+str(a%2))
print('这是//运算的结果'+str(a//2))
print('这是/运算的结果'+str(a/2))

Output result:

这是%运算的结果1
这是//运算的结果4
这是/运算的结果4.5

1. Summary of vomiting blood! A collection of 50 Python interview questions (with answers)
2. Niuke.com

https://www.nowcoder.com/practice/11ae12e8c6fe48f883cad618c2e81475?tpId=188&tqId=37519&rp=1&ru=%2Factivity%2Foj&qru=%2Fta%2Fjob-code-high-week%2Fquestion-ranking&tab=answerKey

https://www.cnblogs.com/zyjimmortalp/p/12669749.html

Guess you like

Origin blog.csdn.net/mao_hui_fei/article/details/114271615