-1

I want to get the sum of all numbers within a list. My code is shown below; however, I am getting an error when I try to run it:

c = [795557,757894,711411,556286,477322,426243,361643,350722]
for c1 in c:
   x = x + c1

I am also trying to divide one number by another. However, the result is always zero:

y=(273591/21247633)*100
GoBusto
  • 4,632
  • 6
  • 28
  • 45
Atul Thakre
  • 502
  • 3
  • 8
  • 24

3 Answers3

2

In the first case, you need to define x before you use it and use c1 instead of c:

x = 0
c=[795557,757894,711411,556286,477322,426243,361643,350722]
for c1 in c:
    x=x+c1
print x

You can try this code online here.


In the second case, you need to use floating point numbers instead of integers:

y=(273591/21247633.0)*100
print y

This is because the result of an integer-integer division in Python 2.x is also an integer. In this case, 273591 ÷ 21247633 = 0.0128763048571 so the result is rounded down to 0.

This has changed in Python 3.x, and you can enable the same behavior in Python 2.x as follows:

from __future__ import division
y=(273591/21247633)*100
print y
GoBusto
  • 4,632
  • 6
  • 28
  • 45
0

You forgot to initialize x to 0 and this statement should be x = x + c1 and not x = x + c

Probably those numbers are used as integers. Using their float value should help.

 y = (float(273591)/21247633)*100
Milind Dumbare
  • 3,104
  • 2
  • 19
  • 32
  • what is the reason for -1? – Milind Dumbare Feb 20 '15 at 11:42
  • It wasn't me, but I'd guess that it's because (A) you only answered half of the question, and (B) You didn't explain *why* your answer works. What you've written in correct, though, and is arguably more explicit than simply adding `.0` on the end of the number. – GoBusto Feb 20 '15 at 11:56
  • I would guess that the the down-vote is due to the fact that you just posted a snippet of corrected code without any explanation what was wrong in the first place. Also, it answers only half of the question. – Adaephon Feb 20 '15 at 11:59
  • The other half I gave in comments ... I will update my answer though. – Milind Dumbare Feb 20 '15 at 12:00
0

If you want to get a sum of numbers in a list, then use sum:

c = [795557,757894,711411,556286,477322,426243,361643,350722]
x = sum(c)

For the second one, int/int returns an int rounded down, so 273591/21247633 returns 0. Convert one (or all) of the numbers to float and it will work as awaited:

y = (273591. / 21247633.) * 100.
eumiro
  • 207,213
  • 34
  • 299
  • 261