我正在学习python,这是来自
http://www.learnpython.org/page/MultipleFunctionArguments
Run Code Online (Sandbox Code Playgroud)
他们有一个不起作用的示例代码 - 我想知道它是否只是一个错字或者根本不应该工作.
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
Run Code Online (Sandbox Code Playgroud)
Learnpython认为输出应该是 -
The sum is: 6
Result: 1
Run Code Online (Sandbox Code Playgroud)
我得到的错误是 -
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
Run Code Online (Sandbox Code Playgroud)
有没有办法做他们想要做的事情或者示例错了?对不起,我确实看过有人回答的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
Run Code Online (Sandbox Code Playgroud)