To what extent can Python learn to interview for a job (answer)

To what extent can Python learn to interview for a job (answer)

Visiting Zhihu, see the post to what extent can I learn Python for job interviews? , In the answer of Taohua Island Master, we talked about the latest Python interview questions in 2019, and Xudong has already done most of the answers.

Basic knowledge

  1. List 5 commonly used Python standard libraries?
import os
import sys
import re
import math
import time
import datetime
import random
import threading
import multiprocessing

2. What are the built-in data types of Python?

int, float, complex # numeric
bool # Boolean
str # string
list # list
tuple # tuple
dict # dictionary copy code

3. Briefly describe what the with method has done for me to open the processing file

  • The with statement is suitable for accessing resources to ensure that necessary cleanup operations are performed regardless of whether an exception occurs during use, and resources are released, such as automatic closing of files after use, automatic acquisition and release of locks in threads, etc.;
  • The with statement is the context manager, used in the program to indicate the environment before and after the code is executed. Context manager: The object containing the __enter__ and __exit__ methods is the context manager.
  • enter(): Before executing the with statement, execute the method first, usually returning an instance object. If the with statement has an as target, the object is assigned to the as target.
  • exit(): After executing the with statement, the __exit__() method is automatically called, and the user releases the resource. If this method returns the boolean value True, the program will ignore the exception.
  • Use environment: file reading and writing, automatic release of thread locks, etc.
with context_expression [as target(s)]:
    with-bodyCopy code

Here context_expression should return a context manager object, which is not assigned to target(s) in the as clause, but the return value of the __enter__() method of the context manager is assigned to target(s).

For those who are not clear, please refer to the link: In-depth understanding of the context manager in Python.

Python's mutable and immutable data types?

  • Immutable data type: After the data is created, the value of the data will no longer change, there are numeric, character, and primitive types;
  • Variable data type: After the data type is created, the value of the data can change, there are list, dictionary, and collection types.

5. Python gets the current date?

# -*- coding: UTF-8 -*-
import datetime
import time

if __name__ == "__main__":
    print(time.time()) # Timestamp
    print(time.strftime("%Y-%m-%d %H:%M:%S %w", time.localtime())) # year, month, day, hour, minute and second
    print(datetime.datetime.now()) # year, month, day, hour, minute, second

6. Count the number of occurrences of each word in the string.

def word_amount(sentence):
    split_list = sentence.split()
    dict_result = {}
    for word_name in split_list:
        if word_name not in dict_result.keys():
            dict_result[word_name] = 1
        else:
            dict_result[word_name] += 1
    return dict_result

if __name__ =='__main__':
    sentence = "I can because i think i can"
    dict_result = word_amount(sentence)
    print(dict_result)Copy code

or:

if __name__ =='__main__':
    sentence = "I can because i think i can"
    result = {word: sentence.split().count(word) for word in set(sentence.split())}
    print(result)Copy code

or:

from collections import Counter

if __name__ =='__main__':
    sentence = "I can because i think i can"
    counts = Counter(sentence.split())
    print(counts)Copy code

7. Use python to delete files and use linux commands to delete files.

import os
os.remove("demo.txt")Copy code
rm demo.txt copy code

8. Write a custom exception code?

class printException(Exception):
    pass

def testRaise():
    raise printException('printErr')

if __name__ =='__main__':
    try:
        testRaise()
    except printException, e:
        print ecopy code

9. Illustrate the relevant meaning of try except else finally in the exception module.

# -*- coding: UTF-8 -*-

def read_filedata(file_name):
    file_obj = ""
    try:
        # Anomalous code snippets that need to be detected
        file_obj = open(file_name, "r")
        result_data = file_obj.read()
    except IOError, e:
        # Code snippet for handling an "IOError" exception
        file_obj = "File does not exist:" + str(e)
    else:
        # Code snippets that did not cause "IOError" exception to be executed, return the read data
        return result_data
    finally:
        # Code snippets that will be executed regardless of whether an error is raised or not, isinstance() is used to determine a data type
        if isinstance(file_obj, str):
            return file_obj
        elif isinstance(file_obj, file):
            file_obj.close()
        else:
            return "Unknown error, please check your code..."

