使用for循环通过.txt文件计算一个值,但它只使用.txt文件中的最后一行数据

问题描述 投票:0回答:3

所以我的input.txt文件包含如下数据:

Height   Weight
2        70
1.5      60
1.9      80

......(随后还有几行数字)。

我试图把这些数字,通过一个等式计算BMI,并输出一个新的txt文件,格式为高度,重量,bmi和bmi类(例如2,70,15,不健康)。

这是我提出的代码:

infile = open("input.txt", "r")
for line in infile:
    height = float(elements[0])
    weight = float(elements[1])
    bmi = round(weight/(height*height), 1)
    if bmi < 20:
        category = 'unhealthy'
    elif 20 <= bmi <= 24.99:
        category = 'healthy'
    elif 25 <= bmi <= bmi < 29.99:
        category = 'non optimum'
    elif bmi > 30:
        category = 'obese'
    result = height, weight, bmi, category
    print(result)
infile.close()

但是,当我运行它时,我连续多次获得相同的结果:

1.66, 53.0, 19.2, 'unhealthy'
1.66, 53.0, 19.2, 'unhealthy'
1.66, 53.0, 19.2, 'unhealthy'
...etc...

结果的前两个数字(1.66,53.0)是input.txt文件最后一行的高度和重量。我得到的包含这些数字的输出数量与input.txt文件中找到的数据行数相匹配,因此就像循环遍历input.txt文件的每一行,但输出只使用高度和input.txt文件的最后一行的权重。

有任何想法吗?谢谢

python for-loop
3个回答
0
投票

也许缺少第4行:

elements = line.split()

0
投票

也许你应该尝试这个:

result = height + ',' + weight + ',' + bmi + ',' + category

0
投票

代码是正确的。您只需通过更改读取文件的方式,跳过输入文件的标题(如果它始终采用您提供的格式)。我试过这个并为我工作:

outfile = open("output.txt", "w")
with open("file.txt", "r") as f:
    next(f)
    for line in f:
        elements = line.split()
        height = float(elements[0])
        weight = float(elements[1])
        bmi = round(weight/(height*height), 1)
        if bmi < 20:
            category = 'unhealthy'
        elif 20 <= bmi <= 24.99:
            category = 'healthy'
        elif 25 <= bmi <= bmi < 29.99:
            category = 'non optimum'
        elif bmi > 30:
            category = 'obese'
        result = height, weight, bmi, category
        outfile.write(str(result) + "\n")
        print(result)    
    outfile.close()

并为您在问题中提供的数据获得了这些结果:

(2.0, 70.0, 17.5, 'unhealthy')
(1.5, 60.0, 26.7, 'non optimum')
(1.9, 80.0, 22.2, 'healthy')
© www.soinside.com 2019 - 2024. All rights reserved.