Python Skipping a Parameter in a Function

Viewed 246

Beginner Here and I just want to know how to skip a parameter in python for example

def function(a, b):
    pass

function(5)

I want to only assign 5 to b. How can I do it?

2 Answers

You can do this:

def function(a=None, b=None):
    pass

function(b=5)

This makes the values that don't get assigned None (in this case a is gonna be None).

If you don't add =None to the two parameters, it will throw an error because I didn't assign anything to a.

If in the last line you don't say b=5 and instead say just 5, it will think that is for the a parameter since the a parameter is before the b parameter in the parenthesis.

Simply, You can set a default value to a in that case.

def function(b,a=None):
pass

function(5)

Please note that the default parameters are supposed to follow the non-defualt ones.

Related