This question already has answers here:
What is the purpose of the return statement? How is it different from printing?
(15 answers)
Closed 6 months ago.
I am exceedingly new to programming, so go easy on me. I use Visual Studio Code as my editor in which I am working on a few python files. When I run the code, say for instance a pandas.dataframe.head() function, it doesn't return anything in the terminal. But when I print the same return value, I am seeing the data from a csv file as expected.
Can anyone explain what is going on?
Is it the case that when a function is run, that the data is stored but not necessarily displayed?
If so, is print the only means of displaying the value of a function when debugging?
Tried googling answers, but don't have clarity yet.
import pandas as pd
df = pd.read_csv('sample.csv')
df.head()
# print(df.head())
Expect some data to be displayed in the terminal
I believe you have learned using either Jupyter or a python console. VS Code is an IDE; it's basically a glorified text editor with features that help developers. You must be used to using python in the console where each line/command it automatically prints the results, whereas you are now likely creating a script and expect the same thing to happen. I don't believe `return has anything to do with what you're asking as it acts the same either way.
EDIT (as I found the actual documentation)
When in an interactive console python calls sys.displayhook after every execution. here's the actual documentation:
If value is not None, this function prints repr(value) to sys.stdout,
and saves value in builtins._. If repr(value) is not encodable to
sys.stdout.encoding with sys.stdout.errors error handler (which is
probably 'strict'), encode it to sys.stdout.encoding with
'backslashreplace' error handler.
sys.displayhook is called on the result of evaluating an expression
entered in an interactive Python session. The display of these values
can be customized by assigning another one-argument function to
sys.displayhook.
Here's my very basic explanation I hope I explain it well enough
In the python console each line/command's results are printed after execution (ie: when you hit enter). (For context, every function/operation implicitly returns None if nothing else is returned, therefore not printed)
When running a python script, nothing will display in the console unless explicitly printed (other cases are uncaught error tracebacks, logging, or writing to stdout, etc...)
So basically the line
df.head()
In a script performs the head function on df and returns the results but nothing happens to the results, unless you assign it to a variable or print it. It's the same as just writing:
"This will only print in a console"
If that line is executed in an interactive console it will call sys.displayhook with the value and print the results:
'This will only print in a console'
But if ran in a script it is essentially a needless line of code unless assigned to a variable.
Basically, the console assumes you want to see results as you code. (basically calling a special print at every line that doesn't print None and isn't called when print is explicitly run) Whereas when running a script it only prints to the console when explicitly asked or other special cases.
Are the first 5 rows of your 'sample.csv' file blank per chance? If not selected, the df.head() returns (https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.head.html) the first 5 rows. So:
import pandas as pd
df = pd.DataFrame({'animal':['alligator', 'bee', 'falcon', 'lion', 'monkey', 'parrot', 'shark', 'whale', 'zebra']})
print(df.head())
animal
0 alligator
1 bee
2 falcon
3 lion
4 monkey
If you want to get a value from a function and use it elsewhere, you should return that value at the end of the function definition. That way when you call the function at some point in your code and you can assign it to a variable which would store the output of the function
For instance
#test.py
def square(i):
return i*i
def main():
eight_square = square(8)
print(eight_square)
Only if you print the output you can actually see it in the terminal when you run python3 test.py. There are other ways to check, what the value is in a variable, for instance using a debugger. Visual Studio can be configured with a debugger if it isn't set up.
A breakpoint is to be set at the location where the value of the variable has to be found and the debugger has to be started.
Reference: Microsoft visual studio docs
Related
I would like to understand why f-strings do not print output in class methods. I would like to use their concise syntax for making breakpoints.
MWE:
class FStringTest:
def test(self):
print('why does this work')
f'but not this'
print(FStringTest().test())
f'yet this works'
Output:
why does this work
None
yet this works
Are you running this in Jupyter or an interactive python shell?
Because if you were, then the 'P' in REPL, which stands for print (R=READ,E=EVALUATE,P=PRINT,L=LOOP), will print the yet this works automatically for you without you explicitly calling the print function.
So:
why does this work
This is what the print inside your method returns.
None
You're seeing this because you're printing the value that your test() method is returning, and since it happens that it returns nothing (no return) it gives you this 'None' value.
yet this works
This is just what the REPL echoing back to you.
Note: Save this as a python script (.py) and try running it in an IDE like VSC, or via the command line using py <script_name>.py, it will not show you that last line of output.
I'm trying to import a CSV into pandas and view the data frame. I'm following a tutorial that says I can e.g. retrieve the headers via data.head().
This doesn't return anything when I run the program and I have to put print around everything to make it work.
What am I doing wrong?
import os
path = "testdata"
os.chdir(path)
os.getcwd()
data = pd.read_csv("testdata.csv")
print(data.head())
list(data.columns.values)
Your tutorial is expecting that you are typing your Python code at an interpreter's read-execute-display prompt (such as the command-line Python interpreter, or IDLE), normally indicated by >>>. But you are running your code in PyCharm as a program. If you want the behaviour you expect in PyCharm, ask it to open a Python console and type your code there.
You are not doing anything wrong, but you probably don't understand the meaning of return. data.head() returns the first five values of data. However, if you would use it like this:
data.head()
It will return into nothing, so whatever the function returns is discarded. You could either print the data that it returns in the console, like you did:
print(data.head())
Or you could save it in a variable and print that or do something else with it:
someVariable = data.head()
print(someVariable)
# Or do something with someVariable
If you are typing this code in the interpreter, the return value of data.head() would be written to the console automatically. Like this (from this example):
>>> df.head()
animal
0 alligator
1 bee
2 falcon
3 lion
4 monkey
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
Result after running code in editor displayed in the console
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.
To expand Fabian's N. answer, Spyder has different evaluation models:
Run file, which is equivalent to python my_file.py.
Run line and Run cell, which copy the contents of a line or a cell to the IPython console and run it there. This model doesn't require adding print's to your code.
I saw the code in an answer here, and I'm trying to pick it apart to see how it works. I think I understand it (using the or operator as a sort of ersatz "if" statement.), but that's not the issue here. It is supposed to return a value, and after visualizing the code(done here) it apparently IS returning a value. However, when I run it in the terminal, no values are ACTUALLY displayed. What is happening?
def ispalin(word):
return(not word) or (word[0]==word[-1] and ispalin(word[1:-1]))
ispalin(input("Enter a word."))
When this runs, it asks for a value, but nothing is displayed.
Unless you run code in the interpreter, Python will not just print return values in module-level code.
You need to explicitly print your result:
print(ispalin(input("Enter a word.")))
The interactive interpreter session is a REPL, or Read-Eval-Print loop, where it'll print the results of whatever you try, but when you run code from the command line or when doubleclicking on your script, no printing takes place.
That is because you are just returning the value and not printing it
print (ispalin(input("Enter a word.")))
Will print out your values
O/P after changing the sentence
Enter a word.malayalam
True
Try,
print ispalin(input("Enter a word."))
I want to set a breakpoint on the set.update() function, but when I try, I get an error message.
Example:
ss= set()
ss.update('a')
Breakpoint:
b set.update
b ss.update
Errors:
The specified object 'ss.update' is not a function
or was not found along sys.path.
The specified object 'set.update' is not a function
or was not found along sys.path.
(Note, I also tried with the parentheses at the end, e.g., b set.update(), but still got the error. I didn't print all the permutations of errors.)
Thanks! Using #avasal's answer and Doug Hellmann's pdb webpage, I came up with this:
Since I was trying to catch set.update, I had to edit the sets.py file, but that wasn't enough, since python was using the builtin set class rather than the one I edited. So I overwrote the builtin sets class:
import sets
locals()['__builtins__'].set=sets.Set
Then I could set conditional break points in the debugger:
b set.update, iterable=='a' #successful
b set.update, iterable=='b' #won't stop for ss.update('a')
My entire example file looks like this:
import pdb
import sets
locals()['__builtins__'].set=sets.Set
pdb.set_trace()
ss = set()
ss.update('a')
print "goodbye cruel world"
Then at the debugger prompt, enter this:
b set.update, iterable=='a'
Hope this helps others too.