JuanB457
JuanB457

Reputation: 107

Python 2.7.5, getting sum of an array/ list, proper use of len and output result

Working on moving code from a flowchart tool to python, loaded an array with 3 student ages, and want to get the sum of the 3 ages, I'm new to python and want to know how it is you do this, I get an error running what I have, here is my code so far:

#g is my index, sample input was: 35,25,50 
st_age = [0]*3 
for g in range(0,3):
    st_age[g] = int(input("Enter student age "))

g = 1
sum = 0 
while g < len(st_age): #am I using this correctly? 
    sum = sum + st_age[g]
    g + g + 1

print sum #I get a zero this way. 

thank you for the assist, arrays have been tricky so far.

Upvotes: 0

Views: 916

Answers (1)

Hyperboreus
Hyperboreus

Reputation: 32459

You are not incrementing g. g + g + 1 shoudl read g = g + 1.

Also indices in python are 0-based, hence your starting value should be g = 0.

Also python has a neat builtin sum.

print sum(st_age)

So your fixed code could read:

st_age = [0]*3 
for g in range(3):
    st_age[g] = int(input("Enter student age "))

g = sum = 0 
while g < len(st_age): #am I using this correctly? 
    sum = sum + st_age[g]
    g += 1

print sum

Or with a list comprehension and builtin sum:

st_age = [int(input("Enter student age ")) for _ in range(3) ]
print (sum(st_age)) #Note extra parentheses

I put in the extra parentheses, so your code will run fine in both python 2 and 3.

Upvotes: 1

Related Questions