So, I have this pretty simple function (I'm a novice still).
And it goes like:
def add_num(x,y,z=None):
if z == None:
return x+y
else:
return x+y+z
print(add_num(1,2))
print(add_num(1,2,3))
So my question is, when I notice that if there is no third variable, then it is accepted. So does "None" mean basically mean that it is ok to have no value attached to a variable if "variable=None." Just confirming! Thanks!
So does "None" mean basically mean that it is ok to have no value attached to a variable if "variable=None." Just confirming! Thanks!
No. When you define a function like this:
def add_num(x,y,z=None):
x and y are "positional" arguments, and they are required, while z is a keyword argument. Keyword arguments have default values that will be used if you don't provide one when you call the function. Instead of None, you could just as easily have written:
def add_num(x,y,z=0):
Or:
def add_num(x,y,z=5):
Etc. In either case, you are setting a default value for z if it is not provided in the function call.
Note that if you have multiple keyword arguments, like this:
def do_something(x, y, size='medium', name=None):
That you can provide them with values as positional arguments, in which case the arguments need to be in the matching order:
do_something(1,2, 'large', 'alice')
But you can also specify keyword arguments in an arbitrary order by providing their name in the function call, like this:
do_something(1, 2, name='alice', size='large)
And you don't need to provide values if you are happy with the default:
do_something(1, 2, name='alice')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With