59 Essential Python Interview Questions and Answers

59 Essential Python Interview Questions and Answers

Source: AI Time

This article contains7920 words, and is recommended for reading in 10+ minutes.

This article organizes common Python interview questions and reference answers from theory to practice.

The interview questions are roughly divided into four categories:

  • What?

  • How?

  • Difference/Talk about advantages

  • And practical operations

What?

1. What is Python?

Python is a programming language that has objects, modules, threads, exception handling, and automatic memory management. You can include comparisons with other languages. Here are a few key points to answer this question:

  • Python is an interpreted language; Python code does not need to be compiled before running.

  • Python is a dynamically typed language, meaning you do not need to specify the type of a variable when declaring it.

  • Python is suitable for object-oriented programming because it supports defining classes through composition and inheritance.

  • In Python, functions are first-class objects.

  • Python code is written quickly, but its execution speed is generally slower than compiled languages.

  • Python is versatile and often used as a “glue language” to help other languages and components improve their performance.

  • With Python, programmers can focus on designing algorithms and data structures without dealing with low-level details.

2. What is Python introspection?

Introspection in Python is a capability that allows programs written in this object-oriented language to obtain the class type of an object at runtime. Python is an interpreted language that provides great flexibility and control for programmers.

3. What is PEP8?

PEP8 is a programming guideline that contains suggestions on how to make your code more readable.

4. What are pickling and unpickling?

The Pickle module reads any Python object, converts them into a string, and then uses the dump function to store it in a file—this process is called pickling. Conversely, the process of extracting the original Python object from the stored string file is called unpickling.

5. What is a Python decorator?

A Python decorator is a unique feature in Python that makes modifying functions easier.

6. What is a Python namespace?

In Python, all names exist within a namespace, where they are created and manipulated—this is the namespace. It is like a box where each variable name corresponds to an object. When querying a variable, the corresponding object is sought from this box.

7. What are dictionary comprehensions and list comprehensions?

They are syntactic structures that allow for easy creation of dictionaries and lists.

8. What is a lambda function?

This is an anonymous function often used in code that consists of a single expression.

9. What are *args and **kwargs?

If we are unsure how many arguments to pass to a function, or if we want to pass arguments as lists or tuples, we use *args; if we do not know how many keyword arguments to pass, or want to pass dictionary values as keyword arguments, we use **kwargs.

10. What is the Pass statement?

The Pass statement is a placeholder in Python that is not executed. It is often used in complex statements where a part needs to be temporarily left blank.

11. What is unittest?

In Python, unittest is a unit testing framework that supports shared setups, automated testing, pausing code during tests, and grouping different tests into iterations, among other features.

12. What is a constructor?

A constructor is a mechanism for implementing iterators; its functionality relies on the yield expression and otherwise behaves like a regular function.

13. What is a docstring?

In Python, a docstring is a string that serves to document functions, modules, and classes.

14. What is a negative index?

In Python, sequence indices can be both positive and negative. For positive indices, 0 is the first index in the sequence, while 1 is the second. For negative indices, (-1) is the last index and (-2) is the second to last index.

15. What are modules and packages?

In Python, a module is a way to build programs. Each Python code file is a module and can reference other modules, such as objects and attributes.

A folder containing many Python code files is a package. A package can contain modules and subfolders.

16. What is garbage collection?

In Python, to address memory leak issues, object reference counting is used, and automatic garbage collection is implemented based on reference counting.

17. What is CSRF?

CSRF is an attack that forges client requests; CSRF stands for Cross-Site Request Forgery, which literally means forging requests across sites.

How?

1. How to make your program more readable?

By appropriately adding non-leading spaces, appropriate line breaks, and consistent naming.

2. How is Python interpreted?

Python is an interpreted language; its source code can be run directly. The Python interpreter converts the source code into intermediate language, which is then translated into machine code for execution.

3. How to copy an object in Python?

To copy an object in Python, you can usually use copy.copy() or copy.deepcopy(). However, not all objects can be copied.

4. How to delete a file in Python?

Use the function os.remove(“file”)

5. How to convert a number to a string?

You can use the built-in function str() to convert a number to a string. If you want octal or hexadecimal numbers, you can use oct() or hex().

6. How does Python manage memory?

Python’s memory management is handled by a private heap space. All Python objects and data structures reside in this private heap. Programmers do not have access to this heap; only the interpreter can operate on it. Memory allocation for Python’s heap space is managed by Python’s memory management module, which provides some methods for programmers to access it. Python has a built-in garbage collection system that recycles and frees unused memory so that it can be used by other programs.

