Python Forum

Full Version: return outside function?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have been battling with this code for like an hour lol. I have unindented, indented and now I'm on the error "Return outside of function". What am I doing wrong here? Thanks in advance!

 # create variables
item_cnt = int(0)		# this is the item counter
tot_cals = int(0)		# this is the total meal calories

# create global variables
itemNameGlobal = ""
itemCalsGlobal = 0


def disp_menu():
        choice_list ["a", "d", "m", "q"]

        while True:
                print("What would you like to do")
                print("a = add an item")
                print("d = delete an item")
                print("m = display the meal so far")
                print("q = quit")
                choice = input("make a selection>")

        if choice in choice_list:
                return choice
        else:
                print("that is not a valid entry, please try again.")
	



def disp_meal():
    print("\nMeal Calorie Counter")
    print("Num\tItem\t\tCals")
    print("---\t----\t\t---")
    meal_cals = 0

    for c in range(len(item_list)):
        meal_cals += cals_list[c]
        print("{}.\t{}\t\t{}".format(c+1, item_list[c], cals_list[c]))

    print("\nYour meal has {} items for a total {} calories\n".format(len(item_list), meal_cals))
    print("-" *  20)




def enterItemName():
        
	valid_data = False
	#capture input
while not valid_data:
                  item_name = input("please enter the item>")
if len(item_name) > 20:
                          print("not a valid food name")
elif len(item_name) == 0:
                          print("you need to enter a name")
else:
                    #item_name is valid
return item_name

def enterElementGrams(element):
	
	valid_data = False
	while not valid_data:
            try:
                grams = int(input("enter grams of {}> ".format(element)))
                valid_data = True
            except Exception as detail:
                    print("{} error: ".format(element), detail)
		
            return grams

def math(element, grams):
	if element == "f":
		return grams * 9
	else:
		return grams * 4

def add_process(tot_cals, item_cnt):
    #input data
    item_name = enterItemName()
    g_carbs = enterElementGrams("carbs")
    g_fats = enterElementGrams("fats")
    g_prot = enterElementGrams("proteins")

    cals = math("c", g_carbs) + math("f", g_fats) + math("p", g_prot)
#output

    print("total calories for {} are {}".format(item_name, cals))
	
    incl = input("would you like to include {}? (y/n)".format(item_name))

    if incl.lower() == "y":
        add_item(item_name, cals)
            
        tot_cals = tot_cals + cals
        item_cnt += 1
        print("item {} entered.".format(item_name))
    else:
        print("item {} not entered.".format(item_name))

    return tot_cals, item_cnt

                    
def addItem(name, cals):
        item_list.append(name)
        cals_list.append(cals)

def del_Item():
    if len(item_list) == 0:
        print("you have no items in your menu to delete")
    else:
        print("\nDelete an item")
        disp_meal()

        valid_data = False
        while not valid_data:
            try:
                choice = int(input("Please enter the item number you would like to delete>"))
                if 1<= choice <= len(item_list):

                    choice = choice - 1

                    print("item {}. {} with {} calories will be deleted".format(choice+1,
                                                                                            item_list[choice]
                                                                                            ,cals_list[choice]))
                    del item_list[choice]
                    del cals_llist[choice]
                    valid_data = True

            except Exception as detail:
                   print("error: ", detail)
                   print("please try again")
             


# create the main program here
while True:

    choice = disp_menu()

    if choice == "a":
         tot_cals , item_cnt = add_process(tot_cals, item_cnt)
    elif choice == "d":
          del_item()
    elif choice == "q":
        break

    disp_meal()
	


disp_meal()
print("Thank you for using our program")
Please post entire error traceback message.
It contains important information
(Mar-03-2018, 06:21 PM)Larz60+ Wrote: [ -> ]Please post entire error traceback message.
It contains important information

how can I do that? I try and press F5 to run the program but it won't let me. Just says return outside function.
You have many issues in this program:
choice_list ["a", "d", "m", "q"]
needs to be
choice_list = ["a", "d", "m", "q"]
        while True:
                print("What would you like to do")
                print("a = add an item")
                print("d = delete an item")
                print("m = display the meal so far")
                print("q = quit")
                choice = input("make a selection>")
indentation is wrong, needs to be:
def disp_menu():
    choice_list = ["a", "d", "m", "q"]
 
    while True:
        print("What would you like to do")
        print("a = add an item")
        print("d = delete an item")
        print("m = display the meal so far")
        print("q = quit")
        choice = input("make a selection>")
 
        if choice in choice_list:
            return choice
        else:
            print("that is not a valid entry, please try again.")
item_cnt = int(0)       # this is the item counter
item_cnt = 0       # this is the item counter
you don't need the int. zero is already an integer

You should refrain from using globals, it's considered poor programming practice, and rarely needed
you define two that aren't even used:
# create global variables
itemNameGlobal = ""
itemCalsGlobal = 0
the function that is causing the error is:
enterItemName,
indentation is just wrong:
replace with:
def enterItemName():
    item_name = None
    valid_data = False
    # capture input

    while not valid_data:
        item_name = input("please enter the item>")
        if len(item_name) > 20:
            print("not a valid food name")
        elif len(item_name) == 0:
            print("you need to enter a name")
    return item_name
there's more, fix these and your remaining errors may be more obvious
Thanks Larz!
Line 57...
All lines from 49 to 58 have to be indented.
Quote:All lines from 49 to 58 have to be indented.
already covered