Hi, I’m Rocky0429.

In terms of learning Python, many friends told me that they didn’t know what level they were at and what stage they were at. In fact, it is very simple. As the saying goes, practice is the only criterion for testing truth. How do you practice it? I feel like I’m going to an interview.

A lot of students may listen to the interview, hurriedly shook his head, feel that their level is not enough to interview time. But it’s not as complicated as you think. The interview is just to ask you some questions and you answer them. Answer on, answer not to go back to learn. This is like us from small to large in school, the teacher asked questions in class, each of us should be the interview of the strong.

Of course, I have to prepare for the interview, just like we do before the exam, so I combined my own experience to compile the best interview questions in Python.

At the end of the article, there is a PDF version, which can also be viewed offline!

In the beginning, I will start from Python foundation, Advanced Python, Python background development to crawler, machine learning, and with detailed answers, whether preparing for the interview or learning, this interview question is definitely worth your reading and learning.

1. What is Python?

Python is a programming language with objects, modules, threads, exception handling, and automatic memory management that can be compared to other languages.

Python is an interpreted language. Python does not need to be interpreted before code is run.

Python is a dynamically typed language. When you declare variables, you do not need to specify the type of the variable.

Python is well suited for object-oriented programming because it supports the definition of classes through composition and inheritance.

In Python, functions are first class objects.

Python code is fast to write, but generally slower to run than compiled languages.

Python is so versatile that it is often used as a “glue language” to help improve the health of other languages and components.

With Python, programmers can focus on the design of algorithms and data structures without dealing with the low-level details.

2. What is the difference between assignment, shallow copy and deep copy?

(1) assignment

In Python, assignment to an object is simply an object reference, unlike C++, as follows:

A = [1,2,"hello",['python', 'C++']] b = aCopy the code

In this case, A and B are the same, they point to the same piece of memory, and B is just an alias for A, a reference.

We can also use the id() function to see if the two lists have the same address.

Assignment (which includes an object as a parameter and returns a value) does not open up new memory space; it simply copies the reference to the object. In other words, there is no memory overhead other than the name B. If you change A, it affects B, and likewise, if you change B, it affects A.

(2) shallow copy

A shallow copy creates a new object whose content is not a reference to the original object itself, but a reference to the first layer of objects within the original object.

Shallow copies come in three forms: slicing operations, factory functions, and the copy function in the Copy module.

For example, in list A above, slice: b = a[:] or b = [x for x in a];

B = list(a);

Copy function: b = copy. Copy (a);

The shallow copy of list B is no longer list A. Using is, you can see that they are not the same object, and using ID, they do not point to the same memory space. But when we use id(x) for x in a and id(x) for x in b to look at the addresses of the elements in a and B, we can see that the addresses of the elements in both are the same.

In this case, lists A and B are different objects, and modifying list B theoretically does not affect list A.

Note, however, that the shallow copy is so called because it only copies one layer, and there is a nested list in list A. If we modify it, the situation changes.

Such as: A [3].append(‘ Java ‘), look at list B, and see that list B has also changed. This is because if we change the nested list, we change the outer elements, we change the references to it, so that they point to something else, and we change the elements in the nested list, the address of the list has not changed, so that it points to the same location.

(3) copies

There is only one form of deepcopy, the deepcopy() function in the copy module.

A deep copy corresponds to a shallow copy. A deep copy copies all elements of an object, including multiple nested elements. Therefore, its time and space overhead is high.

If b = copy. Deepcopy (a) is used for list a, changing list b will not affect list a, even if the nested list has a deeper level, because the object copied from the deepcopy is completely new and no longer associated with the original object.

(4) pay attention to the point

For non-container types, such as numbers, characters, and other “atomic” types, there is no copy; all references to the original object are produced.

If the tuple variable value contains an object of atomic type, only a shallow copy will be obtained, even if a deep copy is taken.

3,initAnd __new__?

When we use “class name ()” to create an object, the Python interpreter does two things for us: the first is to allocate space for the object in memory, and the second is to initialize the object. “Allocate space” is the __new__ method, and initialization is the __init__ method.

The new method internally does two things: the first thing is to “allocate space for the object” and the second thing is to “return a reference to the object to the Python interpreter.” When the Python interpreter gets a reference to an object, it passes the reference to init’s first argument, self. Once init gets a reference to the object, init can define instance properties for the object inside the method.

