ask_ok('Howdy?', 5) a valid function call?
def ask_ok(prompt, retries=4, reminder=’Repeat!’):
ok = input(prompt)
if ok in (‘y’, ‘ye’, ‘yes’):
if ok in (‘n’, ‘no’, ‘nop’, ‘nope’):
retries = retries – 1
if retries < 0:
raise ValueError(‘invalid user response’)
This puzzle introduces the concept of default arguments in Python.
Suppose, you have created a Python command line tool for your business. The tool requires user confirmation for different activities like writing or deleting files.
To avoid redundant code, you have implemented a generic function that handles the interaction with the user. The default behavior should consist of three steps. (1) You ask (prompt) the user a question. (2) The user puts in some response. (3) As long as the response is invalid, the function repeats up to four times–each time printing a reminder ‘Repeat!’. The number of repetitions and the reminder should be customizable via the parameters.
To achieve this, you can specify default arguments as given in the puzzle. You can use the default parameters by calling
ask_ok('Hi?'). Or you can overwrite them in the order of their definition (one, several, or all parameters).
It is interesting that only 50% of all finxter users solve this puzzle: they seem to guess the answer. Partial replacement of default arguments is a new feature to most of the users. Is it new to you?
Mastering these basic language features will lift you to the level of an advanced coder.
Are you a master coder?
Test your skills now!