[Tutor] Step Value

Steven D'Aprano steve at pearwood.info
Fri Jun 17 02:55:45 CEST 2011


Vincent Balmori wrote:

> Okay, I think I understand it better for the quesiton:
> "Improve the function ask_number() so that the function can be called with a step value. Make the default value of step 1." Here is the improved function and the human_move function that calls it later on. The thing I am unaware of doing is making the step value 'optional rather than required' though.

You're almost there.

> def ask_number(question, low, high, step):
>     """Ask for a number within a range."""
>     step = 1

The line above is inappropriate, because it over-writes the value of 
step that the caller provides. If you call

ask_number(question, 1, 100, 5)

the line step=1 throws away the value 5 and replaces it with 1. Get rid 
of that line altogether, you don't want it.

The last change that needs to be made is to give step a default value. 
The way to do that is to put it in the function parameters. He's an example:

def spam(n=3):
     """Return n slices of yummy spam."""
     return "spam "*n

And here it is in use:

 >>> spam(4)
'spam spam spam spam '
 >>> spam()  # just use the default
'spam spam spam '

Can you see what I did to set the default value for n? Read the function 
definition line "def spam... " carefully.



-- 
Steven


More information about the Tutor mailing list