The latest Python interview questions in 2020 (3): Python basics

1. Talk about your knowledge of Python coding standards and write the coding standards you know

The Python specification is mainly based on the following reasons:

(1) Most programmers have poor code readability.
(2) Collaboration between different programmers is very important, and code readability must be good.
(3) When performing version upgrades, upgrade based on source code.
(4) Unfriendly code will affect the execution efficiency of Python and the overall progress of the project.

Currently, PEP8's Python coding style is used. Python coding standards mainly have the following points:

1. Code layout

(1) Indentation: 4 spaces to achieve indentation, try not to use Tab, and prohibit mixing Tab and spaces.
(2) Line: The maximum length of each line does not exceed 79, and a backslash (\) can be used for line breaks. It is best to use parentheses to enclose the newline content, and it is not recommended ;.
(3) Blank line: There are two blank lines between the class and the top-level function definitions, one line between the method definitions in the class, and one line between logic-independent paragraphs in the function. Try not to leave blank lines in other places.
(4) Space: The first position in the brackets, no space. Do not use spaces immediately adjacent to the closing parenthesis. Do not add a space before the colon (: ), comma (,) and semicolon (;).
(5) in brackets: For single-element tuple must be added ,and parentheses.

2、命名规范
module_name
package_name
ClassName
metho_name
ExceptionName
function_name
GLOBAL_CONSTANT_NAME
global_var_name
instance_var_name
function_parameter_name
local_var_name

3. Comment specification

(1) Block comment, a comment added before a piece of code. In #between a space after the addition, only the passages at #the row spacing.
(2) Line comment, add a comment after a sentence of code.
(3) Avoid unnecessary comments.

4. Programming suggestions

(1) For string splicing, try to use join.
(2) For singleton objects, try to use is and is not instead of ==.
(3) Use is not instead of not is.
(4) Use def to define a function instead of assigning an anonymous function to a variable.
(5) Try to make the code neat and concise.
(6) Use isinstance() to determine the type of instance.

2. What is the purpose of the pass statement in Python?

pass is a statement that will not be executed in Python. The pass statement is generally used as a placeholder or to create a placeholder program. In a complex statement, if a place needs to be left blank temporarily, then the pass statement can be used. Sample code:

age = 17
if age >= 18:
    pass
else:
    print("age<18!未成年!")

3. What are the functions of except in Python programming?

Python's except is used to catch all exceptions. Because every error in Python throws an exception, every program error is treated as a runtime error.

try...
except...
except...
[else...][finally...]

When executing the try block statement, if an exception is thrown, the execution will jump to the except code block. Try to execute each except branch in sequence. If the thrown exception matches the exception group in except, execute the corresponding statement. If all the excepts do not match, the exception will be thrown to the upper caller.

If the statement under try is executed normally, the else code block is executed. If an exception occurs, it will not be executed. If there is a finally statement, the finally code block will always be executed at the end.

4. Functions

Functions are organized, reusable, code segments used to implement single or related functions. Functions can improve application modularity and code reuse rate. Python provides many built-in functions, such as print(). You can also create a function yourself, which is called a user-defined function.

The purpose of the function is to encapsulate some complex operations to simplify the structure of the program and make it easy to read. Before the function is called, it must be defined first. You can also define a function inside a function, and the internal function can only be executed when the external function is called. When the program calls a function, it goes to execute the statement inside the function. After the function is executed, it returns to the place where it left the program and executes the next statement of the program.

4.1 How does Python define a function?

User-defined functions need to follow the following rules:

(1) The function code block starts with the def keyword, followed by the function identifier name and parentheses ().
(2) Any incoming parameters and independent variables must be placed between the parentheses, and the parentheses can be used to define parameters.
(3) The first line of the function can optionally use a docstring to store the function description.
(4) The content of the function starts with a colon and is indented.
(5) return [expression] End the function and optionally return a value to the function caller. Return without expression is equivalent to returning None.
(6) By default, parameter values ​​and parameter names are matched in the order defined in the function declaration. The sample code is as follows:

