Tech With Tim Logo
Go back

Optional Parameters

Optional Parameters

To recall, parameters are input that must be passed to a function or method from the call statement. Unlike many other languages python supports optional parameters. If we setup a parameter to be optional that means we can omit passing it to the function or method in the call statement. To declare an optional parameter we simply set a default value for it when we create it. If we do not pass a value the default value will be used, if we pass a value it will be the value for the parameter.

def myFunc(x=5):
    print(x)

myFunc()    # Prints 5
myFunc(12)  # Prints 12

It is possible to have multiple optional parameters.

def myFunc(x=5, y=6):
    print(x + y)

myFunc()    # Prints 11
myFunc(12)  # Prints 18
myFunc(10,10)  # Prints 20

It is also possible to use a combination or optional and non-optional parameters.

def myFunc(x, y=6):  # Now we must always pass x
    print(x + y)

myFunc(12)  # Prints 18
myFunc(10,10)  # Prints 20
Design & Development by Ibezio Logo