Python pass second parameter not first

跟風遠走 提交于 2020-12-16 08:11:22

问题


I have a Python function that is not behaving the way I expect:

def xyz(x=1, y=2):
    print(str(x), str(y))

When I pass in an argument for the second parameter (y), I do not get the output I expect.

xyz(, 5)

I was hoping the output would be something like:

1 5

But instead, Python produces an error.


回答1:


if you have more than one argument with a default value in a function, you should be more specific when you're calling them. for example:

def xyz(z, x=1, y=2):     # z doesn't have a default value
    print(str(x), str(y))

xyz(3, x=5)      # correct
xyz(3, x=5, y=9) # correct
xyz(3, 9, 5)     # correct
xyz(5, 0, y=5)   # correct!
xyz(5, 0, x=5)   # incorrect!
xyz(x=5)         # incorrect!
xyz(3, ,)        # incorrect!

remember you must define non-default value arguments (also called positional arguments) before default value arguments




回答2:


The syntax is wrong. This is how you pass value for a specific parameter.

def xyz(x=1, y=2):
    print(str(x), str(y))

xyz(y=5)


来源:https://stackoverflow.com/questions/48005200/python-pass-second-parameter-not-first

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!