简体   繁体   中英

Erroneous example in official Python tutorial (Chapter 9.10)?

I copied the following example from Python 3.6.1 Documentation, Chapter 9.10 into Jupyter Notebook (Python version 3.6.1):

xvec = [10, 20, 30]

yvec = [7, 5, 3]

sum(x*y for x,y in zip(xvec, yvec))         # dot product

While the official documentation says that it would print 260 , I got the following error in Notebook:

----> 4 sum(x*y for x,y in zip(xvec, yvec))
TypeError: 'int' object is not callable

This is definitely not just a question on 'int object is not callable', but more on the palpable error in what is considered to be the gospel for Python.

If by mistake you have overwritten zip() or/and sum() , which leads that your current code will not work. You can restore their default functionalities using del , like this example:

>>> zip = [1]
>>> zip
[1]
>>> del zip
>>> zip
<function zip>

So, you can try :

>>> del zip
>>> del sum
>>> xvec = [10, 20, 30]
>>> yvec = [7, 5, 3]
>>> sum(x*y for x,y in zip(xvec, yvec))

And it will output:

260

The code should work as long as you didn't overwrite zip or sum :

>>> xvec = [10, 20, 30]
>>> yvec = [7, 5, 3]
>>> sum(x*y for x,y in zip(xvec, yvec))
260

Make sure that you didn't overwrite them:

>>> sum = 0  # <--- overwrite
>>> sum(x*y for x,y in zip(xvec, yvec))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM