Go to Zhihu , See the post Python Learn how much you can interview for a job ?
, stay Peach Blossom Island owner
In his reply, he said 2019 The latest Python Interview questions , As well as Xudong
The big guy has done most of the answers .
In a few posts, the blogger will , Combined with the big guy's answer , Answer these questions in more detail .
Source code of this article github Address :https://github.com/yngzMiao/yngzmiao-blogs/tree/master/2020Q1/20200103.
import os
import sys
import re
import math
import time
import datetime
import random
import threading
import multiprocessing
int、float、complex # Numerical type
bool # Boolean type
str # character string
list # list
tuple # Tuples
dict # Dictionaries
Context manager
, It is used to represent the environment before and after code execution . Context manager : contain __enter__
and __exit__
The object of the method is the context manager .with context_expression [as target(s)]:
with-body
here context_expression want Returns a context manager object , This object is not assigned to as In Clause target(s), It's the context manager __enter__() The return value of the method is assigned to the target(s).
Not very clear can refer to the link : In depth understanding of Python Context manager in .
# -*- coding: UTF-8 -*-
import datetime
import time
if __name__ == "__main__":
print(time.time()) # Time stamp
print(time.strftime("%Y-%m-%d %H:%M:%S %w", time.localtime())) # Mm / DD / yyyy HHM / S
print(datetime.datetime.now()) # Mm / DD / yyyy HHM / S
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)
perhaps :
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)
perhaps :
from collections import Counter
if __name__ == '__main__':
sentence = "I can because i think i can"
counts = Counter(sentence.split())
print(counts)
import os
os.remove("demo.txt")
rm demo.txt
class printException(Exception):
pass
def testRaise():
raise printException('printErr')
if __name__ == '__main__':
try:
testRaise()
except printException, e:
print e
# -*- coding: UTF-8 -*-
def read_filedata(file_name):
file_obj = ""
try:
# Exception code fragment to detect
file_obj = open(file_name, "r")
result_data = file_obj.read()
except IOError, e:
# happen “IOError” Code snippet for exception handling
file_obj = " file does not exist :"+ str(e)
else:
# Did not trigger “IOError” Code snippet for exception execution , Return the data read
return result_data
finally:
# Code snippets that execute with or without an error ,isinstance() 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)
Python It's a simple and beautiful grammar , It's powerful , It has a wide range of applications , A gate with a powerful and complete third-party library Strong type
Of dynamic
, portable , Scalable , Embeddable interpreted
programing language .
Strong type language 、 The difference between weakly typed languages :
Weak type language
, If it's rarely done , That's it Strong type language
.Python Rarely implicitly convert variable types , therefore Python It's a strong type of language .Dynamic language 、 The difference between static languages :
Dynamic type language
: Dynamic languages are languages that do data type checking only during runtime , That is to say, dynamic type language programming , Never assign a data type to any variable , The language will be assigned to variables the first time , Record data types internally **.Python and Ruby Is a typical dynamic type language , Other scripting languages such as VBScript It's more or less dynamic . Static type language
: Static type languages are the opposite of dynamic classes , Its data type is checked during compilation , That is to say, the data type of all variables should be declared when writing the program ,C/C++ Is a typical representative of static type language , Other static languages include C#、Java etc. .Compiler language 、 The difference between interpretative languages :
Compiler language
: You need to translate a program directly into machine code ( about C/C++ This non platform language ) Or middle size (Java This cross platform language , The virtual machine is needed to print the middle code into machine code ). Generally, it needs to be compiled (compile)、 link (linker) These two steps . Compiling is to compile source code into machine code , Link is to connect the machine code of each module with the dependency library to generate the executable file . Explanatory language
: Use the interpreter to interpret the source line by line into machine code and execute it immediately , There will be no overall compilation and link processing , Compared with compiled language, it saves a process .Please refer to the previous explanation .
CPython
: The official version of the interpreter . This interpreter uses C Language development , So called CPython. Run on the command line python That is to start. CPython Interpreter . CPython Is the most widely used Python Interpreter .IPython
:IPython Is based on CPython An interactive interpreter on top , in other words ,IPython It's just a little bit more interactive , But to perform Python Code functions and CPython It's exactly the same .CPython use >>> As a prompt , and IPython use In [ Serial number ]: As a prompt .PyPy
: its The goal is speed of execution .PyPy use JIT technology , Yes Python Dynamic compilation of code ( Notice it's not an explanation ), So it can be significantly improved Python Code execution speed . most Python Code can be found in PyPy Run under , however PyPy and CPython Some are different , This leads to the same Python Code execution under two interpreters may have different results .Jython
:Jython Is running on the Java On the platform Python Interpreter , You can directly Python Code compiled into Java Bytecode execution .IronPython
:IronPython and Jython similar , It's just IronPython It's running at Microsoft .Net On the platform Python Interpreter , You can directly Python Code compiled into .Net Bytecode . code
:Python2 The default encoding for is asscii, It also leads to Python2 One of the reasons we often encounter coding problems in , As for why we use asscii As default encoding , The reason lies in Python The language was not born yet Unicode.Python3 By default UTF-8 As default encoding , So you don't have to write at the top of the file # coding=utf-8 了 .
character string
:Python2 The type of Chinese characters ,str: The sequence of bytes that have been encoded ,unicode: Text characters before encoding ; and Python3 The type of Chinese characters ,str: Code of unicode Text character ,bytes: Sequence of bytes before encoding .
You can think of a string as having two states , That is, text status and bytes ( Binary system ) state .Python2 and Python3 Both character types in correspond to these two states respectively , And then encode and decode each other . Encoding is to convert a string into bytecode , It's about the internal representation of strings ; Decoding is the conversion of bytecode to string , Display bits as characters .
stay Python2 in ,str and unicode There are encode and decode Method . But not recommended for str Use encode, Yes unicode Use decode, This is a Python2 Defects in design .Python3 It's optimized ,str only one encode Method to convert a string to a bytecode , and bytes There is only one decode Method to convert bytecode to a text string .
print
:Python2 Medium print Is the statement ;Python3 Medium print Is the function . for example :
# py2
>>> print("hello", "world")
('hello', 'world')
# py3
>>> print("hello", "world")
hello world
This example is obvious , stay py2 in ,print The statement is followed by a tuple object , And in the py3 in ,print Function can receive multiple position parameters . If you want to Python2 Zhongba print When a function uses , Then you can import future Module print_function.
import
:python2 The default is to import modules and packages according to the relative path ,python3 The default is to import by absolute path .
import The understanding of the :python2 and python3 adopt import The difference between the import module and the package
input
:Python3:input The parsing input is str Character ;Python2:input The parsing input is int type ,raw_input The parsing input is str type .
Algorithmic symbols
: stay Python2 in ,/ Perform traditional division , Perform truncation division on integers , Floating point performs floating-point division ( Keep the decimal part , Even if you divide );// perform Floor division , Truncates the remainder and returns an integer for the integer operand , If any of the operands are floating-point numbers , Returns a floating-point number . stay Python3 in ,/ Always perform true Division , Regardless of the type of operand , Will return a floating-point result with any remainder ;// perform Floor division , Truncates the remainder and returns an integer for the integer operand , If any of the operands are floating-point numbers , Returns a floating-point number .
int/long
:Python3 in , There is only one integer type int, Most of the time , It's very much like Python2 The long shape of Li .Python2 There's something for non floating point numbers int and long type .int The maximum value of type cannot exceed sys.maxint, And this maximum is platform related .
True and False
: stay Python2 in ,True and False It's two global variables ( name ), In numerical terms, they correspond to 1 and 0, Since it's a variable , Then they can point to other objects .Python3 Fixed this bug ,True and False Change to two keywords , Always point to two fixed objects , It is not allowed to be reassigned .
iterator
: stay Python2 Many of the built-in functions and methods that return list objects in Python3 All changed to return objects similar to iterators , Because the iterator's lazy loading feature makes it more efficient to operate big data .
for example :Python2 Use in xrange() To create an iterator object , Use range() Create a list Array ( To generate a large sequence of numbers , use xrange than range It's a lot better , Because it doesn't need to open up a large memory space );Python3 Use in range() Create iterator object , Removed xrange() Method .
in addition , Of dictionary objects dict.keys()、dict.values() Methods are no longer returned to the list , But with an iterator like view Object returns . Higher order function map、filter、zip None of the returned objects are list objects .Python2 The iterator of must implement next Method , and Python3 Changed to __iter__()、next.
nonlocal
: stay Python2 You can use keywords in functions global Declare a variable as a global variable , But in nested functions , It's impossible to declare a variable as a nonlocal variable , stay Pyhon3, New keyword nonlcoal, Commonly used in closures , Make the variable use the outer variable with the same name .
LEGB
Understanding of scope :python3 Of local, global, nonlocal analysis
Please refer to the previous explanation .
Please refer to the explanation above .