Python 3.2 idle : range function - print or list?
I know this is wrong thing to do, but I am using python 3 but studying it with python 2 book.
it says,
>&g开发者_开发技巧t;>range(2,7)
will show
[2,3,4,5,6]
but I know it won't show the output above, THAT I figured. so I tried:
>>>>print(range(2,7))
and ta-da- it shows follow:
range(2,7)
looks like this is the one of changes from P2 to P3 so I tried:
list(range(2,7))
this one works ok on IDLE but not ok on notepad for long coding. so finally I tried:
print(list(range(2,7)))
and it showed something similar to what I intended... Am I doing right? Is this the only way to write it?
In your IDLE case, you are running the code in IDLE's PyShell window. This is running the interactive interpreter. In interactive mode, Python interprets immediately each line you type in and it displays the value returned by evaluating the statement you typed plus anything written to standard output or standard error. For Python 2, range()
returns a list and, as you discovered, in Python 3, it returns an iterable range()
object which you can use to create a list object or use elsewhere in iteration contexts. The Python 3 range() is similar to Python 2's xrange().
When you edit a file in an editor like Notepad, you are writing a script file and when you run the file in the Python interpreter, the whole script is interpreted and run as a unit, even if it is only one line long. On the screen, you only see what is written to standard output (i.e. "print()
") or standard error (i.e. error tracebacks); you don't see the results of the evaluation of each statement as you do in interactive mode. So, in your example, when running from a script file, if you don't print the results of evaluating something you won't see it.
The Python tutorial talks a bit about this here.
If your only goal is to get back the list representation, what you're doing is correct. Python 3.0 now treats range
as returning an iterator (what xrange
used to do)
精彩评论