Ok. This IS homework ...

Chris Johnson effigies at gmail.com
Sat Oct 14 23:32:42 EDT 2006


spawn wrote:
> but I've been struggling with this for far too long and I'm about to
> start beating my head against the wall.
>
> My assignment seemed simple: create a program that will cacluate the
> running total of user inputs until it hits 100.  At 100 it should stop.
>  That's not the problem, in fact, that part works.  It's the adding
> that isn't working.  How can my program add 2 + 7 and come up with 14?
>
> I'm posting my code (so that you may all laugh).  If ANYONE has any
> ideas on what I'm doing wrong, I'd appreciate.
>
> ---------------------------------------------------
>
> running = True
> goal = 100
>
> # subtotal = 0
> # running_total = subtotal + guess
>
> while running:
> 	guess = int(raw_input('Enter an integer that I can use to add : '))
> 	subtotal = guess
>
> 	while running:
> 		guess = int(raw_input('I\'ll need another number : '))
> 		running_total = guess +	subtotal
> 		print running_total
>
> 		if running_total == goal:
> 			print 'Congratulations!  You\'re done.'
>
> 		elif running_total > goal:
> 			print 'That\'s a good number, but too high.  Try again.'
>
> print 'Done'

A couple things:
1) I don't understand this looping structure. When the inner one ends,
the outer one will as well, and will never repeat.
2) As to why 2 + 7 gets you 14, subtotal is a shallow copy of guess, so
I speculate that the second assignment to guess doesn't change the
address, but inserts a new value into the old address. The upshot being
that you have guess and subtotal pointing to the same second value. If
I were you I would rewrite that bit as:

guess1 = int(raw_input('Enter an integer that I can use to add : '))
while running:
	guess2 = int(raw_input('I\'ll need another number : '))
	total = guess1 + guess2

(Your original assignments were confusing, using the same variables in
different contexts, and throwing in extra variables for no obvious
reason. This way it is clear what's being done, and it's easy to see
whether what's being done is what you want.)

Reading your description, that's not what you want. You want to
accumulate, so you'll want subtotal to be increasing each time a decent
guess is input. You want to quit when you reach 100, but you never set
running to False.

> --------------------------
>
> I tried adding an additional "while" statement to capture the second
> number, but it didn't seem to solve my problem.  Help!




More information about the Python-list mailing list