1

I'm having a small issue using Python with Atom. My code executes fine expect that in order for me to see results of functions I need to include a print statement. If I include a return instead statement I do not see the result. How can I fix this?

EDIT

Here's a reproducible example. No output is returned by Atom when I execute Python code from it (Note, I am using the language-python package in Atom).

def multiplier(i, j):
    output = i * j
    return(output)

multiplier(2, 5)

if I instead do:

def multiplier(i, j):
    output = i * j
    print(output)

multiplier(2, 5)

I get an output of 10 from Atom.

user3141121
  • 480
  • 3
  • 8
  • 17

2 Answers2

3

A return statement sends the output of the function back to where it was called from. This will not print the output.

You could put a print statement just before the return statement if you want to see the output.

This is not an issue with Atom, as it is just a text editor, though it can execute python code by installing a package.

Chris
  • 4,009
  • 3
  • 21
  • 52
2

Some editors and IDEs and environments like the python REPL and jupyter implicitly print the results of statements as they are executed. But that's not python itself.

Atom is just running the code that you give it and presenting its output to you. Since your initial code has nothing that explicitly produces any output, it doesn't print anything.

In your case, it's probably best to leave the function multiplier as-is: you probably don't always want it to print anything, but you do want it to return the value to whatever program or other function has called it.

So a better fix is to replace multiplier(2, 5) with print(multiplier(2, 5)) which explicitly prints the result when you call it.

For the aficionados (and or for the next steps as you're learning the language), it's probably useful to know that the REPL and Jupyter give you an unambiguous representation of the object (usually the result of the __repr__ method) -- vs print which gives you a "pretty" version (usually the result of the __str__ method). See this question which discusses the difference and this one about the REPL and __repr__.

Andrew Jaffe
  • 26,554
  • 4
  • 50
  • 59
  • Thanks, this is helpful. I am just confused as to why when I run the `multiplier` function in a session of Python opened directly from the terminal I get an output using the `return` function. Based on your description, I should expect the `multiplier` function to return nothing as well there. – user3141121 Nov 15 '19 at 19:27
  • 1
    There is a difference between the “python interpreter” on the one hand and what happens when you type`python` at the command line or use jupyter on the other. The latter is intended to be used interactively and so, by convention, outputs the `repr` of the statements as they are executed. – Andrew Jaffe Nov 15 '19 at 20:37