[英]function with multiple arguments **args
我正在學習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
您可能不應使用“ return
”作為參數名稱,因為它是Python命令。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.