[Tutor] Getting total of a list (newbie)
Danny Yoo
dyoo@hkn.eecs.berkeley.edu
Tue, 11 Sep 2001 11:05:43 -0700 (PDT)
On Tue, 11 Sep 2001 Brmfq@aol.com wrote:
> num = input("Please enter a number:")
> tot = [num]
> while len(tot) < 10:
> nex = input("Please enter another number: ")
> tot.append (nex)
> print 'total of 10 numbers is',
> tot[0]+tot[1]+tot[2]+tot[3]+tot[4]+tot[5]+tot[6]+tot[7]+tot[8]+tot[9]
>
> This works, but it's only for 10 numbers. Could someone please show me
> a better way? Thanks in advance to anyone who replies.
Hello! Have you learned about functions yet? We can write a sumUp()
function that takes in a list, and returns its total:
###
def sumUp(numbers):
total = 0
for n in numbers:
total = total + n
return total
###
What makes this function so useful is that now we can use it for your
program:
###
print 'total of 10 numbers is', sumUp(numbers)
###
for random, gratuitous summations:
###
>>> sumUp(range(10))
45
###
or even for the definitions of other functions:
###
def average(numbers):
return sumUp(numbers) / float(len(numbers))
## float() might be necessary because of possibility
## of integer division (as of Python 2.1.1)
###
Only our sumUp() function has to do this "sum" thing. When we make a
sumUp() function, we can treat the summing of lists as a new tool that we
can fiddle with.
As you can tell, I'm something of a function fanatic. *grin*
If you have more questions, please feel free to ask.