开发者

Why won't the len() function output anything in python 3.1.2?

I installed the 3.1.2 IDLE python console, then I entered this code:

>>> a = ['a', 'b', 'c', 'd']
>>> len(a)
4

Directly from the python official docs http://docs.python.org/py3k/tutorial/introduction.html#lists

But it does not work in the interpreter as it should, it does not return 4.

What am I doing wrong? Are the official docs 开发者_C百科wrong?

I've looked in a few other sites but many are talking about Python 2.x.


There is no bug; you have misunderstood what should happen.

Python can be called interactively (by running python.exe at the prompt). This mode automatically prints the result of a line when it is finished, for ease of reading/debugging. However, it's not very useful for writing any serious amount of code.

The way do to that is to put the code in a script (a plain text file with a .py ending on Windows) and call the script with python.exe foo.py. In this case, something else happens: Python executes the script and does not automatically print the result of every line. That's what the print function/statement is for. Write print(len(a)) instead.

Note that this has nothing to do with the version of Python you are using.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