search
HomeBackend DevelopmentPython TutorialDetailed summary of python interview questions (with answers)

Detailed summary of python interview questions (with answers)

This article brings you a summary of python interview questions (with answers). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. helped.

Recommended related articles: "Summary of python interview questions in 2020 (latest)"

##1. What is the output of the following code? please explain.

def extendList(val, list=[]):
    list.append(val)
    return list
list1 = extendList(10)
list2 = extendList(123,[])
list3 = extendList('a')
print "list1 = %s" % list1
print "list2 = %s" % list2
print "list3 = %s" % list3

How to modify the definition of extendList to produce the following expected behavior?

The output result of the above code will be:

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

Many people will mistakenly think that list1=[10], list3=['a'], because they thought that every time extendList is called, the default value of the list parameter will be set to []. But the actual situation is that the new default list is only used at the moment the function is defined. Created once.

When extendList is called without specifying a specific parameter list, the values ​​of this set of list will be used subsequently. This is because expressions with default parameters are evaluated when the function is defined, not when it is called. Therefore list1 and list3 operate (calculate) on the same default list. And list2 operates (calculates) on a separate list. (By passing an own empty list as the value of the list argument).

The definition of extendList can be modified as follows.

Although, creates a new list with no specific list parameters.

The following code may produce the desired results.

def extendList(val, list=None):
  if list is None:
    list = []
  list.append(val)
  return list

With the above modification, the output result will become:

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

2. What will be the output result of the following code? please explain.

def multipliers():
  return [lambda x : i * x for i in range(4)]
print [m(2) for m in multipliers()]

How do you modify the definition of multipliers above to produce the desired results?

The result output by the above code is [6, 6, 6, 6] (not [0, 2, 4, 6] as we thought).

The above problem is caused by the delayed binding of Python closures. This means that when the inner function is called, the value of the argument is looked up within the closure. Therefore, when any function returned by multipliers() is called, the value of i will be looked up in the nearby range. At that point, regardless of whether the returned function has been called, the for loop has completed and i is assigned the final value of 3.

Therefore, the function returned each time is multiplied by the passed value 3, because the value passed in the previous code is 2, and they eventually return 6 (3*2). Coincidentally, "The Hitchhiker’s Guide to Python" also pointed out that there is also a widely misunderstood knowledge point related to lambdas functions, but it is different from this case. There is nothing special about the function created by lambda expression. It is actually the same as the function created by def.

Here are some ways to solve this problem.

One solution is to use Python generators.

def multipliers():
  for i in range(4): yield lambda x : i * x

Another solution is to create a closure and bind it immediately using the default function.

def multipliers():
  return [lambda x, i=i : i * x for i in range(4)]

An alternative is to use a partial function:

from functools import partial
from operator import mul
def multipliers():
  return [partial(mul, i) for i in range(4)]

3. What will be the output of the following code? please explain.

class Parent(object):
    x = 1
class Child1(Parent):
    pass
class Child2(Parent):
    pass
print Parent.x, Child1.x, Child2.x
Child1.x = 2
print Parent.x, Child1.x, Child2.x
Parent.x = 3
print Parent.x, Child1.x, Child2.x

The output result will be:

1 1 1
1 2 1
3 2 3

What confuses or surprises many people is why the last line of output is 3 2 3 instead of 3 2 1. Why is it also changing parent.x at the same time? Changed the value of child2.x? But at the same time the value of Child1.x is not changed?

The key to this answer is that in Python, class variables are passed internally as a dictionary.

If a variable name is not found in the dictionary under the current class. Then search exhaustively in higher-level classes (such as its parent class) until the referenced variable name is found. (If the reference variable name is not found in its own class or a higher-level class, an attribute error will be raised.)

Therefore, set x = 1 in the parent class and let the variable x class (with value 1) Can be referenced in its class and its subclasses. This is why the output of the first print statement is 1 1 1

Therefore, if any of its subclasses are overwritten with a value (for example, when we execute the statement Child1.x = 2), this value Modified only in subclasses. This is why the output of the second print statement is 1 2 1

Finally, if this value is modified in the parent class, (for example, when we execute the statement Parent.x = 3), this change Will affect those values ​​that have not been overridden by the subclass (in this example, Child2). This is why the output result of the third print statement is 3 2 3

4. The following code outputs the result under Python2 What will it be? please explain.

def div1(x,y):
    print "%s/%s = %s" % (x, y, x/y)
