蟒蛇|重复增加要素

时间:2017-10-04 00:14:37

标签: python loops for-loop

例如,水(H2O)的分子量为:2(1.00794)+ 15.9994 = 18 代码:

formula = int(input("Enter the number of elements: "))
for i in range(formula):
    element = input("enter your element: ")
    molCount = float(input("enter the molecule count: "))
    print(molCount)
    atomWeight = float(input("enter the atomic weight: "))
    print(atomWeight)
    total = molCount*atomWeight
print(total)
total = total + total
print(total)

需要帮助才能将多个元素添加到一起......

2 个答案:

答案 0 :(得分:0)

线路上有一个错误: total = molCount*atomWeight

你的意思可能是total += molCount*atomWeight

答案 1 :(得分:0)

首先,在for循环之前定义total。其次,我认为你的等式需要

total += (molCount * atomWeight)

而不是原件。编辑代码:

formula = int(input("Enter the number of elements: "))
total = 0
for i in range(formula):
    molCount = int(input("Enter the molecule count: "))
    print("Molecule count: " + str(molCount))
    atomWeight = float(input("Enter the atomic weight: "))
    print("Atomic Weight: " + str(atomWeight))
    total += (molCount * atomWeight)
print(total)