Program not showing returned values - python

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."))

Related

Why are f-strings not printed in Python class methods?

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.

Python function return value vs print [duplicate]

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

Clearing Print in Python

So I'm pretty new to both coding and this website, so please bear with me if this is stupid:
I'm working on a personal project and would like to find a way to clear "print()" statements in python 3.6. For example:
print("The user would see this text.")
but if I continue
print("The user would see this text.")
print("They would also see this text.")
Is there a way to make it so a user would only see the second print statement?
I have seen "os.system('cls')" and "os.system('clear')" recommended, but I get these errors for each:
os.system('cls')
resulting in
sh: 1: cls: not found
and
os.system('clear')
resulting in
TERM environment variable not set.
Obviously I'm missing something, but if you know what it'd be much appreciated. If you know of another way to do what I'm thinking, that would also be awesome. Thank you for taking the time to read this, and thanks for any help.
Edit: I'm using Repl.it as my IDE. Could this be an issue with that site specifically?
Edit: Downloaded a new IDE to check, and the reply worked. If you are new and using Repl.it, be aware that some code does not function properly.
The method that I've used in the past to 'reprint' something on an existing line is to make use of the standard output directly, coupled with a carriage return to bring the printed statement's cursor back to the start of the line (\r = carriage return), instead of relying on the print function.
In pseudocode:
# Send what you want to print initially to standard output, with a carriage return appended to the front of it.
# Flush the contents of standard output.
# Send the second thing you want to print to standard output.
A working example in Python:
import sys
sys.stdout.write('\rThe user would see this text')
sys.stdout.flush()
sys.stdout.write('\rThe user would also see this text')
Edit
Figured I'd add an example where you can actually see the code working, since the working example above is going to execute so quickly that you'll never see the original line. The below code incorporates a sleep so that you can see it print the first line, wait, then reprint the line using the second string:
import sys
from time import sleep
sys.stdout.write('\rThe user would see this text')
sys.stdout.flush()
sleep(2)
sys.stdout.write('\rThe user would also see this text')

Scrapy Shell: How to execute multiple lines of code in shell?

You will see in the screenshot that pressing enter after pasting a multiline code doesnt run it but merely send each time a "...".
How can I run this multiline pasted code?
someone asked here, but did not get (the right) answer;
Did not work:
Backspace
Use the arrow key to move the cursor, then use the delete key
Escape
F2
Pressing enter twice when inside the Python interpreter executes a block of code, but you have an unmatched open parenthesis on the last line, so you haven't completed defining the block of code. Also, I'm not sure what dic is in the last line, because you haven't included its definition, so you may need to fix that as well.
Running
a=[1,2]
for x in a:
print(x)
actually works (pressing 2 enters worked as expected). So I made a mistake in the code above. I aplogise, I should have checked that before.
I don't delete the question since the one on google can be confusing (the guy did not mentioned it was his mistake, so I though there was a trick to be found. The trick is to check the code).
you could use IPython link which simplifies the process, better yet you have access to every command line as if executed inside the shell.
The other alternative is to encapsulate this inside a function
I know this answer is a bit late, but someone will need the information sometime:
When you make a new line, i.e. title.quote.... you need to press the tab to create an indent, then it will work. Without indenting, you get the "expected an indent" error message.

Python IDLE with Python 3.5.2 "crashing"

Okay, so let me just say beforehand: I am new to Python. I was just experimenting with IDLE and then I had this weird "crash". I put "crash" inside speech marks because I'm not sure if it qualifies as a crash, as rather than the program just crashing the way a normal program would in Windows, it still runs, but whenever I press enter and try and get it to accept new text it doesn't do anything. E.g. if you try and type "print('a')" and then hit enter it just goes to the next line (and doesn't print 'a'). I tried to make a simple function which converted an integer to a string where each character in the string was either a '1' or a '0', forming the binary number representing said (unsigned) integer.
>>> def int_to_str(int_in):
str_out=''
bit_val=1<<int_in.bit_length()
while(int_in>0):
if(int_in>bit_val):
str_out+='1'
int_in-=bit_val
else:
str_out+='0'
bit_val>>=1
return str_out
>>> print('a')
print('c')
Basically, it becomes completely unresponsive to my input, and allows me to edit/change "print('a')" even though I shouldn't be able to if it had actually "accepted" my input. Why is this? What have I done wrong/messed up?
Also, I made sure it isn't something else I was previously messing around with by closing the shell and opening it again and only putting in said code for the "int_to_string" function, and I haven't changed any settings or imported any modules before hand or anything like that (in case it matters).
EDIT: I tried reinstalling, and that helped a bit in that I can now do other stuff fine, but the moment I try to use the "str_to_int()" function, it has this same weird behaviour of not accepting/interpreting any more user input.
Your while loop never terminates, you need to re-arrange your logic. Printing variables can be an effective debugging tool - like this:
>>> def int_to_str(int_in):
str_out=''
bit_val=1<<int_in.bit_length()
while(int_in>0):
print(int_in, bit_val)
if(int_in>bit_val):
str_out+='1'
int_in-=bit_val
else:
str_out+='0'
bit_val>>=1
return str_out
If your program seems to be going on too long you can stop it with ctrl-c.

Categories

Resources