首页 > 解决方案 > Why does my loop only return one answer instead of answers for the entire list?

问题描述

I am trying to do a precourse assignment for lambda School and Loops are giving me the worst headache. I have a 2d list of names with heights and weights. heights were givin in cm so i used a loop to convert it to m. Then to calculate the BMI, I tried running a l;oop but it keeps giving me only the last one. Let me type the code so it makes more sense.

person_data2

[['John', 84.5, 184],
 ['Ryan', 81.8, 177],
 ['Bobby', 86.1, 190],
 ['Pete', 92.2, 188],
 ['Esther', 69.6, 159],
 ['Jane', 72.0, 166],
 ['Samantha', 51.3, 162]]

Changed heights from cm to m using the loop below and it worked

for i, person in enumerate(person_data2):
  person_data2[i][2] = person_data2[i][2] / 100

print(person_data2)

[['John', 84.5, 1.84], 
['Ryan', 81.8, 1.77], 
['Bobby', 86.1, 1.9], 
['Pete', 92.2, 1.88], 
['Esther', 69.6, 1.59], 
['Jane', 72.0, 1.66], 
['Samantha', 51.3, 1.62]]

BMI = weight/(height^2) So I ran this

for i, person in enumerate(person_data2):
  BMI2 = ((person_data2[i][1])/(person_data2[i][2]**2))

print (BMI2)

19.547325102880652

Why does it only run the last nested list BMI ie Samanthas BMI and not the rest? TBH I dont understand loops fully and changing from cm to m was a bit of copy and paste and trial and error. Could someone point me to what I am doing wrong? And if you know any resources I could use to help me get this right, I would appreciate that as well.

标签: pythonloops

解决方案


Welcome to StackOverflow. Your print() is out of your loop, just change your code to this and place your print() in your loop:

for i, person in enumerate(person_data2):
  BMI2 = ((person_data2[i][1])/(person_data2[i][2]**2))
  print (BMI2)

推荐阅读