pythonread-eval-print-loop

Why does the Python shell output something even when there is no "print" command?


I wrote the following code in Python IDLE, using its editor

import urllib.request
print(urllib.request.urlopen('https://github.com').read().decode('utf-8'))

and then saved the code as a script. After I ran the script, Python displayed the page source I want.

When I changed the above code to:

import urllib.request
urllib.request.urlopen('https://github.com').read().decode('utf-8')

and then ran the script, Python displayed nothing. This is understandable.

The weird thing for me, however, is that if I run the above code (the one without print) interactively in a Python shell, Python shell can still display the page source, as you see:

>>> import urllib.request
>>> urllib.request.urlopen('https://github.com').read().decode('utf-8')
'\n\n\n\n\n\n<!DOCTYPE html>\n<html\n  lang="en"\n  \n  \n ...'

(output snipped)

I don't understand why.


Solution

  • You are using the interactive python prompt. It automatically prints return values for you so that you can see the result of what you're doing.

    Try typing 3 + 2. You know this doesn't print anything either - but you will see the result.

    Likewise, if you put those two lines into a file you won't get any output.