[Tutor] Function works one time then subsequently fails

Alan Gauld alan.gauld at btinternet.com
Wed Apr 29 10:21:06 CEST 2015


On 29/04/15 04:58, Jim Mooney Py3winXP wrote:

> numbers = []

Note that you chose to make this global.

> def parse_string(math_string):
>      """Input: A math string with a verbal or mathematical operation
>      and two valid numbers to operate on. Extra numbers and operations
>      are ignored. Output: A tuple containing a function corresponding
>      to the operation and the two numbers. Returns None on failure.
>      """

General comment. returning a mixture of None and valid data
is a recipe for confusion later. Its better to fail by
raising an exception, say a ValueError for example,
or even create a bespoke error.

>      operation = None
>      tokens = math_string.split()
>      for token in tokens:
>          if token in operations:
>              operation = operations[token]
>          elif test_number(token) != None:
>              numbers.append(test_number(token))
>          if len(numbers) > 1:
>              break
>      if operation is None or len(numbers) < 2:
>          return None
>      else:
>          return operation, numbers[0], numbers[1]
>
> REPL
>>>> result = parse_string('1 minus 15')
>>>> func, number1, number2 = result
>>>> func(number1, number2)
> -14
>>>> result = parse_string('1 minus 15')
>>>> print(result)
> None

You never empty numbers so it already contains >1 numbers.
Your loop breaks. And operation is None.
So you return None.

That's why raising an error with suitable text would be clearer.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list