问题
So I made a function, and wanted to add annotations to it, and the compiler keeps giving me an error:
def square_root(x:number, eps:number) -> float:
pass
And the compiler returns this:
File "/Users/albertcalzaretto/Google Drive/CSC148H1/e1/e1a.py", line 1
def square_root(x, eps) -> float:
^
SyntaxError: invalid syntax
I've never used function annotations, and I've read several sources about it, and I don't think what I'm doing is wrong.
回答1:
Two things:
You must be using Python 2.x somehow. Function annotations are only supported in Python 3.x. If you try to use them in Python 2.x, you will get a
SyntaxError
:>>> def f() -> int: File "<stdin>", line 1 def f() -> int: ^ SyntaxError: invalid syntax >>>
If
number
is undefined (which I believe it is), then you need to make it a string so that you don't get aNameError
. Below is a demonstration:>>> def square_root(x:number, eps:number) -> float: ... pass ... Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'number' is not defined >>> >>> def square_root(x:'number', eps:'number') -> float: ... pass ... >>>
来源:https://stackoverflow.com/questions/21170521/function-annotations-giving-error-in-python