[Tutor] Function works one time then subsequently fails

Cameron Simpson cs at zip.com.au
Wed Apr 29 06:27:25 CEST 2015


On 28Apr2015 20:58, Jim Mooney Py3winXP <cybervigilante at gmail.com> wrote:
>This is really puzzling me. I'm parsing a string to do some simple math
>operations and practice tossing functions around. My parser works on the
>first run, then it continually fails on the same input.

[...]
>numbers = []
[...]
>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.
>    """
>    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
[...]

At a first glance numbers is a global. It is reset to [] at program start, but 
never again. So you're appending to it forever. I have not investigated further 
as to how that affects your program's flow.

Cheers,
Cameron Simpson <cs at zip.com.au>

There are two ways of dealing with this problem: one is complicated and
messy, and the other is simple and very elegant. We don't have much time
left, so I'll just show you the complicated and messy way.
- Richard Feynman, 1981


More information about the Tutor mailing list