I want the function to return a value when there is an error. I created this sample code, but it has two parameters. How can I make the function parameters optional? Because when I run the code below, my IDE returns an error that the parameters are required.
def test(error, parameter1):
if parameter1 == True:
print("true")
else:
print("false")
array = []
try:
array[0]
except Exception as e:
error = e
return error
value1 = 1
value2 = 2
if value1 == 1:
#I want this to print the error of the function above
print(test(error))
if value2 == 2:
# I want this to pass parameter to the function above
test(parameter1=True)
CodePudding user response:
Optional paramteters are declared with =None
, i.e.:
def test(error=None, parameter1=None):
...
in your function you'll have to check if the parameters are not none, i.e.:
if error is not None:
....
CodePudding user response:
You could set the function parameters some default values so when no parameters are passed, the default values become the values of the variables:
def test(error = None, parameter1 = None):
if parameter1 == True:
print("true")
else:
print("false")
array = []
try:
array[0]
except Exception as e:
error = e
return error
Here None becomes a default value and if a parameter is passed, the value changes from None to the given value.