私はpythonが初めてで、現在リストと辞書を扱う方法を学んでいます。
私はこれらの2つの機能を持っています
def food_database(item_name, size_serv, calorie_serv, protein_serv, carb_serv, fat_serv):
# used to list the different foods when users ask for it
# food database
food_dict = [ {
'food_name': item_name,
'serving_size': size_serv,
'serving_calorie': calorie_serv,
'serving_protien': protein_serv,
'serving_fat': fat_serv,
'serving_carb': carb_serv
} ]
print food_dict
def food_in_diet(item_name, size_serv, calorie_serv, protein_serv, carb_serv, fat_serv, num_serv):
# used to show how much is in the diet plan for the user
User_diet_dict = [ {
'food_name': item_name,
'amount': num_serv*size_serv,
'serving_calorie': num_serv*calorie_serv,
'serving_protien': protein_serv,
'serving_fat': fat_serv,
'serving_carb': carb_serv
} ]
print User_diet_dict
私はこの他の機能を持っています
def add_food():
ask_to_add_another = raw_input("Would you like to add another food?(y/n)")
if ask_to_add_another == 'y':
# update
item_name = raw_input("What is the name of the food you would like to add? ")
size_serv = input("What is the size(grams) in each serving of %s? " % item_name)
calorie_serv = input("How many calories is in each serving of %s? " % item_name)
protein_serv = input("How many grams of protein is in each serving of %s? " % item_name)
carb_serv = input("How many grams of carbohydrates is in each serving of %s? " % item_name)
fat_serv = input("How many grams of fat is in each serving of %s? " % item_name)
num_serv = input("How many servings of %s would you like to add? " % item_name)
food_dict.append( {
'food_name': 'item_name',
'serving_size': size_serv,
'serving_calorie': calorie_serv,
'serving_protien': protein_serv,
'serving_fat': fat_erv,
'serving_carb': carb_serv
} )
# User_diet_dict.append = ( {
# 'food_name': item_name,
# 'amount': num_serv*size_serv,
# 'serving_calorie': num_serv*calorie_serv,
# 'serving_protien': protein_serv,
# 'serving_fat': fat_serv,
# 'serving_carb': carb_serv
# } )
# add to the dictonary/list
print food_dict
add_food()
if ask_to_add_another == 'n':
return False
add_food() 関数は food_dict 辞書を更新し、リストに追加します。
エラーが発生します
Traceback (most recent call last):
File "MACROCALC.py", line 156, in <module>
main()
File "MACROCALC.py", line 35, in main
add_food()
File "MACROCALC.py", line 130, in add_food
food_dict.append( {
NameError: global name 'food_dict' is not defined
辞書がグローバルではないため、これが発生しているように感じます。
誰かが興味を持っているなら、これが私のコードです --> http://pastebin.com/m8S6fkS
提案をお待ちしています!初心者プログラマーが上達することを目指しています!
あなたの助けに感謝!