Python - Combining keywords and defaults in argument passing

Introduction

The following code demonstrates keywords and defaults.

In the following, the caller must always pass at least two arguments to match test and eggs, but the other two are optional.

If they are omitted, Python assigns toast and ham to the defaults specified in the header:

Demo

def func(test, eggs, toast=0, ham=0):   # First 2 required 
    print((test, eggs, toast, ham)) 

func(1, 2)                              # Output: (1, 2, 0, 0) 
func(1, ham=1, eggs=0)                  # Output: (1, 0, 0, 1) 
func(test=1, eggs=0)                    # Output: (1, 0, 0, 0) 
func(toast=1, eggs=2, test=3)           # Output: (3, 2, 1, 0) 
func(1, 2, 3, 4)                        # Output: (1, 2, 3, 4)
# ww  w  . j a  v  a2s.  c om

Result

Related Topic