Python 3.2 idle: range function - print or list?

I know this is wrong, but I am using python 3, but studying it with a python 2 book.

He says,

>>>range(2,7) 

will show

 [2,3,4,5,6] 

but I know that he will not show the way out above, THIS I understand. so i tried:

 >>>>print(range(2,7)) 

and ta-da- it shows the following:

 range(2,7) 

it looks like this is a change from P2 to P3, so I tried:

 list(range(2,7)) 

This mode works fine in IDLE, but does not work in notepad for long coding. so finally i tried:

 print(list(range(2,7))) 

and he showed something similar to what I intended ... Am I doing the right thing? Is this the only way to write this?

+6
python list printing range
source share
2 answers

In your IDLE case, you run the code in the IDLE PyShell window. This runs an interactive interpreter. In interactive mode, Python immediately interprets each input line and displays the value returned by evaluating the operator you entered, plus everything 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 it in other places in iterative contexts. Python 3 range () is similar to Python 2 xrange () .

When you edit a file in an editor, such as Notepad, you write a script file, and when you run the file in the Python interpreter, the entire script is interpreted and run as a unit, even if it is only one line. On the screen you see only what is written to standard output (ie, " print() ") or standard error (ie error tracing); You do not see the results of the evaluation of each operator, as in interactive mode. So, in your example, when you run from a script file, if you do not print the results of the evaluation of something, you will not see it.

The Python tutorial talks about this here .

+6
source share

If your only goal is to get the list back, then what you are doing is right. Python 3.0 now treats range as a return iterator (which xrange used)

+4
source share

All Articles