Begginers Guide - Exrcise. Help me, plz!
Bengt Richter
bokr at oz.net
Fri Mar 22 18:15:24 EST 2002
On Fri, 22 Mar 2002 10:38:22 -0800, Jeff Shannon <jeff at ccvcorp.com> wrote:
>
>
>Jim Dennis wrote:
>
>> Shouldn't all these (helpful) examples be using raw_input() rather
>> than input(). Do we really want the new user to be implicitly and
>> blindly using eval(raw_input())?
>
>Yes, they should. :) The calls to input() should, in this case, all be
>replaced by int(raw_input()), and optionally wrapped in a try/except and while
>loop, so that the program can prompt again if a non-numeric value is given. I
>almost mentioned this in my earlier response, but decided not to overly confuse
>the O.P. -- this essentially doubles the code size.
>
>while sum < sum_stop:
> num = None
> while num is None:
> try:
> num = int(raw_input("Please enter the number:"))
> except ValueError:
> print "That's not a number. Try again!"
> sum = sum + num # could also be sum += num
> print "The sum is", sum
>print "and it is > 100"
>
>Alternatively, instead of setting num to None and watching for that to change,
>we could use a 'while 1: try: ... except: ... else: break' structure.
>
Alternatively again, we could factor out the function of getting a number, to
keep that concept bite sized (and also changing a few details ;-) e.g.:
---<snip>---
def get_num():
while 1:
try:
return int(raw_input("Please enter an integer: "))
except ValueError:
print "That's not a integer. Try again!"
sum = 0; sum_stop = 100
while sum < sum_stop:
sum += get_num()
print "The sum is", sum
print "... and it is >= %d" % sum_stop
---<snip>---
Please enter an integer: 2.
That's not a integer. Try again!
Please enter an integer: 2
The sum is 2
Please enter an integer: -5
The sum is -3
Please enter an integer: 99
The sum is 96
Please enter an integer: 3
The sum is 99
Please enter an integer: 1
The sum is 100
... and it is >= 100
Regards,
Bengt Richter
More information about the Python-list
mailing list