Editor settings

General settings

Save settings

Learn to program with Python

Setting default values for parameters #

You can create a function with default value(s) for its parameter(s) by simply assigning the default value(s) to the parameter(s) in the function definition.

Here's an example:

def greet(name, message="Hello"):
    print(f"{message}, {name}!")

greet("John") # Output: Hello, John!
greet("Alice", "Hi") # Output: Hi, Alice!

In this example, the greet() function takes two parameters: name and message. The message parameter has a default value of "Hello". If the caller doesn't provide a value for message, the default value will be used.

In the first call to greet(), we only pass the name parameter, so the default value of "Hello" is used for the message parameter. In the second call, we provide both name and message parameters, so the provided value for the message is used.

When defining a function with default arguments, optional argument values must be specified after all the regular arguments. For example, when we define a function like the one below, the program will display an error message: SyntaxError: non-default argument follows default argument.
def print_height(unit = "cm", height):
    print(f"You are {height} {unit} tall.")

Exercise #

Create a function with default parameter

Tests #

  • Create a function print_height
  • Function print_height should take 2 parameters:
    • height as a number
    • unit with the default value "cm"
  • print_height(170) should print "You are 170 cm tall."
  • print_height(6, "ft") should print "You are 6 ft tall."
Output will be displayed here