[Tutor] General design question

Kent Johnson kent37 at tds.net
Wed Jul 2 12:50:19 CEST 2008


On Wed, Jul 2, 2008 at 5:54 AM, Tim Golden <mail at timgolden.me.uk> wrote:
> Paul Melvin wrote:
>>
>> If I have a set of numbers, or strings etc. which have been generated and
>> I then want to do something with them, for example a sum function call.  Is
>> the best way to put those items in a list, or similar container, before
>> applying the function.

Putting them in a list is one way, sometimes you can just handle them
as they are generated.

> If you're getting a user to enter them (say) by raw_input, you'll
> need to create your own list:
>
> <code>
>
> nums = []
> while True:
>  snum = raw_input ("Enter number (0 to finish): ")
>  num = int (snum)
>  if num == 0:
>   break
>  else:
>   nums.append (num)
>
> print nums, "->", sum (nums)
>
> </code>

Or add each number to a running total within the loop:

total = 0
while True:
 snum = raw_input ("Enter number (0 to finish): ")
 num = int (snum)
 if num == 0:
  break
 else:
  total += num

print nums, "->", total

Kent


More information about the Tutor mailing list