为什么在酸洗这个数组时会丢失最后一个值?

2024-10-01 07:48:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将配方的成分写入一个数组中,然后进行腌制并重新打开以供进一步使用。该程序需要能够采取任何数量的成分,所以循环三个输入的成分数量。你知道吗

recipedetails=[] #starts array

for i in range (ing_number): #Loops 3 intented code by in_number amount of times
    ing_name = input ("Enter ingredient name: ") #Ingredient name variable
    ing_amount = int (input ("Enter quantity of ingredient ")) #Quantity variable
    ing_unit =  input ("Enter unit of ingredient: ") #Unit variable

    recipedetails.append ((ing_name, ing_amount, ing_unit)) #closes array

    recipe = open(rec_name+".dat", "wb") #Creates .dat file with recipe name as file  name.
    pickle.dump(recipedetails, recipe) #Adds this info to .dat file

但是,当我输入时,例如4,数组只将3保存到.dat文件中。我不明白为什么会发生这种情况,因为它没有覆盖最后一种成分,似乎只是忽略了它。如何将所有循环变量添加到数组和.dat文件中?你知道吗

 print ("Create Recipe") #Shows user has opted to create recipe

 rec_name = input ("Enter recipe name: ") #Prompts user for recipe name.
 ing_number = int (input ("Enter number of ingredients: ")) #Prompts user for number of ingredients
 people = str (input ("Enter number of people: ")) #Prompts user for number of people

 f = open(rec_name+"people.txt", 'w')
 f.write(people)
 f.close()

 recipedetails=[] #starts array

 for i in range (ing_number): #Loops 3 intented code by in_number amount of times
     ing_name = input ("Enter ingredient name: ") #Ingredient name variable
     ing_amount = int (input ("Enter quantity of ingredient ")) #Quantity variable
     ing_unit =  input ("Enter unit of ingredient: ") #Unit variable

recipedetails.append ((ing_name, ing_amount, ing_unit)) #closes array

recipe = open(rec_name+".dat", "wb") #Creates .dat file with recipe name as file  name.
pickle.dump(recipedetails, recipe) #Adds this info to .dat file
print (recipedetails)#Prints ingredients that user has added.

添加了完整代码


Tags: ofnamenumberforinputrecipeunitvariable