May 30, 2021 Article blog
Recently, small editors in the major blog sites always see such a question: Python learned what degree can interview the job, degree of the word, it is always difficult to grasp that point, small editor in this to collect some Python common interview questions, if you can master then you can find a junior Python development job believe is not a problem. Recommended lessons: Python3 Advanced, Python Django Framework
import os
import sys
import re
import math
import time
import datetime
import random
import threading
import multiprocessing
2. What are Python's built-in data types?
INT, FLOAT, Complex # numeric
Bool # Boolean
STR # string
List # list
Tuple # 元 组
Dict # Dictionary
3. What did we do to briefly open the processing file with the method?
上下文管理器
which is used in a program to represent the environment before and after the execution of code. C
ontext Manager: Objects with
__enter__
and
__exit__
methods are context managers.
with context_expression [as target(s)]:
with-body
Here context_expression to return a context manager object that is not assigned to target(s) in the as clause, but rather assigns the return value of the context manager's __enter__() method to target(s).
4. Python's variable and immutable data types?
import datetime
import time
Print (Time.Time ()) # Timestamp
Print (Time.StrFTIME ("% Y-% M-% D% H:% M:% S% W", time.localtime ()) # 年 日 日时 时间
Print (datetime.datetime.now ()) # 年月 日时 时间
6. Count the number of times each word appears 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)
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)
or:
from collections import Counter
if __name__ == '__main__':
sentence = "I can because i think i can"
counts = Counter(sentence.split())
print(counts)
7. Delete files with python and delete files with the linux command method.
import os
os.remove("demo.txt")
8. Write a custom exception code?
class printException(Exception):
pass
def testRaise():
raise printException('printErr')
if __name__ == '__main__':
try:
testRaise()
except printException, e:
print e
9. Give an example of what it means to try except else finally in an exception module.
def read_filedata(file_name):
file_obj = ""
try:
# 需要 异 异 代 代 片段
file_obj = open(file_name, "r")
result_data = file_obj.read()
except IOError, e:
# Code snippet that happens "orerror" exception
File_obj = "file does not exist:" + Str (e)
else:
# Do not trigger the code snippet executed by "orerror", returns the data read
return result_data
finally:
# No matter if there is an incorrect error, 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)
10. What happens when I encounter a bug?
1. Talk about the difference between what you know about Python and other languages?
Python is a dynamic, portable, scalable,
解释型
programming language with a simple, powerful, wide range
动态
applications, and a
强类型
third-party library.
Differences between strong-type languages and weak-type languages:
弱类型语言
and if it rarely does so, it is
强类型语言
P
ython rarely implicitly converts the type of variable, so Python is a strongly typed language.
Differences between dynamic and static languages:
动态类型语言
Dynamic language is a language that does data type checking during runtime, that is, dynamic type language programming never has to specify a data type to any variable, and the language records the data type internally the first time it is assigned to a variable. P
ython and Ruby are typical dynamic type languages, and other scripting languages such as VBScript are more or less dynamic type languages.
静态类型语言
Static type language is the opposite of dynamic class, its data type is checked during compilation, that is, when writing the program to declare the data type of all variables, C/C? is a typical representative of static type language, other static languages are C#, Java, and so on.
Differences between compiled and interpretive languages:
编译型语言
A program needs to be translated directly into machine code (for non-cross-platform languages such as C/C?) or intermediate code (Java, a cross-platform language, requires a virtual machine to print the intermediate code into a machine code). T
ypically, there are two steps to compile (compile) and linker. C
ompilation is the compilation of the source code into machine code, the link is to each module of the machine code and rely on the library string together to generate executable files.
解释型语言
Use the interpreter to interpret the source code line by line into machine code and execute it immediately, without holistic compilation and link processing, saving a process compared to the compiled language.
2. Briefly describe the explanatory and compiled programming languages?
Refer to the explanation in the previous article.
3. What kind of interpreter is Python and its associated characteristics?
CPython
The official version of the interpreter. T
his interpreter was developed in C language, so it's called CPython. R
unning python on the command line is starting the CPython interpreter. C
Python is the most widely used Python interpreter.
IPython
IPython is an interactive interpreter based on CPython, which means that IPython is only enhanced in the way it interacts, but performs the same functionality as CPython. C
Python uses >>> as a prompt, while IPython uses I n (serial number): as a prompt.
PyPy
Its goal is execution speed. P
yPy uses J IT technology to dynamically compile Python code (note that it's not an explanation), so it can significantly speed up the execution of Python code. M
ost Python code can run under PyPy, but some of PyPy and CPython are different, which results in the same Python code executing under two interpreters that may have different results.
Jython
: Jython is a Python interpreter running on a Java platform that compiles Python code directly into Java bytecode execution.
IronPython
IronPython is similar to Jython, except that IronPython is a Python interpreter running on The Microsoft .Net platform that compiles Python code directly into .Net bytecodes.
4. Tell me what you know about the difference between Python3 and Python2?
编码
:P the default encoding for ython2 is asscii, which is one of the reasons why coding problems are common in Python2, as to why asscii is used as the default encoding because the language of Python was born without Unicode. P
ython3 uses UTF-8 as the default encoding by default, so you no longer need to write on top of the file.
字符串
:P the type of character in ython2, str: encoded byte sequence, unicode: text character before encoding, while Python3 character type, str: encoded unicode text character, bytes: bytes: byte sequence before encoding.
Strings can be thought of as having two states, the text state and the byte (binary) state. B oth character types in Python2 and Python3 correspond to these two states, and then codec transformations are made to each other. Encoding is converting a string into a bytecode, involving the internal representation of a string;
In Python2, both str and unicode have encode and decode methods. H owever, it is not recommended to use encode for str and decode for unicode, which is a flaw in the Python2 design. Python3 is optimized, str has only one encode method that converts strings into a bytecode, and bytes has only one decode method that converts bytecodes into a text string.
print
:P print in ython2 is a statement; F
or example:
>>> print("hello", "world")
('hello', 'world')
# py3
>>> print("hello", "world")
hello world
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 position parameters. I
f you want to use print as a function in Python2, you can import print_function in the future module.
import
:p ython2 import modules and packages by default, and python3 imports by absolute path by default.
input
:P ython3:input resolution input is str character type, Python2:input resolution input is int type, raw_input parsing input is str type.
算法符
In Python2, / performs traditional division, for integers to perform truncation division, floating points perform floating-point division (retaining fractional parts, even if divided); / Performs floor division, truncates the remainder and returns an integer for integer operands, and returns a floating number if any of the operands are floating points. I
n Python3, / always performs true division, returning floating-point results that contain any remaining number regardless of the type of operand;
int/long
:P ython3, there is only one integer type int, and in most cases it resembles the long integer in Python2. P
ython2 has int and long types for non-floating points. T
he maximum value of the int type cannot exceed sys.maxint, and this maximum value is platform-dependent.
True和False
In Python2, True and False are two global variables (names) that correspond numerically to 1 and 0, respectively, and since they are variables, they can point to other objects. P
ython3 corrects this flaw, and True and False become two keywords that always point to two fixed objects and are no longer allowed to be re-assigned.
迭代器
Many of the built-in functions and methods that return list objects in Python2 have been changed in Python3 to return objects similar to iterators because of the inert loading nature of iterators that make iterations more efficient to manipulate big data.
For example, Python2 uses xrange() to create an iterator object, range() to create a list array (xrange performs much better than range when generating a large sequence of numbers, because you don't need to come up with a large piece of memory space) ;P ython3 uses range(range) to create an iterator object and remove the xrange() method.
In addition, the dict.keys() and dict.values() methods of dictionary objects are no longer returned to the list, but are returned as a view object similar to an iterator. H igher-order functions map, filter, and zip also return list objects. The iterator of Python2 must implement the next method, and Python3 is changed to __iter__(), next.
nonlocal
In Python2 you can declare a variable as a global variable with the keyword global in a function, but in nested functions, it is not possible to declare a variable as a non-local variable, and in Pyhon3, the keyword nonlcoal is added, which is generally used in closures so that the variable uses the outer variable of the same name.
Understanding of
LEGB
scope: python3's local, global, nonlocal brief
5. What is the difference between int and long in Python3 and Python2?
Refer to the explanation in the previous article.
6. What is the difference between xrange and range?
You can refer to the explanation in the previous article.