4 Replies - 4326 Views - Last Post: 25 February 2011 - 07:58 AM Rate Topic: -----

#1 epis   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 16-February 11

adding a number in a list

Posted 16 February 2011 - 01:09 AM

Hello there,
Can you give me an example of how to define a function that sum all the numbers in a list using for loop?

Thanks
Is This A Good Question/Topic? 0
  • +

Replies To: adding a number in a list

#2 Dogstopper   User is offline

  • The Ninjaducky
  • member icon

Reputation: 2972
  • View blog
  • Posts: 11,223
  • Joined: 15-July 08

Re: adding a number in a list

Posted 16 February 2011 - 01:30 AM

In this case, Google was probably the best thing to go to. However, I did your Googling for you. Remember that Python's loop can work like a "foreach" construct in other languages. Say "for each number in the list", "add the numbers"

li = [1,2,3]
sum = 0
for num in list:
    sum += num


Was This Post Helpful? 2
  • +
  • -

#3 epis   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 16-February 11

Re: adding a number in a list

Posted 16 February 2011 - 11:02 PM

View Postepis, on 16 February 2011 - 01:09 AM, said:

Hello there,
Can you give me an example of how to define a function that sum all the numbers in a list using for loop?

Thanks

This is a great Help
Thanks
Was This Post Helpful? 0
  • +
  • -

#4 CheckersW   User is offline

  • D.I.C Head
  • member icon

Reputation: 12
  • View blog
  • Posts: 198
  • Joined: 04-April 09

Re: adding a number in a list

Posted 23 February 2011 - 07:49 PM

Wow just browsing the threads here, and that was a brilliant way of describing it, dogstopper. That's actually fundamentally answered a question I was about to ask. Thanks
Was This Post Helpful? 0
  • +
  • -

#5 atraub   User is offline

  • Pythoneer
  • member icon

Reputation: 829
  • View blog
  • Posts: 2,250
  • Joined: 23-December 08

Re: adding a number in a list

Posted 25 February 2011 - 07:58 AM

just a little side note, sum is a key word in python, so you probably should call it something else.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1