if __name__ =='__main__':
    result = read_filedata("abc.txt")
    print(result)Copy code

10. How to deal with bugs?

First check the error message, and find the corresponding code according to the error message. Generally, general data structure or algorithm errors can be solved smoothly by finding the error code;

If you encounter an error that cannot be solved temporarily, don't panic, we can use the Debug mode of the compiler or add breakpoints in the code to check the code;

If the bug still cannot be solved, we can copy the error message and search in the search engine. No one writes code without bugs. If you spend more than half an hour on a bug, you can discuss with other colleagues (pay attention to moderation, some colleagues may be costly);

Another way: There are more methods than difficulties. When doing rapid development, we should give priority to the realization of functions rather than the operation efficiency, so we can consider other implementation methods when we encounter some bugs that cannot be solved temporarily.

Language features

  1. Talk about the difference between understanding of Python and other languages?

Python is a dynamic, portable, extensible, and embeddable interpreted programming language with simple and beautiful syntax, powerful functions, and a wide range of applications. It has a powerful and complete third-party library.

The difference between a strongly typed language and a weakly typed language:

  • If the language often implicitly converts the types of variables, then the language is a weakly typed language, if it rarely does so, then it is a strongly typed language. Python rarely converts variable types implicitly, so Python is a strongly typed language.
  • The reason for strongly typed language and weak type is whether it will implicitly change the language type. The reason of strong typing may be slightly inferior to weakly-typed languages ​​in terms of speed, but the rigor brought by strongly-typed definitions avoids unnecessary errors.
  • Strongly typed languages ​​include: Java, .net, Python, C++ and other languages. Among them, Python is a dynamic language, a strongly typed language, and a type-safe language; Java is a static language, a strongly typed language, and a type-safe language; weakly typed languages ​​include: VB, PHP, JavaScript and other languages. Among them, VBScript is a dynamic language, which is a cause of type insecurity.

The difference between dynamic language and static language:

  • Dynamically typed language: A dynamic language is a language that does data type checking during runtime. That is to say, when programming in a dynamically typed language, you never need to assign a data type to any variable. The language will be assigned to a variable for the first time , Record the data type internally**. Python and Ruby are typical dynamically typed languages, and various other scripting languages ​​such as VBScript are more or less dynamically typed languages.
  • Statically typed language: The statically typed language is just the opposite of the dynamic type. Its data type is checked during compilation, which means that the data type of all variables must be declared when writing a program. C/C++ is a typical representative of statically typed languages. Others Static languages ​​include C#, Java, etc.
  • The distinction between dynamic language and static language is based on whether the data type is checked during runtime or during compilation.

The difference between compiled language and interpreted language:

  • Compiled language: a program needs to be directly translated into machine code (for non-cross-platform languages ​​such as C/C++) or intermediate code (a cross-platform language such as Java, a virtual machine is required to print the intermediate code into machine code) . Generally, it needs to go through the two steps of compile and linker. Compilation is to compile the source code into machine code, and linking is to concatenate the machine code of each module and the dependent library to generate an executable file.
  • Interpreted language: Use an interpreter to interpret the source code line by line into machine code and execute it immediately, without overall compilation and link processing, which saves a process compared to a compiled language.
  • One is like eating and waiting for the dishes to be served before starting, and the other is like eating hot pot, simmering and eating, the timing is different.
  • Advantages of interpreted languages: easy to cross-platform, only need to provide a specific platform interpreter; disadvantages: every time it runs, it has to be explained, and its performance is not as good as compiled languages.
  1. Briefly describe interpreted and compiled programming languages?

Refer to the explanation of the previous article.

3. Types of Python interpreters and related features?

  • CPython: The official version of the interpreter. This interpreter is developed in C language, so it is called CPython. Running python on the command line is to start the CPython interpreter. CPython is the most widely used Python interpreter.
  • IPython: IPython is an interactive interpreter based on CPython, that is to say, IPython is only enhanced in interactive mode, but the function of executing Python code is exactly the same as CPython. CPython uses >>> as the prompt, and IPython uses In [serial number]: as the prompt.
  • PyPy: Its goal is execution speed. PyPy uses JIT technology to dynamically compile Python code (note that it is not an interpretation), so it can significantly improve the execution speed of Python code. Most Python codes can be run under PyPy, but there are some differences between PyPy and CPython, which leads to different results when the same Python code is executed under the two interpreters.
  • Jython: Jython is a Python interpreter running on the Java platform, which can directly compile Python code into Java bytecode for execution.
  1. Tell me about the difference between Python3 and Python2 you know?