def get_ip(url, headers):
    """
    用于获取指定网站中的ip及端口
    :param url: 抓取网站的链接
    :param headers: 请求头
    :return: None
    """
    response = requests.get(url=url, headers=headers)
    response.encoding = "utf8"  # 设置编码方式
    if response.status_code == 200:  # 判断请求是否成功
        html = etree.HTML(response.text)  # 解析HTML
        # 获取所有带有IP的li标签
        li_list = html.xpath('//div[@class="container"]/div[2]/ul/li')[1:]
        for li in li_list:  # 遍历每行内容
            ip = li.xpath('./span[@class="f-address"]/text()')[0]  # 获取ip
            port = li.xpath('./span[@class="f-port"]/text()')[0]  # 获取端口
            ip_list.append(ip + ":" + port)
            print(f"代理ip为: {ip}, 对应端口为: {port}")

4.2 What is a lambda function?

There are two ways to define functions in Python, one is to use the keyword def to define. When defining a function in this way, you need to specify the name of the function. This type of function is called an ordinary function; the other is to use the keyword lambda to define it without specifying the name of the function. This type of function is called a lambda function. Lambda function is also called anonymous function. It is a small one-line function with simple syntax, simplified code, no naming conflicts, and no namespace occupation. A lambda function is a function that can receive any number of parameters (including optional parameters) and return a single expression value. The lambda function cannot return more than one expression. Don't try to use lambda functions to implement complex business logic functions, because this will make the code obscure. If there is such a requirement, it should be defined as an ordinary function, and then complex business logic should be implemented in the ordinary function. The syntax is as follows:

lambda 参数: 表达式

Among them, there can be multiple parameters, separated by commas, there can be only one expression on the right side of the colon, and the lambda function returns a function object, so when using a lambda function, you need to define a variable to receive it.

Insert picture description here
If the function that needs to be defined is very simple, for example, there is only one expression and no other commands, then lambda functions can be considered. Otherwise, it is recommended to define ordinary functions, after all, there are not too many restrictions on ordinary functions.

4.3 What are the similarities and differences between ordinary functions and lambda functions?

Similarities:
(1) Both can define a fixed method and program processing flow.
(2) Both can contain parameters.
Differences:
(1) Lambda function code is more concise, but ordinary functions defined by def are more intuitive and easy to understand.
(2) def defines ordinary functions, while lambda defines expressions.
(3) The lambda function cannot contain loops or branches, and cannot contain return statements.
(4) The keyword lambda is used to create anonymous functions, and the keyword def is used to create named ordinary functions.

4.4 What is the method of passing function parameters in Python?

Value transfer refers to copying the actual parameters to the formal parameters when calling the function, so that the formal parameters can be modified in the function without affecting the actual parameters. Passing by reference refers to passing the address of the actual parameter to the function when calling the function, so that the modification of the parameter in the function will directly affect the actual parameter.

For immutable types (numerical type, string, tuple), because the variable cannot be modified, the operation will not affect the variable itself, while for the variable type (list, dictionary), the operation within the function may change The parameter variable passed in. Therefore, for immutable data types, the parameter passing of a function can be regarded as value passing, while for variable data types, the parameter passing of a function is passing by reference.

def self_add(a):
    a += a


a_int = 1
print(a_int)  # 1
self_add(a_int)
print(a_int)  # 1

a_list = [1, 2]
print(a_list)  # [1,2]
self_add(a_list)
print(a_list)  # [1,2,1,2]

Another example:

def method(value):
    value = 2
    print(id(value))  # 140722991755568
    print(value)  # 2


value = 1
print(id(value))  # 140722991755536
method(value)
print(value)  # 1

4.5 What is a closure?

The internal function can refer to the parameters and local variables of the external function. When the external function returns to the internal function, the related parameters and variables are saved in the returned function. This feature is called Closure. A closure is a nesting of two functions. The outer function returns a reference to the inner function, and the outer function must have parameters. Similar format for closures:

def 外部函数(参数):
	def 内部函数():
		pass
	return 内部函数

Closures have the following characteristics:
(1) There must be an embedded function.
(2) The internal function must refer to the variable of the external function (the function contains a reference to the external scope rather than the global scope name).
(3) The return value of the external function must be an embedded function.