def div2(x,y):
    print "%s//%s = %s" % (x, y, x//y)
div1(5,2)
div1(5.,2)
div2(5,2)
div2(5.,2.)

How will the results be different under Python3? (Assuming, of course, that the above print statement is converted to Python3's syntax)

In Python2, the output of the above code will be

5/2 = 2
5.0/2 = 2.5
5//2 = 2
5.0//2.0 = 2.0

By default, Python 2 automatically performs integer calculations if both is an integer. Therefore, 5/2 results in 2, and 5./2 results in 2.5

Note that in Python 2, you can override this behavior by adding the following reference.

from future import division


Also note that the // operator will always perform integer division, regardless of the type of the operator. That's why even in Python 2 the result of 5.0//2.0 is 2.0. However, in Python3, there is no such feature,

例如,在两端都是整形的情况下,它不会执行整形除法

因此,在Python3中,将会是如下结果:

5/2 = 2.5
5.0/2 = 2.5
5//2 = 2
5.0//2.0 = 2.0

注: 在 Python 3 中,/ 操作符是做浮点除法,而 // 是做整除(即商没有余数,比如 10 // 3 其结果就为 3,余数会被截除掉,而 (-7) // 3 的结果却是 -3。这个算法与其它很多编程语言不一样,需要注意,它们的整除运算会向0的方向取值。而在 Python 2 中,/ 就是整除,即和 Python 3 中的 // 操作符一样)

5、下面代码的输出结果将是什么?

list = ['a', 'b', 'c', 'd', 'e']
print list[10:]

下面的代码将输出[],不会产生IndexError错误。就像所期望的那样,尝试用超出成员的个数的index来获取某个列表的成员。

例如,尝试获取list[10]和之后的成员,会导致IndexError.

然而,尝试获取列表的切片,开始的index超过了成员个数不会产生IndexError,而是仅仅返回一个空列表。

这成为特别让人恶心的疑难杂症,因为运行的时候没有错误产生,导致bug很难被追踪到。

6、考虑下列代码片段:

list = [ [ ] ] * 5
list  # output?
list[0].append(10)
list  # output?
list[1].append(20)
list  # output?
list.append(30)
list  # output?

2,4,6,8行将输出什么结果?试解释。

输出的结果如下:

[[], [], [], [], []]
[[10], [10], [10], [10], [10]]
[[10, 20], [10, 20], [10, 20], [10, 20], [10, 20]]
[[10, 20], [10, 20], [10, 20], [10, 20], [10, 20], 30]

解释如下:

第一行的输出结果直觉上很容易理解,例如 list = [ [ ] ] * 5 就是简单的创造了5个空列表。然而,理解表达式list=[ [ ] ] * 5的关键一点是它不是创造一个包含五个独立列表的列表,而是它是一个创建了包含对同一个列表五次引用的列表。只有了解了这一点,我们才能更好的理解接下来的输出结果。

list[0].append(10) 将10附加在第一个列表上。

但由于所有5个列表是引用的同一个列表,所以这个结果将是:

[[10], [10], [10], [10], [10]]

同理,list[1].append(20)将20附加在第二个列表上。但同样由于5个列表是引用的同一个列表,所以输出结果现在是:

[[10, 20], [10, 20], [10, 20], [10, 20], [10, 20]]

作为对比, list.append(30)是将整个新的元素附加在外列表上,因此产生的结果是: [[10, 20], [10, 20], [10, 20], [10, 20], [10, 20], 30].

7、Given a list of N numbers。

给定一个含有N个数字的列表。

使用单一的列表生成式来产生一个新的列表,该列表只包含满足以下条件的值:

(a)偶数值

(b)元素为原始列表中偶数切片。

例如,如果list[2]包含的值是偶数。那么这个值应该被包含在新的列表当中。因为这个数字同时在原始列表的偶数序列(2为偶数)上。然而,如果list[3]包含一个偶数,

那个数字不应该被包含在新的列表当中,因为它在原始列表的奇数序列上。

对此问题的简单解决方法如下:

[x for x in list[::2] if x%2 == 0]

例如,给定列表如下:

list = [ 1 , 3 , 5 , 8 , 10 , 13 , 18 , 36 , 78 ]

列表生成式[x for x in list[::2] if x%2 == 0] 的结果是,

[10, 18, 78]

这个表达式工作的步骤是,第一步取出偶数切片的数字,

第二步剔除其中所有奇数。

8、给定以下字典的子类,下面的代码能够运行么?为什么?

class DefaultDict(dict):
  def __missing__(self, key):
    return []d = DefaultDict()
d['florp'] = 127

能够运行。

当key缺失时,执行DefaultDict类,字典的实例将自动实例化这个数列。

相关学习推荐:python视频教程

The above is the detailed content of Detailed summary of python interview questions (with answers). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:公众号:马哥Linux运维. If there is any infringement, please contact admin@php.cn delete
Python vs. C  : Understanding the Key DifferencesPython vs. C : Understanding the Key DifferencesApr 21, 2025 am 12:18 AM

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Python vs. C  : Which Language to Choose for Your Project?Python vs. C : Which Language to Choose for Your Project?Apr 21, 2025 am 12:17 AM

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

Reaching Your Python Goals: The Power of 2 Hours DailyReaching Your Python Goals: The Power of 2 Hours DailyApr 20, 2025 am 12:21 AM

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Maximizing 2 Hours: Effective Python Learning StrategiesMaximizing 2 Hours: Effective Python Learning StrategiesApr 20, 2025 am 12:20 AM

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Choosing Between Python and C  : The Right Language for YouChoosing Between Python and C : The Right Language for YouApr 20, 2025 am 12:20 AM

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python vs. C  : A Comparative Analysis of Programming LanguagesPython vs. C : A Comparative Analysis of Programming LanguagesApr 20, 2025 am 12:14 AM

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

2 Hours a Day: The Potential of Python Learning2 Hours a Day: The Potential of Python LearningApr 20, 2025 am 12:14 AM

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment