Newbie confusion about 'return'

scott smarsh at hotmail.com
Fri Mar 16 18:33:01 EST 2001


I'm mystified. The same code in IDLE (or at the interactive prompt)
gives a different result compared to entering it into a file and running
it. I'm using Python 2.0 from python .org on NT4. I checked on Solaris 8
with python 2.0 (interactive vs running the file) and got the same
result. The code is from "How to think like a computer scientist Chapter
7"
-----------------------------------
IDLE:

>>> def find(str, ch):
              index = 0
              while index < len(str):
                      if str[index] == ch:
                             return index
                      index = index + 1
              return -1

>>> find ("abcde", "d")
3 (in blue indicating stdout)

The above is what I expected.
------------------------------------

Running python on the file (find.py):

def find(str, ch):
      index = 0
      while index < len(str):
             if str[index] == ch:
                    return index
             index = index + 1
      return -1

find ("abcde", "d")

I ran it as: $ python find.py
*Nothing* was returned (just gave me the command prompt again), instead
of the '3' that I expected.
---------------------------------------

Why the difference? I thought one of the points of the interactive mode
was to test code to see if it works before putting it in a file...
If I add a couple of print statements in the file, I get the expected
result (3) from running 'python find.py':

def find(str, ch):
      index = 0
      while index < len(str):
             if str[index] == ch:
                   print index
                   return
             index = index + 1
      print -1
      return

find ("abcde", "d")

Thanks in advance.





More information about the Python-list mailing list