[Hematemesis compilation] 50 Python interview questions and answers (collection)

青灯夜游
Release: 2022-09-19 20:14:29
forward
4656 people have browsed it

This article summarizes 50 Python interview questions and answers for you. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

[Hematemesis compilation] 50 Python interview questions and answers (collection)

Python is currently the most popular language in the field of programming. In this article, I will summarize the 50 most common Python interview questions. Reference answers are provided for each question, hoping to help you stand out in the job interview in 2019 and find a high-paying job. These interview questions cover many aspects such as Python basics, Python programming, data analysis, and Python function libraries.

Q1. What is the difference between lists and tuples in Python?

Q2. What are the main functions of Python?

Python is an interpreted language. Unlike languages ​​like C, Python does not require compilation before running.

Python is a dynamic language, when you declare a variable or similar, you do not need to declare the type of the variable.

Python is suitable for object-oriented programming because it allows the definition of classes as well as composition and inheritance. Python has no access instructions (such as C's public, private).

In Python, functions are first-class objects. They can be assigned to variables. Classes are also first-class objects

Writing Python code is fast, but running it is slower. Python allows C-based extensions such as the numpy function library.

Python can be used in many fields. Web application development, automation, mathematical modeling, big data applications and more. It is also often used as "glue" code.

Q3. Is Python a general-purpose programming language?

Python is capable of writing scripts, but in a general sense, it is considered a general-purpose programming language.

Q4. How does Python interpret language?

Python does not require interpretation of the program before running it. Therefore, Python is an interpreted language.

Q5. What is pep?

PEP stands for Python Enhancement Proposal. It is a set of rules that specify how to format Python code for maximum readability.

Q6. How to manage memory in Python?

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

Heap space allocation of Python objects is completed 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.

Q7. What is the namespace in Python?

Namespace is a naming system used to ensure that names are unique to avoid naming conflicts.

Q8. What is PYTHONPATH?

It is an environment variable used when importing modules. Whenever a module is imported, PYTHONPATH is also looked up to check whether the imported module exists in the respective directories. This is used by the interpreter to determine which modules to load.

Q9. What is a python module? What are the commonly used built-in modules in Python?

Python modules are .py files that contain Python code. This code can be a function class or a variable. Some commonly used built-in modules include: sys, math, random, data time, JSON.

Q10. What are local variables and global variables in Python?

Global variables: Variables declared outside a function or in the global space are called global variables. These variables can be accessed by any function in the program.

Local variables: Any variable declared within a function is called a local variable. This variable exists in local space, not global space.

Q11. Is python case-sensitive?

yes. Python is a case-sensitive language.

Q12. What is type conversion in Python?

Type conversion refers to converting one data type to another data type.

int() - Converts any data type to integer type

float() - Converts any data type to float type

ord() - Converts character to integer

hex() - Convert an integer to hexadecimal

oct() - Convert an integer to octal

tuple() - This function is used to convert to tuple.

set() - This function returns type after conversion to set.

list() - This function is used to convert any data type to list type.

dict() - This function is used to convert a sequential tuple (key, value) into a dictionary.

str() - Used to convert an integer to a string.

complex(real,imag) - This function converts a real number to a complex (real, image) number.

Q13. How to install Python on Windows and set path variables?

To install Python on Windows, follow these steps:

Install python from the following link: https://http://www.python.org/downloads/

After downloading, install it on your PC. Find where PYTHON is installed on your PC using the following command at the command prompt: cmd python.

Then go to Advanced System Settings and add new variable and name it PYTHON_NAME and paste the copied path.

Find the path variable, select its value and choose Edit.

If the value does not exist, add a semicolon at the end of the value and type %PYTHON_HOME%

Q14. Is indentation required in python?

Indentation is required for Python. It specifies a block of code. All code within loops, classes, functions, etc. is specified within indented blocks. This is usually done using four space characters. If your code is not indented as necessary, it will not execute accurately and will also throw an error.

Q15. What is the difference between Python arrays and lists?

Arrays and lists in Python have the same way of storing data. However, an array can contain only a single data type element, whereas a list can contain any data type element.

Q16. What are the functions in Python?

A function is a block of code that only executes when called. To define a function in Python, you need to use the def keyword.

Q17. What is __init__?

__init__ is a method or structure in Python. This method is automatically called to allocate memory when a new object/instance of the class is created. All classes have __init__ method.

Q18. What is lambda function?

The lambda function is also called an anonymous function. The function can contain any number of parameters, but can only have one statement to perform the operation.

Q19. What is self in Python?

self is an instance or object of a class. In Python, self is included in the first parameter. However, this is not the case in Java, it is optional. It helps to differentiate between methods and properties of a class that has local variables. The self variable in the init method refers to the newly created object, while in other methods it refers to the object whose method is called.

Q20. Distinguish between break, continue and pass?

Q21. What does [:: - 1} mean?

[:: - 1] is used to reverse the order of an array or sequence.

Q22. How to randomize elements in a list in Python?

You can use the shuffle function to randomize list elements. For example:

The code output is:

Q23. What is a python iterator?

Iterators are objects that can be traversed or iterated over.

Q24. How to generate random numbers in Python?

Therandom module is a standard module for generating random numbers. This method is defined as:

random.random() method returns a floating point number in the range [0,1]. This function generates random floating point numbers. The method used by the random class is the binding method of the hidden instance. You can use instances of Random to display multi-threaded programs that create different thread instances. Other random generators used there are:

randrange(a,b): It selects an integer and defines the range between [a,b]. It returns elements by randomly selecting elements from the specified range. It does not build scope objects.

uniform(a,b): It selects a floating point number defined in the range [a,b)

normalvariate(mean,sdev): It is used for normal distribution, where mean is the mean and sdev is the sigma for the standard deviation.

Use and instantiate the Random class to create an independent multiple random number generator.

Q25, what is the difference between range & xrange?

In most cases, xrange and range are functionally identical. They both provide a way to generate a list of integers, the only difference is that range returns a Python list object and xrange returns an xrange object. This means that xrange does not actually generate a static list at runtime. It creates values ​​as needed using a special technique called yielding. This technique works with an object called a generator. So if you have a very large list, consider xrange.

Q26. How to write comments in python?

Comments in Python start with the # character. Comments can also be made using doc-strings (strings enclosed in triple quotes).

Q27. What are pickling and unpickling?

The Pickle module accepts any Python object and converts it to a string representation and dumps it to a file using the dump function, a process called pickling. The process of retrieving original Python objects from stored strings is called unpickling.

Q28. What is the generator in python?

A function that returns an iterable item set is called a generator.

Q29. How do you capitalize the first letter of a string?

In Python, the capitalize() function can capitalize the first letter of a string. If the string already contains uppercase letters at the beginning, then it will return the original string.

Q30. How to convert a string to all lowercase?

To convert a string to lowercase, you can use the lower() function.

Q31. How to comment multiple lines in python?

When commenting multiple lines of code. All lines to be commented must be preceded by #. You can also use the shortcut to comment out multiple lines by holding down the Ctrl key and left-clicking and typing # once at each place you want a # character.

Q32. What are document Docstrings in Python?

Docstrings are not actually comments, they are docstrings. These docstrings are enclosed in triple quotes. They are not assigned to any variables and are therefore sometimes used in comments.

Q33. What are the functions of is, not and in in operators?

Operators are special functions that compare one or more values ​​and produce corresponding results. Where is: Returns true when the 2 operands are true (for example: "a" is 'a')

not: Returns the reciprocal of the Boolean value

in: Checks whether an element Exists in a certain sequence

Q34. What are the usages of help() and dir() functions in Python?

Both functions Help() and dir() can be accessed directly from the Python interpreter and used to view merged dumps of built-in functions.

help() function: The help() function is used to display the documentation string, and you can also view usage information related to modules, keywords, attributes, etc.

dir() function: The dir() function is used to display defined symbols.

Q35. When Python exits, why does it not clear all allocated memory?

When Python exits, especially those Python modules that have circular references to other objects or objects referenced from the global namespace are not deallocated or released.

Unable to deallocate those portions of memory reserved by the C library.

When exiting, Python will try to deallocate/destroy all other objects due to its own efficient cleanup mechanism.

Q36. What is a dictionary in Python?

The built-in data type in Python is called a dictionary. It defines a one-to-one relationship between keys and values. A dictionary contains a pair of keys and their corresponding values. Dictionaries are indexed by keys.

Q37. How to use the ternary operator in python?

The ternary operator is an operator used to display conditional statements. This contains a true or false value and for which the statement must be evaluated. Its basic syntax is:

The ternary operator is an operator used to display conditional statements. This contains a true or false value and for which the statement must be evaluated. The basic syntax is:

[on_true] if [expression] else [on_false] x, y = 25,50big = x if x

Q38. Why Using *args, **kwargs?

We use *args when we are not sure how many arguments to pass to the function, or we want to pass a stored list or tuple of arguments to the function. **Kwargs are used when we don't know how many keyword arguments to pass to a function, or it can be used to pass values ​​of a dictionary as keyword arguments. Identifiers args and kwargs are a convention, you can also use *bob and **billy.

Q39. What is the function of len() function?

The len() function can be used to determine the length of strings, lists, arrays, etc.

Q40. Split(), sub(), subn() functions in Python.

If you want to modify a string, Python's "re" module provides 3 methods. They are:

split() - "split" the given string into a list using a regular expression pattern.

sub() - Finds all substrings matching a regular expression pattern and replaces them with different strings

subn() - It is similar to sub() and also returns new string.

Q41. What is a negative index and what is its function?

Sequences in Python are indexed and consist of positive and negative numbers. Positive numbers use '0' as the first index and '1' as the second index, which the process continues to use.

Indices for negative numbers start with '-1', representing the last index in the sequence, and '-2' as the penultimate index, and the sequence advances like positive numbers.

Negative indexing is used to remove any newlines from the string and allow the string to be except for the last character given as S[:-1]. Negative indexing is also used to show that the index represents the string in the correct order.

Q42. What is a Python package?

A Python package is a namespace containing multiple modules.

Q43. How to delete files in Python?

To delete files in Python, you need to import the OS module. After that you need to use the os.remove() function.

Q44. What are python’s built-in types?

The built-in types in Python are as follows: integer, floating point, complex number, string, Boolean, etc.

Q45. What functions are there in NumPy to operate Python lists?

Python's lists are efficient general-purpose containers. They support (fairly) efficient insertion, deletion, appending, and concatenation, and Python's list comprehensions make them easy to construct and manipulate.

They have certain limitations: they do not support "vectorized" operations such as pixelated addition and multiplication, and the fact that they can contain objects of different types means that Python must store type information for each element, and must Execution type dispatch code as it operates on each element.

NumPy is not only more efficient; it is also more convenient. You get a lot of vector and matrix operations for free, which can sometimes save you from unnecessary work. They are also effectively implemented.

NumPy arrays are faster, you can use NumPy, FFT, convolution, fast search, basic statistics, linear algebra, histograms and more built-in.

Q46. How to add values ​​to a python array?

You can use the append(), extend() and insert(i,x) functions to add elements to the array.

Q47. How to delete the value of a python array?

You can use the pop() or remove() method to delete array elements. The difference between these two functions is that the former returns the deleted value while the latter does not.

Q48. Does Python have the concept of OOps?

Python is an object-oriented programming language. This means that any program can be solved in python by creating an object model. At the same time Python can be regarded as a programming language and a structural language.

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

Use a shallow copy when creating a new instance type and retain the copied values ​​in the new instance. Shallow copy is used to copy a reference pointer just like a value. These references point to the original object, and changes made in any member of the class will also affect its original copy. Shallow copies allow faster execution of programs, depending on the size of the data used.

Deep copy is used to store copied values. A deep copy does not copy the reference pointer to the object. It references an object and stores some new object that the other object points to. Changes made in the original copy do not affect any other copies that use the object. A deep copy can slow down the execution of your program because some copies are created for each object that is called.

Q50. How to implement multi-threading in Python?

Python has a multi-threading library, but the effect of using multi-threading to speed up the code is not that good.

Python has a structure called Global Interpreter Lock (GIL) . The GIL ensures that only one "thread" can execute at a time. One thread obtains the GIL to perform relevant operations, and then passes the GIL to the next thread.

Although it may appear that the program is being executed in parallel by multiple threads, they are actually just taking turns using the same CPU core.

All these GIL passes add overhead to the execution. This means that multi-threading does not make the program run faster.

【Related recommendations: Python3 video tutorial

The above is the detailed content of [Hematemesis compilation] 50 Python interview questions and answers (collection). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!