[Tutor] Now I have a variable-passing problem!
Andrew Wilkins
toodles@yifan.net
Sun, 14 Oct 2001 00:35:23 +0800
Heya Chris,
*changes order of your message*
> Should I even bother or just re-write the body of the if-test to re-prompt
> without a recursive call?
IMHO the recursive calls aren't very useful here. Here's how I'd have it
written:
(Note that you can use int('123') to convert from a string to an integer.
I'm not sure which version of Python that was introduced in, but it can
easily be changed back to string.atoi().)
def get_number():
while 1:
rawNum=raw_input("Enter a number between 0 and 10,000: ")
try:
num_int=int(rawNum)
if not (num_int<0 or num_int>10000):
return num_int
else: print 'Sorry, that number is not between 0 and
10,000'
except ValueError:
print 'Try again. We need an integer between 0 and
10,000'
>>> get_number()
Enter a number between 0 and 10,000: a
Try again. We need an integer between 0 and 10,000
Enter a number between 0 and 10,000: 50
50
HTH
Andrew
> Thanks again to all who helped me with my list/iteration question.
>
> Now I've made the following mess for myself:
>
>
> def get_number():
> rawNum=raw_input("Enter a number between 0 and 10,000: ")
>
> try:
> num_int = string.atoi(rawNum)
> if (0 > num_int) or (num_int > 10000):
> print 'Sorry, that number is not between 0 and 10000'
> get_number()
>
>
> except ValueError:
> print "Try again. We need an integer between 0 and 10,000"
> get_number()
>
> return rawNum
>
> >>Enter a number between 0 and 10,000: a
> >>Try again. We need an integer between 0 and 10,000
> >>Enter a number between 0 and 10,000: 50
>
> Which, when I try to unit-test by entering a letter instead of an integer,
> gives me the following.
>
> Traceback (innermost last):
> File "./6-8.py", line 127, in ?
> pretty=give_me_english(list)
> File "./6-8.py", line 114, in give_me_english
> ones = string.atoi(digit_list[0])
> ValueError: invalid literal for atoi(): a
>
>
> 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
to
> 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?
>
>
> - Chris
>
> _______________________________________________
> Tutor maillist - Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>