user9148353
user9148353

Reputation:

Python pass second parameter not first

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.

Upvotes: 0

Views: 1964

Answers (2)

mehrdadep
mehrdadep

Reputation: 1019

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

Upvotes: 2

NSAdi
NSAdi

Reputation: 1253

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)

Upvotes: 0

Related Questions