Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Default values, optional parameters, optional parameters

def prompt(question, retry=3):
    print(question)
    print(retry)
    #while retry > 0:
    #    inp = input('{} ({}): '.format(question, retry))
    #    if inp == 'my secret':
    #        return True
    #    retry -= 1
    #return False

prompt("Type in your password")

prompt("Type in your secret", 1)

prompt("Hello", retry=7)

# prompt(retry=7, "Hello")  # SyntaxError: positional argument follows keyword argument

prompt(retry=42, question="Is it you?")

Output:

Type in your password
3
Type in your secret
1
Hello
7
Is it you?
42

Function parameters can have default values. In such case the parameters are optional. In the function declaration, the parameters with the default values must come last. In the call, the order among these arguments does not matter, and they are optional anyway.