How to convert list to int
Question:
I am trying to write a code to calculate the average of the height of the student
that is my code
height = input("what is your higthn").split()
for n in range(0, len(height)):
height[n] = int(height[n])
print(height)
t = 0
for i in height:
t += height
print(height)
and I have error
t += higths
TypeError: unsupported operand type(s) for +=: 'int' and 'list'
Answers:
Use enumerate
on the for loop to access to the list indexes and convert it to int
.
Then calculate the sum divided by the len of the list.
height = input("what is your higthn").split()
for i, element in enumerate(height) :
height[i] = int(element)
# Average
print(sum(height)/len(height))
height = [ int(h) for h in input("what's your heightsn").strip("[]").replace(","," ").split()]
print(sum(height) / len(height))
Demo:
what's your heights
1 2 3 4 5 6
3.5
what's your heights
[1, 2 ,3,4 5 6]
3.5
I am trying to write a code to calculate the average of the height of the student
that is my code
height = input("what is your higthn").split()
for n in range(0, len(height)):
height[n] = int(height[n])
print(height)
t = 0
for i in height:
t += height
print(height)
and I have error
t += higths
TypeError: unsupported operand type(s) for +=: 'int' and 'list'
Use enumerate
on the for loop to access to the list indexes and convert it to int
.
Then calculate the sum divided by the len of the list.
height = input("what is your higthn").split()
for i, element in enumerate(height) :
height[i] = int(element)
# Average
print(sum(height)/len(height))
height = [ int(h) for h in input("what's your heightsn").strip("[]").replace(","," ").split()]
print(sum(height) / len(height))
Demo:
what's your heights
1 2 3 4 5 6
3.5
what's your heights
[1, 2 ,3,4 5 6]
3.5