Python Optional Arguments

Python provides functions and methods in order to execute tasks easily by just providing some arguments to them. Functions and methods generally require or accept some arguments for the task. As its name suggests the optional argument is simply free to provide or not provide. Generally, the optional argument value is set as a default value, and if not provided the default value is used for the argument. If the argument value is specified the specified value is used for the argument.

Create Function with Required Argument

Regular arguments for the methods and functions should be provided. In the following example, we create function named person() which accepts 3 parameters named name , surname and country .

def person(name,surname,country):
   print(name)
   print(surname)
   print(country)


person("İsmail","Baydan","Turkey")
İsmail
Baydan
Turkey

Create Function with Optional Argument

Let’s make the previously defined function with an optional argument. We change the argument “country” into an optional argument and other arguments “name”, and “surname” stays as required. In order to make an argument optional, we should provide its default value by using the equal sign in the function definition. We make the country valued “Turkey”.

def person(name,surname,country="Turkey"):
   print(name)
   print(surname)
   print(country)


person("İsmail","Baydan")

person("İsmail","Baydan","Germany")
İsmail
Baydan
Turkey
İsmail
Baydan
Germany

Leave a Comment