I have written a function as follows, with optional argument 'b'.
url depends on the existence of b.
def something(a, b=None)
if len(b) >= 1:
url = 'http://www.xyz.com/%sand%s' % (a, b)
else:
url = 'http://www.xyz.com/%s' (a)
This raises an error when b=None
, saying "object of type 'none-type' has no length"
Any ideas how to get around this?
You can define Python function optional arguments by specifying the name of an argument followed by a default value when you declare a function. You can also use the **kwargs method to accept a variable number of arguments in a function.
A type of argument with a default value is a Python optional parameter. A function definition's assignment operator or the Python **kwargs statement can be used to assign an optional argument. Positional and optional arguments are the two sorts of arguments that a Python function can take.
Users can either pass their values or can pretend the function to use theirs default values which are specified. In this way, the user can call the function by either passing those optional parameters or just passing the required parameters. Without using keyword arguments. By using keyword arguments.
So, it is optional during a call. If a value is provided, it will overwrite the default value. Any number of arguments in a function can have a default value. But once we have a default argument, all the arguments to its right must also have default values.
You can try this code:
def something(a, *b):
if len(b) == 0:
print('Equivalent to calling: something(a)')
else:
print('Both a and b variables are present')
You can simply use if b:
- this will require the value to be both not None
and not an empty string/list/whatever.
You can simply change -
def something(a, b=None)
to -
def something(a, b="")
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