Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

How to pass optional parameters to a function in Python?

In the given code

def greet(name, msg = "Good morning!", msg2="Come on in"):
   """
   This function greets the person with given message.
   If message is not given, it defaults to "Good
   morning!"
   """
   print("Hello",name + ', ' + msg + ' '+ msg2)
greet("Archie")
greet("Richie","How do you do?")

What are optional arguments in the python function?


1 Answer
Rajendra Dharmkar

Python allows function arguments to have default values; if the function is called without the argument, the argument gets its default value. Furthermore, arguments can be specified in any order by using named arguments.

For the given code

OUTPUT

('Hello', 'Archie, Good morning! Come on in')
('Hello', 'Richie, How do you do? Come on in')

Messages msg and msg2 are optional, because they have default values defined. name is a required argument, because it has no default value. If greet is called with only one argument, msg defaults to “Good Morning” and msg2 defaults to “Come on in”. If greet is called with two arguments, msg2 still defaults to “Come on in”.

In most languages, we would need to call the function with three arguments. But in Python, arguments can be specified by name, in any order.

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.