Newbie confusion about 'return'

Aahz Maruch aahz at panix.com
Fri Mar 16 19:16:25 EST 2001


In article <3AB2A2BE.A467DE00 at hotmail.com>, scott  <smarsh at hotmail.com> wrote:
>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.

That's because IDLE itself is a Python program that captures the output
of return.  Try entering *any* Python expression, and its output will be
printed.  You don't want that in a regular program, though, so you need
to be explicit:

>
>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")

Try

print find ("abcde", "d")
-- 
                      --- Aahz  <*>  (Copyright 2001 by aahz at pobox.com)

Androgynous poly kinky vanilla queer het Pythonista   http://www.rahul.net/aahz/
Hugs and backrubs -- I break Rule 6

Three sins: BJ, B&J, B&J



More information about the Python-list mailing list