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

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

Related

I'm trying to use imapgrab to imap gmail, but I can't because of the following error. imapgrab error DEBUG_000 [duplicate]

When I try to use a print statement in Python, it gives me this error:
>>> print "Hello, World!"
File "<stdin>", line 1
print "Hello, World!"
^
SyntaxError: Missing parentheses in call to 'print'
What does that mean?
This error message means that you are attempting to use Python 3 to follow an example or run a program that uses the Python 2 print statement:
print "Hello, World!"
The statement above does not work in Python 3. In Python 3 you need to add parentheses around the value to be printed:
print("Hello, World!")
“SyntaxError: Missing parentheses in call to 'print'” is a new error message that was added in Python 3.4.2 primarily to help users that are trying to follow a Python 2 tutorial while running Python 3.
In Python 3, printing values changed from being a distinct statement to being an ordinary function call, so it now needs parentheses:
>>> print("Hello, World!")
Hello, World!
In earlier versions of Python 3, the interpreter just reports a generic syntax error, without providing any useful hints as to what might be going wrong:
>>> print "Hello, World!"
File "<stdin>", line 1
print "Hello, World!"
^
SyntaxError: invalid syntax
As for why print became an ordinary function in Python 3, that didn't relate to the basic form of the statement, but rather to how you did more complicated things like printing multiple items to stderr with a trailing space rather than ending the line.
In Python 2:
>>> import sys
>>> print >> sys.stderr, 1, 2, 3,; print >> sys.stderr, 4, 5, 6
1 2 3 4 5 6
In Python 3:
>>> import sys
>>> print(1, 2, 3, file=sys.stderr, end=" "); print(4, 5, 6, file=sys.stderr)
1 2 3 4 5 6
Starting with the Python 3.6.3 release in September 2017, some error messages related to the Python 2.x print syntax have been updated to recommend their Python 3.x counterparts:
>>> print "Hello!"
File "<stdin>", line 1
print "Hello!"
^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print("Hello!")?
Since the "Missing parentheses in call to print" case is a compile time syntax error and hence has access to the raw source code, it's able to include the full text on the rest of the line in the suggested replacement. However, it doesn't currently try to work out the appropriate quotes to place around that expression (that's not impossible, just sufficiently complicated that it hasn't been done).
The TypeError raised for the right shift operator has also been customised:
>>> print >> sys.stderr
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for >>: 'builtin_function_or_method' and '_io.TextIOWrapper'. Did you mean "print(<message>, file=<output_stream>)"?
Since this error is raised when the code runs, rather than when it is compiled, it doesn't have access to the raw source code, and hence uses meta-variables (<message> and <output_stream>) in the suggested replacement expression instead of whatever the user actually typed. Unlike the syntax error case, it's straightforward to place quotes around the Python expression in the custom right shift error message.
Unfortunately, the old xkcd comic isn't completely up to date anymore.
Since Python 3.0 you have to write:
print("Hello, World!")
And someone has still to write that antigravity library :(
There is a change in syntax from Python 2 to Python 3.
In Python 2,
print "Hello, World!"
will work but in Python 3, use parentheses as
print("Hello, World!")
This is equivalent syntax to Scala and near to Java.
Basically, since Python 3.x you need to use print with parenthesis.
Python 2.x: print "Lord of the Rings"
Python 3.x: print("Lord of the Rings")
Explanation
print was a statement in 2.x, but it's a function in 3.x. Now, there are a number of good reasons for this.
With function format of Python 3.x, more flexibility comes when printing multiple items with comma separated.
You can't use argument splatting with a statement. In 3.x if you have a list of items that you want to print with a separator, you can do this:
>>> items = ['foo', 'bar', 'baz']
>>> print(*items, sep='+')
foo+bar+baz
You can't override a statement. If you want to change the behavior of print, you can do that when it's a function but not when it's a statement.
If your code should work in both Python 2 and 3, you can achieve this by loading this at the beginning of your program:
from __future__ import print_function # If code has to work in Python 2 and 3!
Then you can print in the Python 3 way:
print("python")
If you want to print something without creating a new line - you can do this:
for number in range(0, 10):
print(number, end=', ')
In Python 3, you can only print as:
print("STRING")
But in Python 2, the parentheses are not necessary.
I could also just add that I knew everything about the syntax change between Python2.7 and Python3, and my code was correctly written as print("string") and even
print(f"string")...
But after some time of debugging I realized that my bash script was calling python like:
python file_name.py
which had the effect of calling my python script by default using python2.7 which gave the error. So I changed my bash script to:
python3 file_name.py
which of coarse uses python3 to run the script which fixed the error.
print('Hello, World!')
You're using python 3, where you need brackets when printing.
Outside of the direct answers here, one should note the other key difference between python 2 and 3. The official python wiki goes into almost all of the major differences and focuses on when you should use either of the versions. This blog post also does a fine job of explaining the current python universe and the somehow unsolved puzzle of moving to python 3.
As far as I can tell, you are beginning to learn the python language. You should consider the aforementioned articles before you continue down the python 3 route. Not only will you have to change some of your syntax, you will also need to think about which packages will be available to you (an advantage of python 2) and potential optimizations that could be made in your code (an advantage of python 3).
So I was getting this error
from trp import BoundingBox, Document
File "C:\Users\Kshitij Agarwal\AppData\Roaming\Python\Python39\site-packages\trp\__init__.py", line 31
print ip
^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print(ip)?
This is a Python package error, in which Python2 has been used and you are probably running this on Python3.
One solution could be to convert Python2 print something to Python3 print(something) for every line in each file in the package folder, which is not a good idea😅. I mean, you can do it but still there are better ways.
To perform the same task, there is a package named 2to3 in Python which converts Python2 scripts to Python3 scripts. To install it, execute the 👇 command in terminal..
pip install 2to3
Then change the directory in terminal to the location where the package files are present, in my case - C:\Users\Kshitij Agarwal\AppData\Roaming\Python\Python39\site-packages\trp
Now execute the command 👇
2to3 . -w
and voila, all the Python2 files in that directory will be converted to Python3.
Note:- The above commands hold true for other operating systems as well. Only Python package path will vary as per the system.
print "text" is not the way of printing text in python as this won't work
print("text") will print said text on your screen in the command line

Syntax error when defining a function on the Python command line

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.

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

Evaluation missing in SublimeREPL Python

I'm trying to get SublimeREPL to work with Python. However, whenever I send a Python command to the REPL with the keyboard shortcut, only output from stdout is displayed. The evaluation of the command should also be displayed, but isn't. Here is a succinct example, copy and pasted from the output in the REPL after sending the commands to the REPL from Python source via the keyboard shortcut.
>>> print 'This will print out'
This will print out
>>> 'But this will not'
>>> 1+1
I would have expected the following output (running manually from BASH terminal in Python produces this):
>>> print 'This will print out'
This will print out
>>> 'But this will not'
'But this will not'
>>> 1+1
2
One last note, manually typing commands directly into the Sublime Text REPL produces the desired output, but is much slower and inconvenient.
I'm running this using SublimeText3 with the default Python 2.7.5 interpreter on Ubuntu 13.10.
This is happening because the REPL is actually evaluating your code in the exact same manner that it would if you put all those commands in a file and ran it from the command line - it is not behaving as an interactive interpreter in this case.
If you want the REPL to behave more like IDLE, for example, you need to transfer your code to it, then switch over and run it from there, simply by adding Shift to your key sequence. So, if previously you were using Ctrl,, S to evaluate a selection, just use CtrlShift,, S instead to transfer your selection to the REPL. Switch tabs and hit Enter, and it should behave as you are expecting.

What do the three arrow (">>>") signs mean?

I haven't been able to figure out what the >>> does, even though I often see it often in source code.
You won't see it in source code, it's probably documentation. It indicates an interactive session, and things typed into the 'interpreter' are marked with this. Output is shown without the arrows.
In fact, the python documentation often has a button >>>at the top right of example code to be able to hide the arrows (and output) so that you can copy and paste the code.
Shown:
Hidden:
'>>>' is the prompt of the interactive Python interpreter, meaning that the interpreter is ready to get Python statements typed in. It's occuring quite often in examples within the documentation of a Python program, in order to show which commands can be used and what will be the result of giving these commands to the interactive interpreter. For example, in a documentation of the print statement, one could give this example:
>>> print "Hello world."
Hello world.
This would be an actual snippet of a session with the interactive Python interpreter.
An interesting feature in IPython is that it ignores leading >>>, meaning that you can copy and paste code from such documentation without needing to remove the leading >>>:
In [1]: >>> print "Hello world."
Hello world.
(The prompt in IPython is In [n]:, where n is counting the interactive commands issued.)
Here are some of my findings on >>> and consequently ... complementing the previous answers.
You only see >>> when you are running Python in interactive mode prompting/asking the user for the "next command". Technical details here.
>>> and ... are not written in stone. These are stored in sys.ps1 and sys.ps2, and therefore can be changed. Further elaborated here.
>>> import sys
>>> sys.ps1 = "$ "
$
Every standard Python has this prompt unless you compile your own Python after changing >>> and ... to what you (sanely) wish to. Apart from that there seems to be a way to change it for all future interactive sessions by changing /usr/lib/python2.7/code.py but I couldn't find any success with it.
The >>> prompt is the Python interpreter’s way of asking you, “What do you want
me to do next?”, and it is called "chevron" prompt
In case you are trying to figure out how to exit a session, run this:
quit()
I found it to be called ' REPL'

Categories

Resources