Begginers Guide - Exrcise. Help me, plz!
phil hunt
philh at comuno.freeserve.co.uk
Sun Mar 17 10:13:13 EST 2002
On Sat, 16 Mar 2002 23:45:30 +0300, Jeffrey-man <i-have at no.mail> wrote:
>Hello, everybody!
>I'm a newbie and I'm just learning. I know, it's a stupid question, but I
>want to resolve it.
>Learning the Begginers Guide, I found an exercise. It tells me:
>"Write a program that continually reads in numbers from the user and adds
>them together until the sum reaches 100."
>Can anybody help me?
>
> -----
>
>sum_stop = 100
>num = input("Please enter the number: ")
>
>for sum in range(num+num,sum_stop):
> print "Now the sum is", num+num
> sleep(1)
>
>print "The sum is >/= 100!"
>
> -----
>
>Maybe I'm doing something wrong?
Yes. Firstly you are only asking for a number once. You need to
keep asking until the total is >= 100. So:
sum_stop = 100
num = input("Enter number: ")
But that's no good, because the 2nd line needs to keep executing:
sum_stop = 100
while 1:
num = input("Enter number: ")
Now you need to add up the total:
sum_stop = 100
total = 0
while 1:
num = input("Enter number: ")
total = total + num
print "Total so far is %d" % total
But this still doesn't work, because there is no exit from the
loop, so:
sum_stop = 100
total = 0
while 1:
num = input("Enter number: ")
total = total + num
print "Total so far is %d" % total
if total >= sum_stop: break
Which does the job.
--
<"><"><"> Philip Hunt <philh at comuno.freeserve.co.uk> <"><"><">
"I would guess that he really believes whatever is politically
advantageous for him to believe."
-- Alison Brooks, referring to Michael
Portillo, on soc.history.what-if
More information about the Python-list
mailing list