Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return statement on Python does not seem to work (on Spyder)

I have been using Python for a while and have had no problems with the IDE I've used (I've used WingIDE, now I use Spyder).

But when I started testing some code, which I typed on the editor, today, the return statement does not seem to work. Then I wrote even more basic tests which see what return does, and found out that other functions do not work properly as well.

For example for the function,

def test():
    return 2

'''the code below is written in the editor'''
test()
print(type(test()))
print(test())

After running the code on the editor.

test() returns 'nothing' (but it's not actually 'nothing/None/blank space')

type(test()) returns 'nothing' (but it's not actually 'nothing/None/blank space')

print(type(test()) prints 'class 'int' '

print(test()) prints 2

But when I type test() on the console, it returns 2, and when I type type(test()) on the console, it returns class: int.

Note that the same results occur before and after I updated Spyder. And previously, the code in the editor functions the same way as the code in the console, as in typing test() in the editor would have returned 2 when I run the code in the editor.

Python/Spyder hasn't done anything this strange before, what happened?

Here's a visualization. Code in editor

enter image description here

Result after running code in editor displayed in the console

enter image description here

like image 988
JtheStudent Avatar asked Apr 09 '26 14:04

JtheStudent


1 Answers

Assuming that the missing output of lines 116-118 is what upsets you:

The editor is handling your code as a normal python script which means statements ala test() don't print their result.

That you get the result of something displayed immediately is a special function of the python console and not normal python behavior.

To actually print the result you have to call print(test()) as you did in line 119-120


Update: After some testing in PyCharm I got the following behavioir:

Copy&Pasting into the python console:

def test():
    return 2
test()
>>press enter

indeed results in a blank output, but this:

def test():
    return 2
>>press enter
test()
>>press enter

prints 2 as expected. So my conclusion is that Spyder is maybe not displaying the return value because it was executing a multi-instruction script instead of a single operation.

like image 58
Fabian N. Avatar answered Apr 12 '26 03:04

Fabian N.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!