Newbie confusion about 'return'
Bruce Sass
bsass at freenet.edmonton.ab.ca
Fri Mar 16 19:13:43 EST 2001
On Fri, 16 Mar 2001, scott wrote:
<...>
> IDLE:
<...>
> >>> find ("abcde", "d")
> 3 (in blue indicating stdout)
>
> The above is what I expected.
> ------------------------------------
>
> Running python on the file (find.py):
<...>
> 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':
The interactive interpreter displays the value of the line when you
hit ENTER, a program will not produce output unless you ask for it
(errors excepted, of course).
> 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")
or do this...
---8< find.py ---
def find(str, ch):
index = 0
while index < len(str):
if str[index] == ch:
return index
index = index + 1
return -1
print find("abcde", 'd')
--->8---
i.e., what you had for the second piece of code, except print out
the returned value.
- Bruce
More information about the Python-list
mailing list