简体   繁体   中英

function with multiple arguments **args

I am learning python and this is from

http://www.learnpython.org/page/MultipleFunctionArguments

They have an example code that does not work- I am wondering if it is just a typo or if it should not work at all.

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 thinks the output should have been-

The sum is: 6
Result: 1

The error i get is-

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

Is there a way to do what they are trying to do or is the example wrong? Sorry I did look at the python tutorial someone had answered but I don't understand how to fix this.

return is a keyword in python - you can't use it as a variable name. If you change it to something else (eg ret ) it will work fine.

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命令。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM