This question already has answers here:
What's the difference between eval, exec, and compile?
(3 answers)
Closed 5 years ago.
In python, if I exec a statement which prints a value, I will see the output, e.g., exec("print 10") gives me output 10. However, if I do exec("10") I got nothing as output, where as if I type 10 in the interactive shell I got 10 as output. How do I get this output when using exec? That is if the statement to be executed is an expression, I print its result.
My question is how I can decide whether the statement to execute is an expression. Am I supposed to do the following:
def my_exec(script):
try:
print eval(compile(script, '<string>', 'eval'))
except SyntaxError:
exec(script)
# Prints 10.
my_exec("print(10)")
# Prints 10 as well.
my_exec("10")
UPDATE:
Basically I want the behavior of executing a cell in a jupyter notebook.
First of all, executing 10 doesn't make sense in real life. How can you execute a number? But, you can execute a command like exec("print(10)"). I don't see the need of creating a my_exec function. It behaves the same as the normal exec. In the interactive shell, everything works differently, so don't try to compare. Basically, exec("print(10)") is the command you are looking for. Another way not using exec is print(10).
Related
i wonder how to import python console in my python script.
If there are a script named script1.py, that taking string input from console.
What i want to do is that, if i give string input "print(5)" to the script1.py,
than it executes the print(5) (which will give the 5 as result as we use the python console).
Use the python eval() function, as in https://docs.python.org/3/library/functions.html#eval. That evaluates any input string as python code.
For instance:
x = 1
eval('x+1')
2
Be careful with eval though; if the string to be evaluated comes from unprotected user input, it can do anything your own python code can do.
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
This question already has answers here:
Python 3 print without parenthesis
(10 answers)
Closed 4 years ago.
So I started learning python 3 and I wanted to run a very simple code on ubuntu:
print type("Hello World")
^
SyntaxError: invalid syntax
When I tried to compile that with command python3 hello.py in terminal it gave me the error above, but when used python hello.py (I think it means to use python 2 instead of 3) then it's all fine. Same when using python 3 and 2 shells in the terminal.
It seems like I'm missing something really stupid because I did some research and found no one with the same issue.
In Python3, print was changed from a statement to a function (with brackets):
i.e.
# In Python 2.x
print type("Hello World")
# In Python 3.x
print(type("Hello World"))
In Python 3.x print() is a function, while in 2.x it was a statement. The correct syntax in Python 3 would be:
print(type("Hello World"))
This is because from Python 3, print is a function, not a statement anymore. Therefore, Python 3 only accepts:
print(type("Hello World"))
This question already has an answer here:
How can I decorate all functions imported from a file?
(1 answer)
Closed 4 years ago.
I'd like to automatically print python statements as they are called in a script while the script runs. Could anybody show a ready-to-use solution?
For example, I may have the following python code.
print "xxx"
myfun()
I'd like print "xxx" and myfun() be printed exactly in the output.
One solution is manually to add a print statement to each function. But this is combersome.
print 'print "xxx"'
print "xxx"
print 'myfun()'
myfun()
The following solutions just can not do so. Please do not mark this question as duplicate.
The solution here will not only print the functions in the current script but also functions in other scripts used in the current scripts. These solutions are not what I need.
How do I print functions as they are called
The following does not do what I need because it does not limit the decoration to the current file. For example, it uses import mymod1; decorate_all_in_module(mymod1, decorator). I don't have a module. I want to print the statements in the current script.
How can I decorate all functions imported from a file?
There is no "ready-to-use" solution to this problem. You are asking for a programming language with different semantics than the Python language: therefore you will either need to write code to get this effect, or use a different language, or both.
That said, for solving your actual problem, I believe simply using a debugger would do what you want: that way you can step over each statement in your program and observe as they are executed.
This question already has answers here:
What does "SyntaxError: Missing parentheses in call to 'print'" mean in Python?
(11 answers)
Closed 6 years ago.
I am learning a tutorial for Python language and trying to write a basic "Hello World!" program.
But when I do all steps described in the book I receive an error.
>> print "Hello World!"
SyntaxError: Missing parentheses in call to 'print'
Why I am getting this error?
Is my book wrong?
it seems that you're using Python 3.x.
In python 3.x, the print statement is a function and you need to use it as a function like this
print("Hello World!")
Your book is right, but might be outdated a bit. It seems it describes Python version 2, but you try to run your example on the version 3.
Python 3 has changed some features and this one is the most annoying to switch from P2 to P3.
"print" statement changed to function rather than operator as was in P2.
Calling function you should always use parentheses.
So, if you want to run your program in Python3 you should call it:
print("Hello World!")
And that's it.
If you want to use examples from your book as is - install Python2 and it should work.