Syntax error when defining a function on the Python command line - python

I am trying to define a function on the Python REPL. Every time I try to run the below code, I get a syntax error.
Code:
def hello():
print ("Hello!")
hello()
Error:
C:\Users\~\Desktop>python
Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 16:07:46) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> def hello():
... print ("Hello!")
... hello()
File "<stdin>", line 3
hello()
^
SyntaxError: invalid syntax
A possible explanation I've come across on stackoverflow is this post Python Error : File "<stdin>" where it says I can't run scripts from the Python interpreter. If that's true, why is that the case? I.e. if I'm able to run >>>2+2 in the cmd window, why am I not able to run a 'def' function? Hoping to look for clarification on this point - Thanks!
Edit: Put the error in text, not just the pic.

Press enter once after defining your function (that is, enter one blank line). Essentially, this lets Python know that you are done defining your function.
Once you see >>> again, you can call your function.
See the picture for how it should look when done right:

If you want to understand why this is happening, rather than just learn a workaround that works for some mysterious reason:
Interactive mode works by reading, compiling, and executing one statement at a time. This is a dead-simple rule—besides being dead-simple to implement it in the C code, it's also dead-simple to work through exactly in your head—once you understand it, that is. When given a choice between an implementation that's easy to explain, document, and work through in your head or one that's more complicated but sometimes easier to use, Python usually goes with the former.
If you enter a simple one-line statement, that's easy: the line is a complete statement, so it just compiles and executes that line.
But if you enter the first line of a compound statement—one that has a : on the end of the line and then an indented block—the statement isn't done until you write an indented block and then unindent again. So, it prints that special ... prompt instead of >>> to let you know it's continuing to read the same statement, and keeps going until you unindent.
If you unindent by typing a blank line, the statement is done, so it compiles and executes it, and everything is good.
If you unindent by typing a new one-liner statement, now it has two statements. If it tries to compile and run that as a single statement, that fails.
By the way, there's nothing magical about def here; the same thing will happen with any compound statement:
>>> for i in range(10):
... print(i)
... print('Done')
You'll get the same SyntaxError.
Couldn't Python figure out that you gave it two statements, and compile and run them one after another? Yes. In fact, if you use IPython/Jupyter, it actually does exactly that. But this would make the rule more complicated—not to mention things like handling exceptions in the first statement. Python chooses the simple rule you can trace through in your head over the complicated rule here, even though the complicated rule would do what you want more often.
So, how does this work in a module file? Well, modules aren't compiled a statement at a time, they're compiled all at once, as a list of statements, and then run all at once. That obviously doesn't work for the interactive terminal, because it can't run anything until it compiles everything, and it doesn't have everything until quitting time.
One last thing: why do continued expressions work?
>>> (1 +
... 2)
3
Expressions don't care about indentation. They end when all the parens/brackets/braces are balanced at the end of a line, not when the next line is unindented. So, as soon as you enter that 2), it knows the input is complete, and can compile it.
And the same thing is true for backslash continuation:
>>> 1 + \
... 2
3
No need for an unindented line; as soon as you type that 2 without a backslash continuation, the input is complete.

You should add a newline between defining function and calling it:
def hello():
print ("Hello!")
hello()

It looks like you've entered the whole block as a single statement. You'll need to hit enter after entering:
def hello():
print ("Hello!")
So that the interpreter understands that this is a single definition that you've entered. Once that's been defined, then try running the hello() function.

Related

How does python interpreter run the code line by line in the following code?

