[Tutor] Now I have a variable-passing problem!
Sun, 14 Oct 2001 12:20:00 +1000
Since I couldn't see anything written by Andrew to show an implementation
method that uses recursion, I thought I'd chuck one in. True, it's better
using a loop but... some people just like recursion :)
> Now I've made the following mess for myself:
> def get_number():
> rawNum=raw_input("Enter a number between 0 and 10,000: ")
> num_int = string.atoi(rawNum)
> if (0 > num_int) or (num_int > 10000):
> print 'Sorry, that number is not between 0 and 10000'
> rawNum = get_number() # lest the value is lost in the wicked
maze of recursion :)
> except ValueError:
> print "Try again. We need an integer between 0 and 10,000"
> return rawNum
> Here's what I don't understand: get_number() is called (function A) and
> assigns a raw input value to rawNum. When rawNum fails the "string.atoi"
> test, the function calls itself again (function B), assinging a new value
> rawNum which does not get passed to the function A when the function B
> terminates. How do I (re)write the code so that function B passes the
> correct value to function A?
Your code looks all well and good, but has a pretty major problem. When
you recursively call get_number you aren't storing the value - something
like 'result = get_number()' is needed. When you do this, you also need to
declare result (again, simple as 'result = None') and modify the return
statement. So, only really one change but the new incarnation would be...
rawNum=raw_input("Enter a number between 0 and 10,000: ")
result = None # don't want an unbound var error...
num_int = int(rawNum)
if (0 > num_int) or (num_int > 10000):
print 'Sorry, that number is not between 0 and 10000'
result = get_number() # lest the value is lost in the wicked
maze of recursion :)
print "Try again. We need an integer between 0 and 10,000"
result = get_number() # ditto
> Should I even bother or just re-write the body of the if-test to re-prompt
> without a recursive call?
It's not too much trouble to correctly recursify it, esp if you've already
built the function.
Anywho, have fun :)