[Tutor] sum of a list

Lloyd Kvam pythonTutor at venix.com
Wed Aug 11 01:48:50 CEST 2004


On Tue, 2004-08-10 at 19:25, jason hochstein wrote:
> I can't figure out or find anywhere how to get the sum of a list??
> Here is what I have so far:
>  
> l_input=[]
>  
> while True:
>     s = raw_input("Type number. Hit enter for more or type quit to
> finish: ")
>  
>    
>     if s == "quit":
>         break
>     else:
>          l_input.append(float(s))
>  
> print "Here is your list of numbers ", l_input
>  
> for i in l_input:
at this point you probably already tried something like
	total = total + i
and got
NameError: name 'total' is not defined

The problem is that total + i can only be computed if total already
exists.  The usual solution is to initialize total to 0.0.

total = 0.0
for i in l_input:
	total = total + i
print total

The latest version of python includes a builtin function called sum that
will compute your total without a loop

total = sum(l_input)



>    
>  
> I am trying to get the sum of all numbers inputed so I can work with
> the the total.
> 
> ______________________________________________________________________
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
-- 

Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-653-8139
fax:	801-459-9582



More information about the Tutor mailing list