7. How to convert between tuple and list?

  • To convert a tuple to a list, initialize the list class with the tuple as a parameter, which will return a list type.

  • To convert a list to a tuple, initialize the tuple class with the list as a parameter, which will return a tuple type.

8. How to generate random numbers in Python?

The module used to generate random numbers in Python is random, and it needs to be imported first. Here are some examples:

  • random.random(): generates a random float between 0 and 1

  • random.uniform(a, b): generates a float between [a, b]

  • random.randint(a, b): generates an integer between [a, b]

  • random.randrange(a, b, step): randomly selects a number from the specified set [a, b) with a step size

  • random.choice(sequence): randomly selects an element from a specific sequence, which can be a string, list, tuple, etc.

9. How to set a global variable inside a function?

To assign a value to a global variable within a function, you must use the global statement. The expression global VarName tells Python that VarName is a global variable, so Python will not look for this variable in the local namespace.

10. How to implement the Singleton pattern in Python? How to implement other 23 design patterns?

The Singleton pattern can be implemented in four main ways: __new__, shared attributes, decorators, and imports.

Other 23 design patterns can be roughly divided into creational, structural, and behavioral patterns.

  • Creational patterns provide methods for instantiation, offering suitable object creation methods for appropriate situations.

  • Structural patterns are usually used to manage relationships between entities, allowing these entities to work together more effectively.

  • Behavioral patterns facilitate communication between different entities, providing easier and more flexible communication methods.

Implementation of each pattern can be coded according to its characteristics (due to space limitations, no examples are provided here).

11. How to determine if a singly linked list has a cycle?

First, traverse the linked list to check for the same address to determine if there is a cycle. If the program enters an infinite loop, a space is needed to store the pointer; while traversing the new pointer, compare it to the stored old pointer. If there is a match, the linked list has a cycle; otherwise, store the new pointer and continue reading until encountering NULL, indicating that the linked list has no cycle.

12. How to traverse an internally unknown folder?

Common methods include os.path.walk(), os.walk(), and listdir.

13. How to partition and shard a MySQL database?

Sharding can be done in three ways: MySQL clustering, custom rules, and merge storage engines.

Partitioning can be categorized into four types:

  • RANGE partitioning: based on the column values belonging to a given continuous range, distributing multiple rows to partitions.

  • LIST partitioning: similar to RANGE partitioning, but based on matching a discrete value in a set of values.

  • HASH partitioning: based on the return value of a user-defined expression, calculated using the column values to be inserted into the table. This function can contain any valid expression in MySQL that produces a non-negative integer value.

  • KEY partitioning: similar to HASH partitioning, but only supports calculating one or more columns, and the MySQL server provides its own hash function. Must have one or more columns containing integer values.

14. How to optimize query commands?

  • Avoid full table scans as much as possible; consider creating indexes on columns involved in where and order by.

  • Avoid null checks on fields in where clauses, avoid using != or <> operators, avoid using or to connect conditions, or using parameters, expressions, or functions on fields in where clauses, as this can lead to index scans.

  • Do not perform functions, arithmetic operations, or other expressions on the left side of the “=” in the where clause, or the system may not use the index correctly.

  • When using indexed fields as conditions, if the index is a composite index, the first field in that index must be used as a condition to ensure the system uses that index; otherwise, the index will not be used.

  • Consider using exists instead of in in many cases.

  • Use numeric fields as much as possible.

  • Use varchar/nvarchar instead of char/nchar whenever possible.

  • Never use select * from t; use a specific list of fields instead of “*” and avoid returning unused fields.

  • Use table variables instead of temporary tables whenever possible.

  • Avoid frequently creating and deleting temporary tables to reduce consumption of system table resources.

  • Avoid using cursors as much as possible, as they are less efficient.

  • At the beginning of all stored procedures and triggers, set SET NOCOUNT ON, and at the end set SET NOCOUNT OFF.

  • Avoid large transaction operations to improve system concurrency.

  • Avoid returning large amounts of data to the client; if the data volume is too large, consider whether the demand is reasonable.

15. How to understand open source?

Open source means open source code. It originated in the software industry and represents not only the openness of software source code but also implies freedom, sharing, and full utilization of resources. Open source is a spirit, a culture, and has become a trend in the development of the software industry today.

16. How to understand the MVC/MTV framework?

