Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help with Code!
#5
(Nov-14-2019, 04:26 AM)Than999 Wrote: My question is how do I iteratively sum up all my numbers in a list, without the use of the special function sum()

Just iterate over items in list and add to total (sum means adding all items; do you want sum only positive values?):

>>> nums = [11.5, 28.3, 23.5, -4.8, 15.9, -63.1, 79.4, 80.0, 0, 67.4, -11.9, 32.6]         
>>> total = 0                                                                              
>>> for num in nums: 
...    total += num 
...                                                                                        
>>> total                                                                                  
258.8
NB! Never use sum as variable name. You overwrite built-in function and it will come and 'bite you when you least expect'

EDIT: for only positive numbers value checking must be added:

>>> nums = [11.5, 28.3, 23.5, -4.8, 15.9, -63.1, 79.4, 80.0, 0, 67.4, -11.9, 32.6]         
>>> total = 0                                                                              
>>> for num in nums:
...     if 0 <= num:     
...         total += num 
...                                                                                        
>>> total
338.6 
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Messages In This Thread
Help with Code! - by Than999 - Nov-14-2019, 04:26 AM
RE: Help with Code! - by ThomasL - Nov-14-2019, 06:10 AM
RE: Help with Code! - by Than999 - Nov-14-2019, 07:55 PM
RE: Help with Code! - by jefsummers - Nov-14-2019, 11:47 PM
RE: Help with Code! - by perfringo - Nov-15-2019, 12:20 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020