Encoding: The default encoding of Python2 is asscii, which is one of the reasons why Python2 often encounters encoding problems. As for why asscii is used as the default encoding, the reason is that Unicode has not appeared when the language of Python was born. Python3 uses UTF-8 as the default encoding by default, so you no longer need to write # coding=utf-8 at the top of the file.

String: the type of character in Python2, str: the byte sequence after encoding, unicode: the text character before encoding; and the type of character in Python3, str: the encoded unicode text character, bytes: the byte before encoding sequence.

It can be considered that the character string has two states, namely the text state and the byte (binary) state. The two character types in Python2 and Python3 correspond to these two states respectively, and then perform codec conversion between each other. Encoding is to convert a character string into bytecode, which involves the internal representation of a character string; decoding is to convert the bytecode into a character string, and display the bits as characters.

In Python2, both str and unicode have encode and decode methods. But it is not recommended to use encode for str and decode for unicode. This is a design flaw in Python2. Python3 is optimized, str has only one encode method to convert a string into a bytecode, and bytes also has only one decode method to convert a bytecode into a text string.

print: print in Python2 is a statement; print in Python3 is a function. E.g:

# py2
>>> print("hello", "world")
('hello','world')

# py3
>>> print("hello", "world")
hello worldcopy code

This example is more obvious. In py2, the print statement is followed by a tuple object, while in py3, the print function can receive multiple positional parameters. If you want to use print as a function in Python2, you can import print_function in the future module.

import: python2 imports modules and packages according to relative paths by default, and python3 imports according to absolute paths by default.

Understanding of import: The difference between python2 and python3 importing modules and packages through import

input: Python3: input parses input as str character type; Python2: input parses input as int type, raw_input parses input as str type.

Arithmetic symbol: In Python2,/performs traditional division, performs truncated division for integers, performs floating-point division (retains the fractional part, even if it is divided);//performs Floor division, truncates the remainder and returns one for the integer operand Integer, if any of the operands is a floating point number, a floating point number is returned. In Python3,/always performs true division, regardless of the type of the operand, will return a floating-point result containing any remainder;//Perform Floor division, truncate the remainder and return an integer for the integer operand, if there is any If the operand is a floating point number, a floating point number is returned.

int/long: In Python3, there is only one integer type int. In most cases, it is very similar to the long integer type in Python2. Python2 has int and long types for non-floating point numbers. The maximum value of the int type cannot exceed sys.maxint, and this maximum value is platform-dependent.

True and False: In Python2, True and False are two global variables (names), which correspond to 1 and 0 numerically. Since they are variables, they can point to other objects. Python3 fixes this defect. True and False have become two keywords, which always point to two fixed objects, and they are not allowed to be reassigned.

Iterators: Many built-in functions and methods that return list objects in Python2 have been changed to return objects similar to iterators in Python3, because the lazy loading feature of iterators makes manipulating big data more efficient.

For example: In Python2, xrange() is used to create an iterator object, and range() is used to create a list array (when you want to generate a large sequence of numbers, using xrange will have much better performance than range, because you don’t need to open it right away. A large memory space); Python3 uses range() to create an iterator object, and removes the xrange() method.

In addition, the dict.keys() and dict.values() methods of the dictionary object no longer return a list, but return it as an iterator-like view object. The higher-order functions map, filter, and zip return are not list objects. Python2's iterator must implement the next method, and Python3 changed to __iter__(), next.

nonlocal: In Python2, you can use the keyword global to declare a variable as a global variable in a function, but in a nested function, it is impossible to declare a variable as a nonlocal variable. In Pyhon3, add The keyword nonlcoal, which is generally used in closures, makes the variable use the outer variable with the same name.

Reference: https://cloud.tencent.com/developer/article/1582925 How much Python can learn to interview for a job (Answer)-Cloud + Community-Tencent Cloud