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

Question:

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 shell 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 shell 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:

enter image description here

I don’t understand why.

I use Python 3.6.3.

Asked By: failbetter

||

Answers:

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.

Answered By: Shadow

It’s because the shell is printing the result of execution. If you assign the function call to a variable then it will suppress the printing.

i.e. html = urllib.request.urlopen( ... )

Answered By: Jordan

How do I avoid printing the result of execution, Only If I have print statement I want it to be printed. Any help experts on this.

Regards
Kanni

Answered By: Mahesh Madicherla
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.