Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the interview questions for Python?

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

Today, the editor will share with you the relevant knowledge points of Python's interview questions, which are detailed in content and clear in logic. I believe most people still know too much about this, so share this article for your reference. I hope you can get something after reading this article. Let's take a look at it.

First, 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 # numerical type

Bool # Boolean type

Str # string

List # list

Tuple # tuple

Dict # Dictionary

3. Briefly describe the with method to open the processing file to help us do what?

The with statement is suitable for accessing resources to ensure that necessary cleanup operations are performed and resources are released regardless of whether an exception occurs during use, such as automatic closing of files after use, automatic acquisition and release of locks in threads, etc.

The with statement, the context manager, is used in a program to represent the environment before and after code execution. Context manager: an object that contains _ _ enter__ and _ _ exit__ methods is the context manager.

Enter (): this method is executed before the with statement is executed, usually returning an instance object, and if the with statement has an as target, the object is assigned to the as target.

Exit (): after the execution of the with statement, the _ _ exit__ () method is called automatically, and the user releases resources. If this method returns a Boolean value of True, the program ignores the exception.

Use environment: file reading and writing, automatic release of thread locks, etc.

With context_expression [as target (s)]:

With-body

Here context_expression returns a context manager object that does not assign a value to target (s) in the as clause, but rather assigns the return value of the context manager's _ _ enter__ () method to target (s).

4. What are the variable and immutable data types of Python?

Immutable data types: that is, after the data is created, the value of the data will no longer change, and there are numeric values, characters and meta-ancestor types.

Variable data types: after the data is created, the values of the data can be changed, including lists, dictionaries, and collection types.

5. Python gets the current date?

Import datetime

Import time

Print (time.time ()) # timestamp