MVC divides web applications into three layers: Model (M), Controller (C), and View (V), which are connected in a plug-in, loosely coupled manner. The MTV model is essentially the same as MVC, also aimed at maintaining loose coupling between components, but with slight differences in definitions.

17. How does a deadlock occur in MSSQL?

The following are the four necessary conditions for a deadlock to occur:

  • Mutual exclusion condition: refers to a process exclusively using the resources allocated to it, meaning that during a period, a resource can only be occupied by one process. If other processes request the resource, they must wait until the resource is released by the occupying process.

  • Request and hold condition: refers to a process holding at least one resource but requesting new resources that are occupied by other processes. At this point, the requesting process is blocked but continues to hold on to the resources it has obtained.

  • No preemption condition: refers to resources obtained by a process that cannot be preempted until they are fully used, and can only be released by the process itself.

  • Circular wait condition: when a deadlock occurs, there must be a circular chain of processes and resources, meaning that a process in the set {P0, P1, P2, …, Pn} is waiting for a resource occupied by P1; P1 is waiting for a resource occupied by P2, and so on, until Pn is waiting for a resource occupied by P0.

18. How does SQL injection occur, and how to prevent it?

During the development process, neglecting to follow standards when writing SQL statements and filtering special characters can lead clients to submit SQL statements through global variables POST and GET that execute normally, resulting in SQL injection. Here are prevention methods:

  • Filter out some common database operation keywords or use system functions for filtering.

  • In the PHP configuration file, set Register_globals=off; to turn it off.

  • When writing SQL statements, avoid omitting single quotes and double quotes as much as possible.

  • Enhance database naming techniques; for important fields, use names that are not easily guessed based on the program’s characteristics.

  • Encapsulate commonly used methods to avoid exposing SQL statements directly.

  • Enable PHP safe mode: Safe_mode=on;

  • Open magic_quotes_gpc to prevent SQL injection.

  • Control error messages: turn off error prompts and write error messages to the system log.

  • Use mysqli or PDO prepared statements.

19. How to prevent XSS?

XSS vulnerabilities are difficult to detect, but to ensure web security, efforts must be made to avoid them:

For reflected and stored XSS, both the server and frontend need to prevent it by parsing and escaping user input data. For frontend development, it is important to use escape and validate data URI content using regular expressions to prohibit user input of non-display information.

For DOM XSS, since the cause of XSS is user input, special attention must be paid to user input sources in the frontend, and any operations that may cause XSS need to be string-escaped.

20. How to generate a shared secret key? How to prevent man-in-the-middle attacks?

Key generation is completed using global configuration commands: For non-exportable keys, use ; for exportable keys, use . Labels are optional; if no label is specified, the key name will be hostname.domain-name.

To prevent man-in-the-middle attacks, the following measures can be taken:

  • Strengthen network infrastructure control through dynamic ARP detection, DHCP Snooping, etc.

  • Use transport encryption.

  • Utilize CASBs (Cloud Access Security Brokers).

  • Create RASP (Runtime Application Self-Protection).

  • Block self-signed certificates.

  • Enforce SSL pinning.

  • Install DAM (Database Activity Monitoring).

21. How to manage different versions of code?

By conducting version management. You can provide examples of how to use Git (or other tools) for tracking.

Difference

1. What is the difference between arrays and tuples?

Arrays are called lists in Python. Lists are mutable, while tuples are immutable. If a tuple contains only one element, a comma must be added after the element. The querying methods for tuples and lists are the same. Tuples are read-only and cannot be modified; if data in a program is not allowed to be modified, tuples can be used.

2. What is the difference between __new__ and __init__?

  • __init__ is called after an instance object is created to set some initial values for the object’s attributes.

  • __new__ is called before the instance is created; its task is to create the instance and return it, making it a static method.

In other words, __new__ is called before __init__, and the return value of __new__ (the instance) is passed as the first argument to the __init__ method, which then sets some parameters for this instance.

3. What is the difference between single underscore and double underscore in Python?

  • A member variable starting with a “single underscore” is called a protected variable, meaning that only the class object and subclass objects can access these variables;

  • A member variable starting with a “double underscore” is private, meaning that only the class object can access it, and even subclass objects cannot access this data.

4. What is the difference between shallow copy and deep copy?

In Python, object assignment is actually a reference to the object. A shallow copy does not copy sub-objects, so changes to the original data will affect the sub-objects, while a deep copy includes copies of the sub-objects, so changes to the original object will not affect any elements in the deep copy.

