我正在学习python,这是来自
http://www.learnpython.org/page/MultipleFunctionArguments
他们有一个不起作用的示例代码 - 我想知道它是否只是一个拼写错误或者它是否根本不应该起作用。
def bar(first, second, third, **options):
if options.get("action") == "sum":
print "The sum is: %d" % (first + second + third)
if options.get("return") == "first":
return first
result = bar(1, 2, 3, action = "sum", return = "first")
print "Result: %d" % result
Learnpython 认为输出应该是-
The sum is: 6
Result: 1
我得到的错误是-
Traceback (most recent call last):
File "/base/data/home/apps/s~learnpythonjail/1.354953192642593048/main.py", line 99, in post
exec(cmd, safe_globals)
File "<string>", line 9
result = bar(1, 2, 3, action = "sum", return = "first")
^
SyntaxError: invalid syntax
有没有办法做他们想做的事情,或者这个例子是错误的?抱歉,我确实看过有人回答过的 python 教程,但我不明白如何解决这个问题。
请您参考如下方法:
return 是 python 中的关键字 - 您不能将其用作变量名。如果您将其更改为其他内容(例如 ret),它将正常工作。
def bar(first, second, third, **options):
if options.get("action") == "sum":
print "The sum is: %d" % (first + second + third)
if options.get("ret") == "first":
return first
result = bar(1, 2, 3, action = "sum", ret = "first")
print "Result: %d" % result
