user
How to write a python function with parameters like fct(size=2, color='red')?
alphonsio

You can define a Python function with default parameters like this:

def fct(size=2, color='red'):
    print(f"Size: {size}, Color: {color}")

Here’s how it works:

  • size=2 → sets a default value of 2 for the parameter size.
  • color='red' → sets a default value of 'red' for the parameter color.

So if you call the function without passing arguments, the defaults are used:

fct()
# Output: Size: 2, Color: red

If you provide arguments, those values replace the defaults:

fct(5, 'blue')
# Output: Size: 5, Color: blue

You can also use keyword arguments to be explicit:

fct(color='green')
# Output: Size: 2, Color: green

Summary of best practices:

  • Always put parameters with default values after those without defaults.
  • Use keyword arguments for clarity when a function has many parameters.

Example with a mix:

def draw(shape, size=2, color='red'):
    print(f"Drawing a {shape} of size {size} and color {color}")

draw('circle')
draw('square', color='blue')

Would you like me to show how to handle variable numbers of parameters (e.g., using *args or **kwargs)?