The reason why we need to learn new methods is because we need to modify the method of allocating space so that when we use “class name ()” to create an object, no matter how many times we execute it, only one instance of the object will be created in memory, thus achieving the purpose of singleton design pattern.

Also, I packaged it as a PDF for easy reading.

The 200 best Interview Questions in Python

4. Python variables, Objects, and references?

First throw out the conclusion:

  • A variable is a pointer to the memory space that holds the connection to the object;

  • Objects are chunks of memory that represent the values they represent;

  • A reference is an automatically formed pointer from a variable to an object.

Here’s how:

When you use variables in Python, you don’t need to declare them and their types in advance, and they work fine. In Python, this is done in a very fluid way, so let’s take a = 1 as an example and see what that looks like.

First is how to know to create a variable, the variable a, or variable names a, when the program is assigned to it for the first time created it, in fact, the truth is the Python in the code to run before they go to detect variable names, we do not to delve into the specific, you need only as “the first assignment to create a variable”.

Another is how to know what type a variable is: in fact, many people do not understand this, the concept of “type” does not exist in variables, but in objects. The variable itself is generic; it just happens to refer to a particular object at a certain point in time. In an expression, for example, the variable we use is immediately replaced by the specific object it is referring to at the time.

This is an obvious difference between a dynamic language and a static language. For starters, dynamic typing is easy to understand if you’re comfortable separating “variables” from “objects.”

Using a = 1 as an example, it’s easy to see how Python executes the assignment statement for a = 1: Create an object representing value 1 –> create a variable a –> concatenate variable a with object 1. Let me use a graph to illustrate it more clearly:

As we can see from the figure above, the variable A actually becomes a reference to object 1. If you’ve learned about Pointers, you’ll notice that internally, “a variable is just a pointer to an object’s memory space.”

Also from the figure above, we can see that in Python a “reference” is a connection from a variable to an object. It is a relationship, implemented as a pointer in memory.

5. How to save memory by creating mega instances?

You can define a slot attribute for a class that declares a list of instance attributes that can be used for memory reduction purposes.

Specific explanation:

First, let’s define a normal User class:

class User1:
    def __init__(self, id, name, sex, status):
        self.id = id
        self.name = name
        self.sex = sex
        self.status = status
Copy the code

Then define a class with a slot:

class User2:
    __slots__ = ['id', 'name', 'sex', 'status']
    def __init__(self, id, name, sex, status):
        self.id = id
        self.name = name
        self.sex = sex
        self.status = status
Copy the code

Next create two instances of the class:

U1 = User1 (' 01 ', 'rocky' and 'male', 1) u2 = User1 (' 02 ', 'leey' and 'male', 1)Copy the code

We already know that U1 uses more memory than U2, so we can think of it this way: U1 must have more properties than U2. Let’s look at the properties of U1 and U2 separately:

['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'id', 'name', 'sex', 'status']
Copy the code
['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__slots__', '__str__', '__subclasshook__', 'id', 'name', 'sex', 'status']
Copy the code

At first glance, this may not seem like much, but let’s take a look at what the difference is:

set(dir(u1)) - set(dir(u2))
Copy the code

By taking the difference set of sets, we get the specific difference in properties of U1 and U2:

{'__weakref__', '__dict__'}
Copy the code

When we don’t use weak references, weakref doesn’t take up much memory, so eventually the pot will be backed by dict.

Let’s take a look at dict:

u1.__dict__
Copy the code

The output is as follows:

{' id ':' 01 ', 'name' : 'rocky', 'sex' : 'male', 'status' : 1}Copy the code

Output a dictionary, inside which we find the properties we just defined in the class, and that dictionary is a dictionary for dynamically binding properties of the instance. How do we dynamically bind them? For example, we don’t have u1.level, so we can dynamically bind a level attribute to it, such as u1.level = 10, and then we can look at the dictionary:

u1.__dict__
Copy the code

The output now looks like this:

{' id ':' 01 ', 'name' : 'rocky', 'sex' : 'male', 'status' : 1, the' level ': 10}Copy the code

So you see level entering into this dictionary.

This dynamic binding property comes at the expense of memory, since the dict itself is memory intensive. Let’s verify this:

import sys
sys.getsizeof(u1.__dict__)
Copy the code

We use the getSizeof method in the sys module, which can get the memory used by an object:

112
Copy the code

We can see that this dictionary takes up 112 bytes. U2, on the other hand, does not have dict, and we want to add an attribute to it, which is also rejected.

u2.level = 10
Copy the code

The following output is displayed:

AttributeError: 'User2' object has no attribute 'level'
Copy the code

How to generate random numbers in Python?

The module used to generate random numbers in Python is random, which requires import before it can be used. The following examples may be given as appropriate:

Random.random () : Generates a random floating point number between 0 and 1

Random. Uniform (a, b) : generates floating point numbers between [a,b]

Random. Randint (a, b) : Generates an integer between [a,b]

Random. Randrange (a, b, step) : Randomly selects a number in the specified set [a,b] with step as the base

Random. Choice (sequence) : Takes an element at random from a particular sequence. The sequence can be a string, a list, a tuple, etc.

Is Python a strong or weak language type?

Python is a strongly typed dynamic scripting language.

Strong typing: Different types are not allowed to add. Dynamic: does not use a display datatype declaration and determines the type of a variable when it is first assigned. Scripting languages: Also generally interpreted languages, which require only an interpreter to run code, no compilation is required.

What is an interpreted language and what is a compiled language?

Computers can’t understand high-level languages directly, they can only understand machine languages directly, so they have to translate high-level languages into machine languages before they can execute programs written in high-level languages.

Interpreted languages translate when the program is running.

Before a program written in a compiled language can be executed, a special process is required to compile the program into machine language (executable files).

Is there a log in Python? How does it work?

The logging module in Python calls logging.basicconfig () to configure the required log level and parameters. The Python interpreter generates logs based on the configured parameters.

Supplementary knowledge:

Python’s standard logging module

The Logging module is available in the Python standard library. In its simplest use, logging prints logs to the screen by default. We can import the logging module directly and log with debug, INFO, WARN, Error, and critical functions. The default logging level is Warning. Logs with a level higher than warning (critical > Error > Warning > Info > Debug) are displayed. The level is a logical concept that identifies the importance of logs.

import logging

logging.debug('debug message')
logging.info("info message")
logging.warn('warn message')
logging.error("error message")
logging.critical('critical message')
Copy the code

The execution result of the above code is as follows:

WARNING:root:warn message
ERROR:root:error message
CRITICAL:root:critical message
Copy the code

As I said above, print produces so much information that it’s hard to find anything really useful. By splitting logs into different levels, logging improves performance and analysis by keeping only higher-level logs most of the time, so you can quickly find errors in a large log file.

Configuring the Log Format

Before logging, let’s do some simple configuration:

import logging

logging.basicConfig(filename= 'test.log', level= logging.INFO)

logging.debug('debug message')
logging.info("info message")
logging.warn('warn message')
logging.error("error message")
logging.critical('critical message')
Copy the code

When you run the above code, you will create a test.log file in the current directory. This file will store info and above logs. Run it once and the result looks like this:

INFO:root:info message
WARNING:root:warn message
ERROR:root:error message
CRITICAL:root:critical message
Copy the code

In the example above, I used basicConfig for simple logging configuration, but there are more complex configuration options, so let’s take a look at some of the concepts in logging:

Logger: The Logger is an interface that can be used directly by the application. Handler: Indicates where and for how long logs are stored. Formatter: Formats, which is used to configure the output format of logs.Copy the code

A Logger uses a Handler, and a Handler uses a Formatter. So now that we know the concepts, how do we use them? There are a number of ways to configure a file in our logging program. The simplest is to use basicConfig, and the more complex one is to save the log configuration in a configuration file and then read the configuration file in the main program using fileConfig.

The log file contains all logs of debug level and above. Each log file should contain the time, level and content of the log. Try it out for yourself, and if you’ve finished, read on:

import logging

logging.basicConfig(
   level= logging.DEBUG,
   format = '%(asctime)s : %(levelname)s : %(message)s',
   filename= "test.log"
)

logging.debug('debug message')
logging.info("info message")
logging.warn('warn message')
logging.error("error message")
logging.critical('critical message')
Copy the code

A run of the above code results as follows:

2018-10-19 22:50:35,225: DEBUG: DEBUG message 2018-10-19 22:50:35,225: INFO: INFO message 2018-10-19 22:50:35,225: WARNING: WARN message 2018-10-19 22:50:35,225: ERROR: ERROR message 2018-10-19 22:50:35,225: CRITICAL: critical messageCopy the code

As I said earlier, for more complex applications you can save the logging configuration in a configuration file and then read the configuration file in the main program using fileConfig. Let’s take a look at a typical logging configuration file named logging.conf:

[loggers]
keys = root

[handlers]
keys = logfile

[formatters]
keys = generic

[logger_root]
handlers = logfile

[handler_logfile]
class = handlers.TimedRotatingFileHandler
args = ('test.log', 'midnight', 1, 10)
level = DEBUG
formatter = generic

[formatter_generic]
format = %(asctime)s %(levelname)-5.5s [%(name)s:%(lineno)s] %(message)s
Copy the code

In the preceding log configuration file, we first declare a logger called root in the loggers and a logfile handler in the handlers. A formatter named generic is declared in [formatters]. In [logger_root], define which handler is used by the root logger. [handler_logfile] defines how the log handler outputs logs, the time to switch log files and so on. Finally, [formatter_generic] defines the log format, including log generation time, level, file name, line number and other information.

With the above configuration file in hand, we can use the fileConfig function of the logging.conf module to load the logging configuration in the main code:

import logging
import logging.config

logging.config.fileConfig('logging.conf')

logging.debug('debug message')
logging.info("info message")
logging.warn('warn message')
logging.error("error message")
logging.critical('critical message')
Copy the code

Running the above code once results in something like this:

2018-10-19 23:00:02,809 WARNI [root:8] warn message 2018-10-19 23:00:02,809 ERROR [root:9] 2018-10-19 23:00:02,809 CRITI [root:10] Critical messageCopy the code

10. How does Python convert?

The built-in functions encapsulate various conversion functions. You can use the target type keyword to cast, and the conversion between bases can use int(‘ STR ‘, base=’n’) to convert a specific base string to decimal, and the corresponding base conversion function to convert decimal to the target base.

Direct conversions can be made using built-in functions:

list---->tuple tuple(list)
tuple---->list list(tuple)
Copy the code

Also, I packaged it as a PDF for easy reading.

The 200 best Interview Questions in Python

11. Scope in Python?

In Python, the scope of a variable is always determined by where it is assigned in the code. When Python encounters a variable it searches in this order:

Local –> Enclosing locals where the current scope is embedded –> Global –> built-in.

12. What is Python introspection?

Python introspection is the ability of Python to enable programmers to write programs in the object-oriented language to obtain python-like versions of objects at runtime.

Python is an interpreted language that gives programmers a great deal of flexibility and control.

13. What is a Python namespace?

The name space, also known as namesapce, is a term that appears in many programming languages.

Global variables & local variables

Global and local variables are the beginning of our understanding of namespaces. Let’s look at this code first:

x = 2
def func():
   x = 3
   print('func x ---> ',x)

func()
print('out of func x ---> ',x)
Copy the code

The output of this code is as follows:

func x ---> 3
out of func x ---> 2
Copy the code

As you can see from the above results, running func() outputs object 3 referenced by the variable x in func(), followed by the last line of code. The first x outputs the variable x inside the function, and the second x outputs the variable x outside the function. The two variables do not affect each other, and they operate in their respective scopes.

The variable that only works within the function is called a “local variable.” With “local” there is a corresponding “all,” but the latter sounds ambiguous, so it is called “global.”

X = 2 def func(): global x = 3 # def func(): global x = 3Copy the code

X = global; x = global; x = global; x = global;

func x ---> 3
out of func x ---> 3
Copy the code

At first glance, this may seem like a global variable, which can be used to control the inside and outside of the function. However, we should be careful to use global variables, because after all, the inside and outside are different, and do not cause confusion.

scope

A scope, in plain English, is the part of a program where variables are associated with objects. For example, as I said above, x = 2 and x = 3 are in two different scopes.

Generally, scope is divided into static scope and dynamic scope. Although we say that Python is a dynamic language, its scope belongs to static scope. That is, the scope of a variable in Python is determined by its place in the program.

In Python, scoping is divided into four levels: local, enclosing, global, and built-in. In the previous section, we first searched the local scope of the variable x, and then the global scope outside of the function. For example:

def out_func():
   x = 2
   def in_func():
       x = 3
       print('in_func x ---> ',x)
   in_func()
   print('out_func x ---> ',x)

x = 4
out_func()
print('x == ',x)
Copy the code

The result of running the above code is:

in_func x ---> 3
out_func x ---> 2
x == 4
Copy the code

Take a closer look at the above code and the results of the operation, and you will see the pattern of variables searching in different scopes. Is this something that you have been missing before?

The namespace

Wikipedia says that “namespaces are a special kind of abstraction of scopes.” Here’S an example to illustrate:

Such as zhang SAN in A company, his work number is 111, li si in company B, his work number is 111, because the two different companies, both of them working status can be the same but does not cause confusion, the company said A separate namespace, if two people are A company, their work number cannot be the same, Otherwise you don’t know who it is just by looking at the id.

In fact, the feature of the above example is why we use namespaces. In large computer programs, there are often hundreds or thousands of identifiers, and namespaces provide a mechanism for hiding area identifiers. By grouping logically related identifiers into response namespaces, you can make the entire system more modular.

The Wikipedia quote I quoted at the beginning that “a namespace is a special abstraction of a scope” actually contains identifiers within that scope and is itself represented by an identifier. In Python, namespaces can be nested because their identifiers belong to one of the outer namespaces, and they live together under the “global namespace”.

In short, different namespaces can exist simultaneously, but independently of each other. Namespaces, of course, vary depending on the object, and can be divided into the following categories:

  • 1. Local namespaces: When a module has a function or class, the namespace defined by each function or class is the local namespace. When the function returns a result or throws an exception, the local namespace ends.

  • 2. Global namespaces: Each module creates its own global namespaces. The global namespaces of different modules are independent of each other.

  • Built-in namespaces: They exist when Python is running. The namespaces of built-in functions belong to built-in namespaces, so we can run them directly in any program.

Programs query namespaces in a certain order: local namespaces, global namespaces, built-in namespaces.

def fun(like):
   name = 'rocky'
   print(locals())

fun('python')
Copy the code

Accessing the local namespace using locals, let’s see the result:

{'name': 'rocky', 'like': 'python'}
Copy the code

As you can see from the above results, the structure of the data store in a namespace is the same as that of a dictionary. As you might have guessed, when we want to access the global namespace, we use globals.

There is also a life cycle issue with namespaces, which is when a namespace appears and when it disappears. This is understood to be the part of the namespace that is read into memory. As we said above, when Python starts, the built-in namespaces are created.

14. What code specifications are you following?

PEP 8 coding style

Python code, at first glance, is simple, elegant, and readable, which is what we call a “high level of appearance.” On the one hand, Python’s excellent design, such as uniform locking and no redundant symbols, makes the code more concise. On the other hand, because it has a fairly uniform coding style, which is not mandatory but recommended, the compiler that writes Python code automatically provides PFP 8 checks that warn you and suggest fixes if your code violates the PEP 8 specification. At the same time, there are specialized inspection tools that examine Python’s code style.

After all, you won’t be able to write code by yourself. In the future, whether it’s in a company or some open source project, you will definitely want to be a part of the public in terms of style.

The PEP 8 coding specification gives detailed instructions on how to code Python, including alignment, package import order, whitespace and comments, naming conventions, and detailed examples.

Let me take a look at the specific programming instructions given by PEP 8, using the import of “packages” as an example. In Python, import should only be one module at a time, with each module on a single line:

import pandas
import numpy
Copy the code

Negative example:

import pandas,numpy
Copy the code

If you want to import more than one module, you can do something like this:

from subprocess import Popen, PIPE
Copy the code

The import statement should be at the top of the source file, after module comments and docstrings, and before global variables and constants. When importing different libraries, group them in the following order, separated by blank lines:

  • Import the standard library module

  • Import related third-party library modules

  • Import the current application/library module

Specific examples are shown as follows:

import os
import time

import psutil

from test import u_test,my_test
Copy the code

Python also supports relative and absolute imports, but absolute imports are strongly pushed here. Because absolute imports are more readable, they are less error-prone and give more detailed error information if they do. The details are as follows:

from sub_package import tools
from sub_package.tools  import msg
Copy the code

Of course, there’s more to package specification than that. The PEP 8 coding style guide is long and written in great detail, so I won’t go into it here. For more information, see the Python website.

Pycodestyle checks the code specification

As I said above, PEP 8 is just the official specification for Python coding, not mandatory, but because everyone uses it, it becomes the de facto standard for Python coding style, and since it is the standard, there should be a tool to check it. This will help Python players to standardize their code, and it will also help people in open source or working to create a uniform code style.

To that end, a command line tool of the same name is provided to check if Python code is violating the PEP 8 specification and to prompt if it is.

pip install pep8
Copy the code

The name of the specification is PEP 8, and the command line tool for checking codestyle is called Pep8, which can be confusing, so the father of Python suggested renaming Pep8 to PyCodeStyle. Let’s take a look at the usage of PyCodeStyle.

Install PIP first:

pip install pycodestyle
Copy the code

Run PyCodeStyle on one or more files to print the check report:

Use –show-source to display nonconforming source code for programmers to modify, as shown below:

Autopep8 formatting code

Autopep8, which automatically formats Python code into the PEP 8 style, uses the PyCodeStyle tool to determine which parts of the code need to be formatted, which fixes most of the typographical problems reported in pyCodeStyle tools. Autopep8 itself is also a tool written in Python, so we can still install it directly with PIP:

pip install autopep8
Copy the code

It is also very simple to use, as shown below:

autopep8 --in-place test_search.py
Copy the code

The above code, without –in-place, outputs the formatted autopep8 code directly to the console. We can check for changes in Autopep8 in this way, and using –in-place saves the results directly to the source file. Here I continue with the py file I used in the previous example, which looks like this:

In the example above, Autopep8 fixed all the issues without a hitch, but if you look at the source file at this time, you will see that the content of the source file is the same as before, and has not been changed. This is where we use –in-place. With this option, there will be no output; autopep8 will directly modify the source file.

autopep8 --in-place test_search.py
Copy the code

15. What can be done to improve the performance of Python programs?

1. Use multi-process to make full use of the multi-core performance of the machine

2, for the performance of the large part of the code, can be written in C or C++

3. The performance impact caused by I/O blocking can be solved by using I/O multiplexing

4. Use Python’s built-in functions whenever possible

5. Use local variables whenever possible

What is the difference between the items() method of dict and the iterItems () method?

The items method returns all the dictionaries as a list, where the items are returned in no particular order

The iterItems method has a similar effect, but returns an iterator object

17. What is the difference between os.path and sys.path?

Os. path is a module that contains various functions for handling long filenames (pathnames).

Sys. path is a list of directory names from which Python finds extension modules (Python source modules, compiled modules, or binary extensions). When Python is started, this list is initialized from the contents of the PYTHONPATH environment variable, the registry (for Windows systems), and so on, according to the built-in rules.

18, 4G memory how to read a 5G data?

Method one:

Through the generator, the data is read multiple times, each time a relatively small amount of data (such as 500MB) is read for processing, and the next 500MB of data is read after processing.

Method 2:

You can split the data into small files by using the Linux command split and then process the data. This method is more efficient. It can be cut by line number, it can be cut by file size.

In Linux using split file split: mode 1: specify the number of lines after the split file and TXT file, you can specify the number of lines after the split file to split the file. Command: split -l 300 large_file. TXT new_file_prefix Mode 2: Specify the size of the split file split -b 10m server.log waynelog

### #19, enter the date of a certain year, judge this day is the day of the year?

Use the Python standard library datetime

import datetime def dayofyear(): Year = input(" please enter the year: ") month = input(" Please enter the month: ") day = input(" Please enter the day: ") ") date1 = datetime.date(year=int(year), month=int(month), day=int(day)) date2 = datetime.date(year=int(year), day= month (day)) day=1) return (date1-date2+1).daysCopy the code

20. What are os.path and sys.path respectively?

Os. path is used to operate system path files.

Sys. path is an operation on the Python interpreter’s system environment parameters (dynamically changing the Python interpreter’s search path).

21. Common methods for OS modules in Python?

Os.remove () Deletes the file

Os.rename () renames a file

Os.walk () generates all the files in the directory tree

Os.chdir () changes the directory

Os. mkdir/makedirs Creates a directory/multi-level directory

Os. rmdir/removedirs Deletes a directory or multiple directories

Os.listdir () lists the files in the specified directory

Os.getcwd () gets the current working directory

Os.chmod () changes directory permissions

Os.path.basename () Removes the directory path and returns the file name

Os.path.dirname () Deletes the file name and returns the directory path

Os.path.join () groups the separated parts into a single pathname

Os.path.split () returns the (dirname(),basename()) tuple

Os.path.splitext () returns the (filename,extension) tuple

Os.path. getatime ctime mtime returns the last accessed, created, and modified time, respectively

Os.path.getsize () returns the file size

Os.path.exists () Indicates whether the OS exists

Os.path.isabs () Specifies whether the path is an absolute path

Os.path.isdir () Is a directory

Os.path.isfile () Is a file

What’s the difference between a dictionary and JSON?

A dictionary is a data structure. Json is a representation of data. As long as the key value of the dictionary can be hash, the key value of JSON must be a string.

Also, I packaged it as a PDF for easy reading.

The 200 best Interview Questions in Python

23. What are mutable and immutable types?

Immutable refers to whether the value in memory can be changed. Immutable refers to the value in the memory block in which the object is located. There are values, strings and tuples. Mutable types can be changed, such as lists and dictionaries.

24. Is the data stored in the dictionary sorted?

The stored data is not automatically sorted. You can use the sort function to sort the dictionary.

25. The format and application scenarios of lambda expressions?

Lambda functions are functions that can take any number of arguments (including optional arguments) and return a single expression value.

Syntax: lambda [arg1 [,arg2,…..argn]]:expression

def calc(x,y):
    return x*y
Copy the code

The above general function is rewritten as an anonymous function:

lambda x,y:x*y
Copy the code

application

(1) Lambda functions are lightweight and read-to-use, suitable for simple functions that are only used in one place.

(2) Anonymous functions, generally used for filter, Map and other functional programming services

(3) as a callback function, passed to some applications, such as message processing.

26, How to understand the \ character in Python strings?

1. Escape characters

2, the path name used to connect to the path name

3, write too long code manual soft line wrapping

27. What are the common Python standard libraries?

OS operating system, Time Time, Random random, Pymysql connecting to the database, Threading, Multiprocessing, queue

Third-party libraries: Django, flask, requests, virtualenv, Selenium, scrapy, xadmin, celery, Re, Hashlib, MD5

Common scientific libraries: Numpy, Pandas, and Matplotlib

How do I manage memory in Python?

Memory management in Python is managed by the Python private heap space. All Python objects and data structures are in the private heap. Programmers do not have access to this private heap. The Python interpreter takes care of this.

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 that reclaims all unused memory and makes it available for heap space.

29, Introduce the function and usage of except?

Except: Catches all exceptions

Except :< exception name >: Catches the specified exception

Except :< exception name 1, exception name 2>: catch exception 1 or exception 2

Except :< exception name >,< data >: catch the specified exception and its attached data

Except :< exception name 1, exception name 2>:< data >: catch exception name 1 or exception name 2, and additional data

Is the code in finally executed after return in except? How to throw a defined exception?

The code in finally continues to be processed; Use the raise method to throw a defined exception.

What is the difference between “read”, “readline” and “readlines”?

Read: Reads the entire file.

Readline: Reads the next line, using the generator method.

Readlines: Reads the entire file into an iterator for us to traverse.

What’s the difference between range and xrange?

The difference is that the result of range is a list, while the result of xrange is a generator. The former is a memory space to hold the list, and the latter is a memory space to use as we loop around, so when the list is long, Xrange is better than range for performance.

33. Describe your understanding of the input() function.

In Python3, input() gets user input, and whatever the user enters, it gets a string.

Python2 has raw_input() and input(). The raw_input() function is the same as the input() function in Python3. The input() function is the same as the input() function.

34. What happens when you try to modify immutable data in code? What exception is thrown?

The code does not work properly and raises TypeError.

35, what low-level Python method does print call?

By default, the print method calls the sys.stdout.write method, which prints the string to the console.

Also, I packaged it as a PDF for easy reading.

The 200 best Interview Questions in Python

36. Common methods of Python’s SYS module

Sys. argv takes a List of command line arguments, the first element being the path of the program itself

Sys.modules.keys () returns a list of all imported modules

Sys. exc_info() Obtain the exception class that is currently being processed,exc_type, exc_value, and exc_traceback

Sys. exit(n) Exits the program. Normally, exit(0)  sys. hexVersion Obtains the Python interpreter version value in hexadecimal format, for example, 0x020403F0

Version Obtains the version information about the Python interpreter

Sys. maxint Maximum Int value

Sys. maxUnicode Maximum Unicode value

Sys. modules Returns the module fields imported by the system. Key is the module name and value is the module

Sys. path returns the search path for the module, initialized with the value of the PYTHONPATH environment variable

Sys. platform Returns the name of the operating system platform

Sys. stdout Standard output

Sys. stdin Standard input

Sys. Stderr error output

Sys.exc_clear () clears current or recent error messages from the current thread

Sys. exec_prefix Returns the installation location of the platform-independent Python file

Byteorder Is an indicator of the native byte rule. The value for the big-endian platform is ‘big’ and the value for the little-endian platform is ‘little’ sys.copyright Keeps track of python copyright stuff

Sys. api_version SPECIFIES the C API version of the interpreter

The sys.version_info tuple provides an easier way to make your program do what the Python version requires

37. What is unittest?

In Python, unittest is a unit testing framework in Python. It has features that support shared builds, automated testing, pausing code during testing, iterating different tests into groups, and more.

38. What are modules and packages?

In Python, a module is a way of building a program. Each Python code file is a module and can refer to other modules, such as objects and properties.

A folder containing a lot of Python code is a package. A package can contain modules and subfolders.

39. What is a greedy match for re?

>>>re.search('ab*c', 'abcaxc')
<_sre.SRE_Match object; span=(0, 3), match='abc'>

>>>re.search('ab\D+c', 'abcaxc')
<_sre.SRE_Match object; span=(0, 6), match='abcaxc'>
Copy the code

Greedy match: Regular expressions tend to match the maximum length, which is called greedy match.

Non – greedy matching: it is good to match the result, less matching characters.

Which kinds of commonly used string formatting?

% Format string operator

print 'hello %s and %s' % ('df', 'another df')
Copy the code

Dictionary format of a string

print 'hello %(first)s and %(second)s' % {'first': 'df', 'second': 'another df'}
Copy the code

String Formatting (format)

(1) Use positional parameters

Positional parameters are not ordered and can be {}. The parameter index starts from 0. In format, enter the parameter value corresponding to {}.

>>> msg = "my name is {}, and age is {}"
>>> msg.format("hqs",22)
'my name is hqs, and age is 22'
Copy the code

(2) Use keyword parameters

To match the keyword parameter values, use a dictionary as the keyword parameter value and add ** before the dictionary

>>> hash = {'name':'john' , 'age': 23}
>>> msg = 'my name is {name}, and age is {age}'
>>> msg.format(**hash)
'my name is john,and age is 23'
Copy the code

(3) Fill and format

:[Fill character][Alignment <^>][Width]

>>> '{0:*<10}'.format(10) # Left-align '10********'Copy the code

41. What are object-oriented depth-first and breadth-first?

When a subclass inherits more than one parent class, there are two methods of attribute search: depth-first and breadth-first.

When the class is a classical class, in the case of multiple inheritance, when the attribute to be searched does not exist, the depth-first method will be used.

When the class is new-style, in the case of multiple inheritance, if the attribute to be searched does not exist, the search will proceed in a breadth-first manner.

42, “a line of code to achieve XX” class topic

(1) A line of code to achieve the sum of 1-100

You can use the sum() function.

(2) A line of code to achieve numerical exchange

No questions asked. Just change.

(3) A line of code to find odd even numbers

Use list deductions.

(4) One line of code expands the list

Use a list derivation, which is a little more complicated, and pay attention to the order.

(5) One line of code scrambles the list

I’m going to use random shuffle.

(6) A line of code reversal string

Use slices.

(7) A line of code to view all files in the directory

Use OS listdir.

(8) A line of code removes Spaces between strings

Method 1 replace function.

Method 2 Join and split function.

(9) a line of code to achieve string integer list into integer list

Use list & map & lambda.

(10) One line of code removes duplicate values from the list

Use list & set.

**(11) a line of code to achieve 9 * 9 multiplication table

A slightly more complicated list derivation, just be patient, work at it bit by bit…

(12) One line of code finds the same element in both lists

Use set and &.

(13) One line of code finds the different elements in two lists

Use set and ^.

(14) One line of code merges the two dictionaries

Use the Update function.

(15) One line of code to implement the dictionary keys from smallest to largest sort

Use the sort function.

Also, I packaged it as a PDF for easy reading.

The 200 best Interview Questions in Python

If you have any questions, please feel free. I think it’s good. Please comment and like.