The difference between a closure and a normal function:
(1) The closure format is a nesting of two functions.
(2) The parameters of the external function of the closure can be kept in memory.
(3) The closure function is like a "class", only the methods in the closure function can use its local variables, and the methods outside the closure function cannot read its local variables. This achieves object-oriented encapsulation, which is safer and more reliable, that is, the data in the closure is unique data and has no influence on the outside world.
(4) Function: In a function, the global variables that need to be used are restricted to a certain extent, because global variables can not only be used by one function, but other functions may also be used. Once modified, it will affect the use of other functions. Global variables, so global variables cannot be modified casually, so there are certain limitations in the use of functions. Example 1:

def func_out(*args):  # 定义外部函数
    def func_in():  # 使用外部函数的args变量
        sum_v = sum(args)
        return sum_v

    return func_in  # 返回内部函数


s = func_out(1, 2, 3, 2)
print(s())  # 真正调用的 func_in 函数 ==> 8

Example 2:

def pass_out(score_line):
    def true_score(score):
        if score >= score_line:
            print("合格")
        else:
            print("不合格")

    return true_score


total_score_100 = pass_out(60)
total_score_150 = pass_out(90)
total_score_100(90)  # 合格
total_score_150(60)  # 不合格

4.6 What is the role of *args and **kwargs in functions?

*args and **kwargs are mainly used for function definition. When the parameters of a function are uncertain, you can use *args and **kwargs to pass a variable number of parameters to a function. Indefinite here means that it is not known in advance how many parameters the user of the function will pass, so these two keywords can be used in this scenario.

*args is used to send a variable number of parameter lists that are not key-value pairs to a function. *args will receive any number of parameters and pass these parameters to the function as a tuple. *args has no key value and is passed as a dictionary. It should be noted that the order of the parameters of the function: *args must be before **kwargs, and the parameters passed by the calling function must also follow this order.

(1) *args example:

def demo(args_f, *args_v):
    print(args_f)
    for x in args_v:
        print(x, end="")


demo(1, "a", "b", "c", "d")

Another example:

def function(x, y, *args):
    print(x, y, args)


function(1, 2, 3, 4, 5)  # 1 2 (3, 4, 5)

Explain that what is passed to the function is a tuple.
(2) **kwargs example

def demo(**args_v):
    for k, v in args_v.items():
        print(k, v)  # name Amo


demo(name="Amo")

Another example:

def function(**kwargs):
    print(kwargs, type(kwargs))


function(a=2)  # {'a': 2} <class 'dict'>

