我正試圖製作一個程序,以克每摩爾爲一個化合物的質量。應該很簡單,但我的for循環之一不是像它應該運行(對於範圍內的x(0,var-1))。它不是從0到var-1的整數運行,而是將x保持爲0.是否有人可以看看?非常感謝!Python For Loop不被感知?
代碼如下:
#Set all elements and their mass per mole (up to Xenon)
elements = [['H' , 1.0079] , ['He' , 4.0026] , ['Li' , 6.941] , ['Be' , 9.0122] , ['B' , 10.811] , ['C' , 12.011] , ['N' , 14.007] , ['O' , 15.999] , ['F' , 18.998] , ['Ne' , 20.180] , ['Na' , 22.990] , ['Mg' , 24.305] , ['Al' , 26.982] , ['Si' , 28.086] , ['P' , 30.974] , ['S' , 32.066] , ['Cl' , 35.453] , ['Ar' , 39.948] , ['K' , 39.098] , ['Ca' , 40.078] , ['Sc' , 44.956] , ['Ti' , 47.88] , ['V' , 50.942] , ['Cr' , 51.996] , ['Mn' , 54.938] , ['Fe' , 55.847] , ['Co' , 58.933] , ['Ni' , 58.693] , ['Cu' , 63.546] , ['Zn' , 65.39] , ['Ga' , 69.723] , ['Ge' , 72.61] , ['As' , 74.922] , ['Se' , 78.96] , ['Br' , 79.904] , ['Kr' , 83.80] , ['Rb' , 85.468] , ['Sr' , 87.62] , ['Y' , 88.906] , ['Zr' , 91.224] , ['Nb' , 92.906] , ['Mo' , 95.94] , ['Tc' , 97.907] , ['Ru' , 101.07] , ['Rh' , 102.91] , ['Pd' , 106.42] , ['Ag' , 107.87] , ['Cd' , 112.41] , ['In' , 114.82] , ['Sn' , 118.71] , ['Sb' , 121.76] , ['Te' , 127.60] , ['I' , 126.90] , ['Xe' , 131.29]]
#Start the main loop
while True:
grams = 0
numOfDistElements = int(input("How many distinct elements?\n"))
#Run through all distinct elements in compound
#x below is not increasing; stays at 0???
for x in range(0 , numOfDistElements - 1):
element = str(input("What is the element?\n"))
numOfIndivElements = int(input("How many?\n"))
#Check if enterred element is a valid element
for y in elements:
if y[1] == element:
#Add that element's weight to total mass
grams += y[2] * numOfIndivElements
print(grams)
你怎麼知道'x'沒有改變?你甚至不使用這個值。請在for循環中打印'x',併爲元素數量輸入> 2的值。 – Matthias
這表明您在提示輸入時輸入了兩個數字。 – ForceBru