[Tutor] why different result from two similar ways

Oscar Benjamin oscar.j.benjamin at gmail.com
Tue Nov 6 01:38:30 CET 2012


On 30 October 2012 01:36, Frank Pontius <yahufpontius at yahoo.com> wrote:
> Hello,

Hi,

It would be good if you could remove unnecessary debug code before
posting since it makes it harder for others to read your actual code.
Also why is there an empty line between each two lines of code? I
think this makes it much harder to read the code.

>
> I have code that works.  Then tried to move some of it into function
> IncrementAndRebuildInput, then result changes, I no longer have same result
> as when code in function was inline – why?

Because you're not using the result returned by the function.

>
> Function version way below:             (This version does not produce the
> same output (w/numbers incremented by 1)
>
> def IsNum(string):
>
> #    print "IsNum string", string
>
>     for char in string:             #checks string groupings to be all nums
>
>         if not char.isdigit():
>
> #            print "false"
>
>             return False
>
> #    print "true"
>
>     return True

You could always just return string.isdigit() instead of looping over
the characters in the string:

>>> s = '123'
>>> s.isdigit()
True
>>> s = '12r'
>>> s.isdigit()
False


>
>
>
> def IncrementAndRebuildInput(text):
>
>     newtext = text.split()                #makes a list from string input
>
>     print newtext
>
> #               print "Did I print LIST?"
>
>     for index, element in enumerate(newtext):
>
>         if IsNum(element):                  #looks at every list element,
> checks for #
>
>             num = int(element) + 1          #if #, increments it
>
>             print num
>
> #               print "Bkpt8"
>
>             newtext[index] = str(num)
>
>             print newtext
>
>             print "NOWHERE"
>
>         else:
>
>             pass
>
> #                print "bkpt9"
>
>     print newtext                 # contains new list w/#'s incremented by 1
>
>     print "Point6"
>
>     return newtext

Here the function returns the created list of strings.

>
>
> def main():
>
>     text = raw_input("Type something: ")
>
>     print
>
>     if text:
>
>         print text
>
>     else:
>
>         text = "I got 432 when I counted, but Jim got 433 which is a lot for
> only 6 cats, or were there 12 cats?"
>
>         print text                              #string input
>
>     IncrementAndRebuildInput(text)

The function returns a list of strings but you ignore its return
value. You need to do

  text = IncrementAndRebuildInput(text)

to actually capture the output of the function in a variable called text.

>
> #       print "bkpt10"
>
>     print
>
>     print text                        #  **********  Placing previous inline
> code into function changes result – what am I doing wrong?    **********


Oscar


More information about the Tutor mailing list