It should be noted that the positions of the three parameters arg, *args, **kwargs are determined. Must be (arg, *args, **kwargs") in this order, otherwise the program will report an error.

def function(arg, *args, **kwargs):
    print(arg, args, kwargs)


function(6, 7, 8, 9, a=1, b=2, c=3)  # 6 (7, 8, 9) {'a': 1, 'b': 2, 'c': 3}

For knowledge of function parameters, please see the 45th exercise in the blogger Python basic exercises:

Insert picture description here

5. What is a module? What are its benefits?

In Python, a .py file is called a module (Module). Modules improve the maintainability of the code, and modules can also be referenced elsewhere. A folder containing a lot of Python code is a package. A package can contain modules and subfolders. In Python, modules are a way of building programs. Modules are generally divided into the following types:

(1) Built-in modules: such as os, random, time and sys modules.
(2) Third-party modules: modules written by others can be used, but before using third-party modules, you need to use the pip command (third-party package management tool) to install.
(3) Custom modules: modules written by programmers themselves.

6. What are the ways to import modules?

In Python, use import or from...import... to import the corresponding module.

(1) Import the entire module (somemodule) in the format: import somemodule.
(2) Import a function from a module, the format is: from somemodule import somefunction.
(3) Import multiple functions from a module, the format is: from somemodule import firstfunc, secondfunc, thirdfunc.
(4) Import all functions in a certain module in the format: from somemodule import *.
(5) Import aliases, for example:

Give the module an alias, such as import random as rr. You can only use the alias in the code later, not the original name.
Give aliases to functions, such as from random import randint as rint. You can only use function aliases in the code in the future, not the original names.

7. What are the differences between os and sys modules?

The os module is responsible for the interaction between the program and the operating system, and provides an interface to access the bottom layer of the operating system, while the sys module is responsible for the interaction between the program and the Python interpreter, and provides a series of functions and variables to manipulate the environment in which Python runs. .

8. What is the purpose of the " name " attribute?

When a module is introduced by another program for the first time, its main program will all run. If you want a certain program block in the module not to be executed when the module is imported, you can use the "__name__" attribute at this time. When the value is "__main__", it indicates that the module itself is running, otherwise it is imported and needs to Note that "__name__" and "__main__" are double underscores. Example:

Insert picture description here
If the module is imported, the result of the program operation is as follows:

Insert picture description here

9. What is the purpose of the dir() function?

The built-in function dir() can find all the names defined in the module and return them as a list of characters. When the built-in dir() function does not take parameters, it returns a list of variables, methods and defined types in the current scope; when it takes parameters, it returns a list of parameter attributes and methods. If the parameter contains the method __dir__(), then the method will be called. If the parameter does not contain __dir__(), then this method will maximize the collection of parameter information.

Insert picture description here

10. What is pip?

JavaScript uses npm to manage software packages, Ruby uses gems, and .NET uses NuGet. In Python, pip is used as the standard package manager for Python. The pip command can be used to install and manage other software packages that are not part of the Python standard library. . Software package management is extremely important. Therefore, since Python 2.7.9, pip has been directly included in the Python installation package, and is also used in other Python projects. This makes pip become every Pythonista (Python user) Essential tool.

The Python installation package comes with pip, so you can use it directly. You can verify that pip is available by running the following command in the console:

Insert picture description here
The output here shows the version of pip and the installation location as well as the version of Python. You can use the following command to upgrade the pip software. Note that if you have insufficient permissions in Windows, you need to add --user:

Insert picture description here
You can use the pip list command to view which packages are installed in the environment:

Insert picture description here
The command pip install will find and install the latest version of the package (generally, in order to speed up the download, we will add the mirror source), and it will also search the dependency list in the package metadata and install these dependencies to ensure the package Meet all needs. Use the show command in pip to view the metadata information of the package. Note: In the virtual environment in Windows, --user cannot be added, otherwise an error will be reported.

Insert picture description here

11. How to generate random numbers in Python?

The module used to generate random numbers in Python is random, and you need to use import to import the module before using it.

(1) random.random(): Generate a random floating point number between 0 and 1.
(2) random.uniform(a,b): Generate floating point numbers between [a,b].
(3) random.randint(a,b): Generate an integer between [a,b].
(4) random.randrange(a,b,step): In the specified set [a,b), randomly select a number based on step.
(5) random.choice(sequence): randomly select an element from a specific sequence, where the sequence can be a string, a list, a tuple, etc.
(6) random.sample(): Randomly obtain a fragment of the specified length from the specified sequence.

Insert picture description here

12. What is the role of the pickle module?

Writing objects into files or databases is called persistent storage of data. Serialization (Serialization) is the process of converting the state information of an object into a form that can be stored or transmitted. Generally, an object is stored in a storage medium, such as a file or a memory buffer. During network transmission, it can be in byte or XML format. The byte or XML encoding format can restore exactly equivalent objects. This reverse process is also called deserialization.

In Python, objects can be serialized or deserialized with the help of the pickle module, and an object can be persisted.
(1) Save to file after serialization:

pickle.dump(对象, 文件对象)  # 序列化后存入文件
pickle.load(文件对象)  # 从文件中反序列化对象

(2) After serializing the object, put it in a string:

string = pickle.dumps(对象) # 将对象序列化后,放入字符串 
s2 = pickle.loads(string)  # 从字符串反序列化对象

For specific and detailed usage, please see the blogger Python crawler data extraction (1): parsing library json and jsonpath pickle .

Guess you like

Origin blog.csdn.net/xw1680/article/details/109645083