I have read that the interpreter runs the code line by line and reports the error if any at the same time and stops the further execution.
So in python, consider the file ex1.py,
print "Hello world"
12variable = 'bye'
print 12variable
Now according to the working of interpreter, the interpreter would run the first line i.e. it prints hello world first and then show the syntax error in the next line (line-by-line working). Hence the expected output is:
Hello world
12variable = 'bye'
^
SyntaxError: invalid syntax
But the actual output is -
12variable = 'bye'
^
SyntaxError: invalid syntax
Why it is not printing Hello World at the first?
It depends on how you run the Python interpréter. If you give it a full source file, it will first parse the whole file and convert it to bytecode before execution any instruction. But if you feed it line by line, it will parse and execute the code bloc by bloc:
python script.py : parse full file
python < script.py : parse and execute by bloc
The latter is typically the way you use it interactively or through a GUI shell like idle.
It's a myth that Python is a fully interpreted language. When CPython runs a script the source code is parsed (this is where it will catch syntax errors), and compiled into bytecode (sometimes these are cached in your directory as .pyc files) before anything is executed. In this regard Python is not all that fundamentally different than Java or C# other than that it doesn't spend much time doing any optimizations, and I believe the bytecode is interpreted one instruction at a time, instead of being JITed to machine code (unless you're using something like PyPy).
Because your understanding of the interpreter is faulty. While it is possible for the behaviour you are describing to occur for a subset of errors it is not the common case for many (most?) errors.
If the interpreter can construct what it thinks is a valid program but there is an error at run time then what you are describing will happen.
Since the case you are pointing at is a syntax error that prevents a valid program being constructed the behaviour is as you see it.
I understand it that way:
Python runs the code line by line after it's in byte code state.
The difference between this thing and compilation (in other languages like C++) is that you have to do this process of interpretation each time you run the script.
Python interpreter interprets the code each time you run the script.
In C++ you compile the program and you can execute it without having to compile it again unless you want to change the system.
Step 1:
The interpreter reads a python code or instruction. Then it verifies that the instruction is well-formatted, i.e. it checks the syntax of each line. If it encounters an error, it immediately halts the translation and shows an error message.
Step 2:
If there is no error, i.e. if the python instruction or code is well-formatted then the interpreter translates it into its equivalent form in an intermediate language called “Byte code”.Thus, after the successful execution of Python script or code, it is completely translated into Byte code.
Step 3:
Byte code is sent to the Python Virtual Machine(PVM).Here again, the byte code is executed on PVM. If an error occurs during this execution then the execution is halted with an error message.
So in your case, the "invalid syntax" error is thrown because of step1. But, the actual print function gets executed at step 3. step 3 comes only after step 1 right... I think got it now.

Python newbie problems

I just finished watching this video https://www.youtube.com/watch?v=qO4ZN5uZSVg, and even though it teaches 2.0 edition Python, some notes pop up for the 3.0 uses of python. Nevertheless, in the end, some challenges are provided, one of them is this:
def returnTwo():
return 20,30
x,y = returnTwo()
print(x,y)
Whenever i try to see what the conclusion will be, this is what comes up
def returnTwo():
return 20,30
(red X in the 3.5 Shell) x,y = returnTwo()
SyntaxError: invalid syntax.
What can I do?
The python shell allows to interactively run commands. This is very useful when doing quick calculations of to quickly check some small pieces of code.
In this case, you want to define a function. Defining a function is just that: a definition. Later on, you actually call the function and make it run. The issue here is that a function is (often) defined in more than one line. That means, you actually hit enter before you finish to define the function. For that reason, you tell the shell that you finished with an extra enter:
This also applies if you define your function in a single line:
And that's the reason why you get a SyntaxError: The line x, y = returnTwo() is supposed to be in the function, but for that, it would need to indented (to the level of return 20, 30):
Like #jim said, just try pressing enter until you get the >>> prompt again!
Remember that the three little dots do have a meaning too.
This question was already answered in the comments by #helios35 and #jim!
I just elaborate and post as an answer here for future users.

Python 3 print without parenthesis

The print used to be a statement in Python 2, but now it became a function that requires parenthesis in Python 3.
Is there anyway to suppress these parenthesis in Python 3? Maybe by re-defining the print function?
So, instead of
print ("Hello stack over flowers")
I could type:
print "Hello stack over flowers"
Although you need a pair of parentheses to print in Python 3, you no longer need a space after print, because it's a function. So that's only a single extra character.
If you still find typing a single pair of parentheses to be "unnecessarily time-consuming," you can do p = print and save a few characters that way. Because you can bind new references to functions but not to keywords, you can only do this print shortcut in Python 3.
Python 2:
>>> p = print
File "<stdin>", line 1
p = print
^
SyntaxError: invalid syntax
Python 3:
>>> p = print
>>> p('hello')
hello
It'll make your code less readable, but you'll save those few characters every time you print something.
Using print without parentheses in Python 3 code is not a good idea. Nor is creating aliases, etc. If that's a deal breaker, use Python 2.
However, print without parentheses might be useful in the interactive shell. It's not really a matter of reducing the number of characters, but rather avoiding the need to press Shift twice every time you want to print something while you're debugging. IPython lets you call functions without using parentheses if you start the line with a slash:
Python 3.6.6 (default, Jun 28 2018, 05:43:53)
Type 'copyright', 'credits' or 'license' for more information
IPython 6.4.0 -- An enhanced Interactive Python. Type '?' for help.
In [1]: var = 'Hello world'
In [2]: /print var
Hello world
And if you turn on autocall, you won't even need to type the slash:
In [3]: %autocall
Automatic calling is: Smart
In [4]: print var
------> print(var)
Hello world
Use Autohotkey to make a macro. AHK is free and dead simple to install. www.autohotkey.com
You could assign the macro to, say, alt-p:
!p::send print(){Left}
That will make alt-p put out print() and move your cursor to inside the parens.
Or, even better, to directly solve your problem, you define an autoreplace and limit its scope to when the open file has the .py extension:
#IfWinActive .py ;;; scope limiter
:b*:print ::print(){Left} ;;; I forget what b* does. The rest should be clear
#IfWinActive ;;; remove the scope limitation
This is a guaranteed, painless, transparent solution.
No. That will always be a syntax error in Python 3. Consider using 2to3 to translate your code to Python 3
The AHK script is a great idea. Just for those interested I needed to change it a little bit to work for me:
SetTitleMatchMode,2 ;;; allows for a partial search
#IfWinActive, .py ;;; scope limiter to only python files
:b*:print ::print(){Left} ;;; I forget what b* does
#IfWinActive ;;; remove the scope limitation
I finally figured out the regex to change these all in old Python2 example scripts. Otherwise use 2to3.py.
Try it out on Regexr.com, doesn't work in NP++(?):
find: (?<=print)( ')(.*)(')
replace: ('$2')
for variables:
(?<=print)( )(.*)(\n)
('$2')\n
for label and variable:
(?<=print)( ')(.*)(',)(.*)(\n)
('$2',$4)\n
You can use operator oveloading:
class Print:
def __lt__(self, thing):
print(thing)
p = Print()
p < 'hello' # -> hello
Or if you like use << like in c++ iostreams.
You can't, because the only way you could do it without parentheses is having it be a keyword, like in Python 2. You can't manually define a keyword, so no.
In Python 3, print is a function, whereas it used to be a statement in previous versions. As #holdenweb suggested, use 2to3 to translate your code.
I have configured vim to auto-add the parens around my debug def calls when I write the file. I use a simple watcher that auto-runs my updates when the timestamp changes. And I defined CTRL+p to delete them all. The only caveat is that I have to have them alone on a line, which I pretty much always do. I thought about trying to save and restore my previous search-highlight. And I did find a solution on Stack. But it looked a little too deep for now. Now I can finally get back to debugging Ruby-style with a quick p<space><obj>.
function! PyAddParensToDebugs()
execute "normal! mZ"
execute "%s/^\\(\\s*\\)\\(p\\|pe\\|pm\\|pp\\|e\\|ppe\\)\\( \\(.*\\)\\)\\{-}$/\\1\\2(\\4)/"
execute "normal! `Z"
endfunction
autocmd BufWrite *.py silent! call PyAddParensToDebugs()
map <c-p> :g/^\\s*\\(p\\\|pe\\\|pm\\\|pp\\\|e\\\|ppe\\)\\( \\\|\(\\)/d<cr>
I use these Python defs to do my debug printing.
def e():
exit()
def pp(obj):
pprint.PrettyPrinter(indent=4).pprint(obj)
def ppe(obj):
pprint.PrettyPrinter(indent=4).pprint(obj)
exit()
def p(obj):
print(repr(obj))
def pe(obj):
print(repr(obj))
exit()
def pm():
print("xxx")

Python - how can I define a function from within the Python shell?

>>> def f(x):
... print x
... f('hello')
File "<stdin>", line 3
f('hello')
^
SyntaxError: invalid syntax
>>>
I'm at the prompt in the Python shell. Why doesn't the above code work?
Enter a blank line after "print x". Generally, the ... prompt indicates that Python expects further input for the current block, in this case the function f.
As pointed out by Iguananaut IPython has superior editing capabilities compared to the standard Python shell, for example tab auto completion.
You need to press enter twice after the last line to get back to a >>> prompt in which case you can enter new expressions.
Also, if you're going to by typing lots of multi-line expressions into the interpreter you should give IPython (now with funding!) a look. It supports much better editing of multi-line statements, and even better still if you use the qtconsole or the notebook.

How to execute multi-line statements within Python's own debugger (PDB)

So I am running a Python script within which I am calling Python's debugger, PDB by writing:
import ipdb; ipdb.set_trace()
(iPython's version of PDB, though for the matter I don't think it makes a difference; I use it for the colored output only).
Now, when I get to the debugger I want to execute a multi-line statement such as an if clause or a for loop but as soon as I type
if condition:
and hit the return key, I get the error message *** SyntaxError: invalid syntax (<stdin>, line 1)
How can one execute multi-line statements within PDB? If not possible is there a way around this to still executing an if clause or a for loop?
You could do this while in pdb to launch a temporary interactive Python session with all the local variables available:
(pdb) !import code; code.interact(local=vars())
Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>>
When you're done, use Ctrl-D to return to the regular pdb prompt.
Just don't hit Ctrl-C, that will terminate the entire pdb session.
In python3 ipdb (and pdb) have a command called interact. It can be used to:
Start an interactive interpreter (using the code module) whose global namespace contains all the (global and local) names found in the current scope.
To use it, simply enter interact at the pdb prompt. Among other things, it's useful for applying code spanning multiple lines, and also for avoiding accidental triggering of other pdb commands.
My recommendation is to use IPython embedding.
ipdb> from IPython import embed; embed()
Inside the Python (2.7.1) interpreter or debugger (import pdb), you can execute a multi-line statement with the following syntax.
for i in range(5): print("Hello"); print("World"); print(i)
Note: When I'm inside the interpreter, I have to hit return twice before the code will execute. Inside the debugger, however, I only have to hit return once.
There is the special case if you want a couple of commands be executed when hitting a break point. Then there is the debugger command commands. It allows you to enter multiple lines of commands and then end the whole sequence with the end key word. More with (pdb) help commands.
I don't know if you can do this, that'd be a great feature for ipdb though. You can use list comprehensions of course, and execute simple multi-line expressions like:
if y == 3: print y; print y; print y;
You could also write some functions beforehand to do whatever it is you need done that would normally take multiple lines.

Categories

Resources