Python Forum
return outside function?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
return outside function?
#1
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")
Reply
#2
Please post entire error traceback message.
It contains important information
Reply
#3
(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.
Reply
#4
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
Reply
#5
Thanks Larz!
Reply
#6
Line 57...
All lines from 49 to 58 have to be indented.
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#7
Quote:All lines from 49 to 58 have to be indented.
already covered
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Use of function/return Paulman 6 2,367 Oct-24-2021, 11:07 PM
Last Post: Paulman
  Multiple return from function Grimmar 7 3,565 Mar-22-2021, 09:20 PM
Last Post: Grimmar
  Lambda function not return value mbilalshafiq 4 3,318 Jul-04-2020, 07:47 AM
Last Post: ndc85430
  Child class function of Log return "None" mbilalshafiq 2 2,220 Jun-30-2020, 07:22 PM
Last Post: mbilalshafiq
  Question on "define function"; difference between return and print extricate 10 4,719 Jun-09-2020, 08:56 PM
Last Post: jefsummers
  [split] problem with function return value ops 1 3,349 Apr-13-2020, 01:48 PM
Last Post: buran
  Function to return today's month, day, and year sbabu 9 4,924 Jan-28-2020, 06:20 PM
Last Post: snippsat
  return outside function seamus 4 3,060 May-17-2019, 07:38 PM
Last Post: seamus
  Recursive Function - Compare 2 lists, return the elements that don't exist in both KellyBaptist 1 5,227 Dec-23-2018, 10:10 AM
Last Post: Gribouillis
  Need of return in function if statement inside the function already returns Athul 5 3,921 Aug-16-2018, 10:19 AM
Last Post: DuaneJack

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020