Print (time.strftime ("% Y-%m-%d% H:%M:%S% w", time.localtime () month, day, minute and second

Print (datetime.datetime.now ()), month, day, hour and 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)

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 linux command.

Import os

Os.remove ("demo.txt")

Rm 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. An example is given to illustrate the significance of try except else finally in the exception module.

Def read_filedata (file_name):

File_obj = ""

Try:

# exception code snippets to be detected

File_obj = open (file_name, "r")

Result_data = file_obj.read ()

Except IOError, e:

# Code snippet for handling when a "IOError" exception occurs

File_obj = "File does not exist:" + str (e)

Else:

# No code snippet executed with "IOError" exception is thrown, and the read data is returned

Return result_data

Finally:

# A code snippet that executes 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)

10. What should I do if I encounter bug?

First of all, check the error information, according to the error information to find the corresponding code, usually the general data structure or algorithm error as long as you find the error code can be solved smoothly

If you encounter an error that cannot be solved temporarily, don't panic. We can use the compiler's Debug mode or add a breakpoint in the code to troubleshoot the code.

If we still can't solve the bug, we can copy the error message and search in the search engine. No one can write code without bug. If you spend more than half an hour on a bug, you can discuss it with other colleagues. (pay attention to moderation, it may cost colleagues)

Find another way: the method is always more difficult, in the rapid development, we should give priority to the implementation of the function rather than rigidly adhere to the operational efficiency, so when we encounter some BUG that can not be solved temporarily, we can consider other implementation methods.

II. Language characteristics

1. What is the difference between Python and other languages?

Python is an interpretive programming language with concise and beautiful syntax, powerful functions, a wide range of applications, and a strong type of dynamic, portable, extensible and embedded third-party library.

The difference between strongly typed and weakly typed languages:

If a language often implicitly converts the types of variables, then the language is weakly typed, and if it rarely does so, it is strongly typed. Python rarely implicitly converts the types of variables, so Python is a strongly typed language.

The fundamental judgment of strongly typed language and weakly typed language is whether the language type conversion will be implicitly carried out. The speed of strongly typed reasons may be slightly lower than that of weakly typed languages, but the rigor of strongly typed definitions avoids unnecessary errors.

Strongly typed languages include: Java,. Net, Python, C++ and other languages. Python is a dynamic language, a strongly typed language, 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. VBScript is a dynamic language, which is a reason for type unsafety.

The difference between dynamic language and static language:

Dynamically typed language: a dynamically typed language is a language that does data type checking only at run time, that is, when a dynamically typed language is programmed, it never has to assign a data type to any variable, and the language will record the data type internally when it is assigned to a variable for the first time. Python and Ruby are typical dynamically typed languages, while other scripting languages such as VBScript are more or less dynamically typed.

Statically typed languages: statically typed languages are just the opposite of dynamically typed classes, whose data types are checked during compilation, that is to say, you have to declare the data types of all variables when you write the program. Cmax Cure + is a typical representative of statically typed languages, and other statically typed languages include C #, Java, and so on.

The fundamental distinction between dynamic and static languages lies in whether the data type is checked at run time or at compile time.

The difference between compiled language and interpreted language:

Compiled language: it is necessary to translate a program directly into machine code (for a non-cross-platform language such as Cpicket +) or intermediate code (a cross-platform language like Java, which requires a virtual machine to print the intermediate code into machine code). Generally need to go through the compilation (compile), link (linker) these two steps. Compilation is to compile the source code into machine code, and linking is to concatenate the machine code of each module with the dependent library to generate an executable file.

Interpretive language: use the interpreter to interpret the source code line by line into machine code and execute it immediately, without overall compilation and linking processing, which saves a lot of work compared to the compiled language.

One is like eating and other dishes are all served before starting, the other is like eating hot pot, rinsing while eating, the time is different.

The advantages of interpretive language: cross-platform is easy, only need to provide a platform-specific interpreter; disadvantages: it has to be explained every time it is run, and its performance is inferior to that of compiled language.

two。 A brief description of interpretive and compiled programming languages?

You can refer to the explanation of the previous article.

3. What are the interpreter types and related features of Python?

CPython: official version of the interpreter. This interpreter is developed in C language, so it is called CPython. Running python from the command line starts the CPython interpreter. CPython is the most widely used Python interpreter.

IPython:IPython is an interactive interpreter based on CPython, that is, IPython is only enhanced in the way it interacts, but the function of executing Python code is exactly the same as CPython. CPython uses > > as the prompt, while IPython uses I n [serial number]: as the prompt.

PyPy: its goal is execution speed. PyPy uses J IT technology to dynamically compile Python code (note that it is not interpreted), so it can significantly improve the execution speed of Python code. Most Python code can be run under PyPy, but there are some differences between PyPy and CPython, which results in different results for the same Python code 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.

IronPython:IronPython is similar to Jython, except that IronPython is a Python interpreter running on Microsoft's .net platform that compiles Python code directly into .net bytecode.

4. Tell me what you know about the difference between Python3 and Python2?

Coding: the default encoding of Python2 is asscii, which is one of the reasons why coding problems are often encountered in Python2. As for why asscii is used as the default encoding, the reason is that Unicode did not appear when the language Python was born. Python3 defaults to UTF-8 as the default encoding, so you no longer need to write # coding=utf-8 at the top of the file.

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

You can think of a string as having two states, the text state and the byte (binary) state. The two character types in Python2 and Python3 correspond to these two states respectively, and then encode and decode each other. Encoding is to convert a string into bytecode, which involves the internal representation of the string; decoding is to convert the bytecode into a string and display bits into characters.

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

Print in print:Python2 is a statement; print in Python3 is a function. For example:

> print ("hello", "world")

('hello',' world')

# py3

> print ("hello", "world")

Hello world

This example is obvious. In py2, the print statement is followed by a tuple object, while in py3, the print function can accept 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 defaults to importing modules and packages according to relative paths, while python3 defaults to importing modules and packages in absolute paths.

Input:Python3:input parsing input is str character type; Python2:input parsing input is int input, and raw_input parsing input is str type.

Operator: in Python2, / performs traditional division, performs truncated division on integers, and floating-point division (leaving decimal parts, even if divisible) for floating-point numbers; / / performs Floor division, truncates the remainder and returns an integer for integer operands, or returns a floating-point number if any Operand is a floating-point number. In Python3, / always performs true division and returns a floating-point result containing any remainder, regardless of the type of Operand; / / performs Floor division, truncates the remainder and returns an integer for integer operands, or a floating-point number if any Operand is floating-point.

In int/long:Python3, there is only one integer type, int, which in most cases is very similar to the long integer 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) that correspond to 1 and 0 respectively. Since they are variables, they can point to other objects. Python3 fixed this flaw by changing True and False to two keywords that always point to two fixed objects and are not allowed to be re-assigned.

Iterators: many built-in functions and methods that return list objects in Python2 are changed to return iterator-like objects in Python3, because the lazy loading nature of iterators makes it more efficient to manipulate big data.

For example: xrange () is used in Python2 to create an iterator object, and range () is used to create an list array (xrange is much better than range when generating a large sequence of numbers, because there is no need to open up a large piece of memory space in the first place); and range () is used in Python3 to create an iterator object, removing the xrange () method.

In addition, the dictionary object's dict.keys () and dict.values () methods no longer return a list, but as an iterator-like view object. Higher-order functions map, filter, and zip no longer return list objects. Python2's iterator must implement the next method, while Python3 has been changed to _ _ iter__ (), next.

Nonlocal: in Python2, you can declare a variable as a global variable with the keyword global in the function, but it is impossible to declare a variable as a non-local variable in a nested function. In Pyhon3, the keyword nonlcoal is added, which is generally used in closures to make the variable use the outer variable of the same name.

Understanding of LEGB scope: a brief Analysis of python3's local, global and nonlocal

These are all the contents of the article "what are the interview questions for Python?" Thank you for your reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report