5. What is the difference between using a decorator for a singleton and using other methods?

The import method alters the class itself, while the new method merely shares attributes among all instance objects, creating a new object each time. This is considered a pseudo-singleton, while the shared attribute method instantiates multiple identical attributes. Thus, the decorator method is the most practical.

6. What is the difference between multiprocessing and multithreading?

  • In short, a program has at least one process, and a process has at least one thread.

  • The granularity of thread division is smaller than that of processes, resulting in higher concurrency for multithreaded programs.

  • Additionally, processes have independent memory units during execution, while multiple threads share memory, greatly improving program execution efficiency.

  • Threads have distinct entry points, sequential execution sequences, and exits for program execution. However, threads cannot execute independently and must rely on the application to provide multiple threads for execution control.

  • Logically, the significance of multithreading is that there are multiple executing parts within an application that can run simultaneously. However, the operating system does not treat multiple threads as independent applications for scheduling and resource allocation. This is a key distinction between processes and threads.

7. What is the difference between select and epoll?

Select requires polling all fd sets continuously until the device is ready, which may involve multiple sleep and wake cycles. Epoll also requires calling epoll_wait to continuously poll the ready list, which may involve multiple sleep and wake cycles, but it wakes up the process sleeping in epoll_wait when the device is ready, placing the ready fd into the ready list. While both require sleep and switching, select must traverse the entire fd set when “awake,” whereas epoll only needs to check if the ready list is empty, saving a significant amount of CPU time.

Every call to select requires copying the fd set from user mode to kernel mode and hanging the current process in the device wait queue, while epoll only requires one copy and hangs the current process in the wait queue once (at the start of epoll_wait). This also saves considerable overhead.

8. What is the difference between TCP and UDP? What is the difference between edge-triggered and level-triggered?

Basic differences:

  • Connection-based vs. connectionless

  • TCP requires more system resources, while UDP requires less;

  • UDP has a simpler program structure

  • Stream mode (TCP) vs. datagram mode (UDP);

  • TCP guarantees data integrity, while UDP may lose packets

  • TCP guarantees data order, while UDP does not

Programming differences:

  • Different parameters for socket()

  • UDP Server does not need to call listen and accept

  • UDP sends and receives data using sendto/recvfrom functions

  • TCP: address information is determined during connect/accept

  • UDP: address information must be specified every time in sendto/recvfrom functions

  • UDP: shutdown function is ineffective

9. What is the difference between GET and POST in HTTP connections?

GET requests append data to the URL, separated by a ?, with multiple parameters connected by &. The URL encoding format uses ASCII encoding instead of Unicode, meaning all non-ASCII characters must be encoded before transmission.

POST requests place data in the body of the HTTP request packet. The above item=bandsaw is the actual transmitted data.

Thus, data from GET requests is exposed in the address bar, while POST requests are not.

10. What is the difference between varchar and char?

char has a fixed length, meaning it will always occupy a fixed length regardless of the data stored. In contrast, varchar has a variable length but adds 1 character to the total length for storage purposes. Therefore, char is faster than varchar in processing speed, but consumes more storage space. For small storage needs with speed requirements, char can be used; otherwise, varchar is recommended.

11. What is the difference between BTree index and hash index?

Due to its special structure, hash index has very high retrieval efficiency, allowing for direct access without the multiple IO accesses required by B-Tree index, which needs to traverse from the root node to branch nodes before accessing page nodes. Therefore, hash index’s query efficiency is significantly higher than that of B-Tree index. However, it also has several obvious drawbacks:

  • Hash index can only satisfy “=”, “IN”, and “<=>” queries, and cannot be used for range queries.

  • Hash index cannot be used to avoid data sorting operations.

  • Hash index cannot utilize partial index key queries.

  • Hash index cannot avoid table scans at any time.

  • Hash index may not perform better than B-Tree index when encountering a large number of equal hash values.

12. What is the difference between primary key and unique?

  • A domain/group acting as a Primary Key cannot be null, while a Unique Key can.

  • There can only be one Primary Key in a table, while multiple Unique Keys can exist simultaneously.

  • Logically, Primary Key is generally used in logical design as a record identifier, which is its original intent, while Unique Key is intended solely to ensure the uniqueness of the domain/group.

