[Courses] need a little help with extremly basic python programming

Mary mary-linuxchix at puzzling.org
Thu Dec 5 18:56:18 EST 2002


Hi,

I've Cc-ed the programming list, since this post isn't part of a course
it would probably be better off there.

On Thu, Dec 05, 2002, Guru - wrote:
> "Exercise 1
> Write a program that continually reads in numbers from the user and adds 
> them together until the sum reaches 100. Write another program that reads 
> 100 numbers from the user and prints out the sum. "
> I know that it's to do with loops but I wasn't sure how to do it...

OK, if you were going to break this up into actual steps:

ask user for a number
read the number
add the number to the sum
check if the sum is bigger than 100, if it is stop
ask user for a number
read the number
add the number to the sum
check if the sum is bigger than 100, if it is stop
ask user for a number
read the number
add the number to the sum
check if the sum is bigger than 100, if it is stop
ask user for a number
read the number
add the number to the sum
check if the sum is bigger than 100, if it is stop

and so on...

OK, so, there's an obvious compression:

BEGIN:
ask user for a number
read the number
add the number to the sum
check if the sum is bigger than 100, if it is stop, otherwise go back to
BEGIN

This compression is the typical use of a loop: if you're going to repeat
the same action over and over, you use a loop.

So, we need to repeat an action until a condition is met. In Python, a
loop that continues running until a condition is met is a while loop. We
need to change the order of instructions for a while loop, and the
condition for a while loop is the condition for staying in the loop:

if the sum is still smaller than 100, do this:

ask user for a number
read the number
add the number to the sum

or, using the word while, and getting closer to Python code:

while the sum is less than 100 do this:

ask the user for a number
read the number X
set the value of sum to be the old value of sum plus X

Finally, the very first time the code runs, Python needs to know the old
value of sum, otherwise "set the value of sum to be the old value of sum
plus X" won't work.

So:

set sum to be 0

while the sum is less than 100 do this:

ask the user for a number
read the number X
set the value of sum to be the old value of sum plus X

Hopefully this makes while loops a bit clearer, now you just need to
translate the above into Python.

-Mary



More information about the Courses mailing list