13. What is the difference between ECB and CBC modes?

  • ECB: a basic encryption method where ciphertext is divided into blocks of equal length (with padding for insufficient lengths) and then encrypted and outputted individually to form ciphertext.

  • CBC: a cyclic mode where the previous ciphertext block is XORed with the current plaintext block before encryption, enhancing the difficulty of cracking. The encryption results of ECB and CBC differ; they use different modes, and CBC includes an initialization vector during the first ciphertext block operation.

14. What is the difference between symmetric and asymmetric encryption?

Symmetric encryption requires using the same key for both encryption and decryption. Due to its speed, symmetric encryption is typically used when the sender needs to encrypt a large amount of data. Therefore, symmetric encryption is also referred to as key encryption.

Asymmetric encryption algorithms require two keys: a public key and a private key. The public key and private key form a pair; if data is encrypted with the public key, only the corresponding private key can decrypt it; if data is encrypted with the private key, only the corresponding public key can decrypt it.

15. What is the difference between xrange and range?

range([start,] stop[, step]) generates a sequence based on the range specified by start and stop and the step set by step. xrange works the same way as range, but it generates not a list object but a generator. When generating large numerical sequences, using xrange is much more efficient than range because it does not allocate a large memory space at once. range directly generates a list object, while xrange does not; it returns one value each time it is called.

16. What is the difference between os and sys modules?

The former provides a convenient way to use operating system functions, while the latter provides access to variables used or maintained by the interpreter and functions for interacting with the interpreter.

17. What is the difference between NoSQL and relational databases?

  • SQL data exists in tables with specific structures, while NoSQL is more flexible and scalable, with storage formats that can be JSON documents, hash tables, or others.

  • In SQL, data must be added only after defining the table and field structure, such as defining primary keys, indexes, triggers, stored procedures, etc. Table structures can be updated after being defined, but significant structural changes can become complex. In NoSQL, data can be added anywhere at any time without needing to define tables first.

  • In SQL, to add external associated data, the normalized approach is to add a foreign key to the original table, linking to external data tables. In NoSQL, in addition to this normalized external data table approach, we can also use non-normalized methods to include external data directly in the original dataset to improve query efficiency. However, this has apparent drawbacks, as updating auditor data will become more complicated.

  • In SQL, JOIN table linking allows data from multiple relational data tables to be queried with a simple query statement. NoSQL has not yet provided a similar JOIN query method for querying data from multiple datasets, so most NoSQL databases use non-normalized data storage methods.

  • In SQL, already used external data cannot be deleted, while NoSQL does not have such a strong coupling concept and allows any data to be deleted at any time.

  • In SQL, if multiple tables need to be updated in the same batch, if one table update fails, other tables cannot be successfully updated. This scenario can be controlled using transactions, which can be committed after all commands are completed. In NoSQL, there is no concept of transactions; each dataset operation is atomic.

  • Under the premise of the same level of system design, NoSQL is theoretically superior to SQL in performance because it eliminates the overhead of JOIN queries.

Practice

This type of practical operation question is quite diverse, with the following categories being more common:

1. Fill in missing code

For example:

59 Essential Python Interview Questions and Answers

def print_directory_contents(sPath):
    import os
    for sChild in os.listdir(sPath):
        sChildPath = os.path.join(sPath,sChild)
        if os.path.isdir(sChildPath):
            print_directory_contents(sChildPath)
        else:
            print(sChildPath)

2. What is the output of the following code? Please explain.

For example:

59 Essential Python Interview Questions and Answers

list1 = [10, 'a']
list2 = [123]
list3 = [10, 'a']

The new default list is created only once when the function is defined. When extendList is called without specifying a specific parameter list, the values of this list will be used subsequently. This is because expressions with default parameters are computed when the function is defined, not when it is called.

3. Can the following code run? Please explain?

For example:

59 Essential Python Interview Questions and Answers

It can run. When the key is missing, the DefaultDict class will automatically instantiate the series when the dictionary instance is executed.

4. Sort the functions by execution efficiency and prove your answer is correct.

For example:

59 Essential Python Interview Questions and Answers

Sort by execution efficiency from high to low: f2, f1, and f3. To prove this answer is correct, you should know how to analyze the performance of your code. Python has a great profiling package that can meet this need.

59 Essential Python Interview Questions and Answers

……

This is the compilation of common Python interview questions and reference answers, provided for all Python programmers. I hope it helps a bit. If you have questions about any of the issues, please leave a message. I wish every Python programmer can get their ideal offer soon!

59 Essential Python Interview Questions and Answers

59 Essential Python Interview Questions and Answers

Leave a Comment