-1

When i comment out the def main() and main() the code runs as expected, but when the function calls go under a main function totalOfItems becomes undefined somehow, does any one know why?

import math 

def shoppingTotal(numItem):
    totalOfItems = 0
    for x in range(numItem):
        totalOfItems += int(input('Whats the cost: '))
    print(totalOfItems)
    return(totalOfItems)

def amountTax(total):
    totalTax = (totalOfItems * 1.13) - totalOfItems
    print(totalTax)
    return(totalTax)

def totalBill(amount, tax):
    finalBill = totalTax + totalOfItems
    print(finalBill)
    return(finalBill)


def greeting():
    print('1. Mangoes $5')
    print('2. Meat $3')
    print('3. Juice $7')
    print('4. Banana $2')

def main():

    greeting()

    numItem = int(input('How many items did you buy: '))
    totalOfItems = shoppingTotal(numItem)

    total = totalOfItems

    totalTax = amountTax(total)
    totalBill(amount=totalOfItems,tax=totalTax)


main()
  • 7
    You need to read about variable scope. If a variable is local to `main` then it wouldn't be visible outside of `main`. – John Coleman Oct 08 '21 at 01:45
  • Also some of your functions don't do anything with the arguments they accept. – Selcuk Oct 08 '21 at 01:48
  • As an aside `import math` is unused, and your functions should probably not `print` anything (leave it to the caller to decide whether or not they want to display the result to the user). – tripleee Oct 08 '21 at 06:15

1 Answers1

-1

This is because variable "totalOfItems" and "totalTax" have scope limited to main function. To avoid this problem, above mentioned variables are to be defined globally, you can edit your main function to something like

 greeting()
    global totalOfItems 
    global totalTax
    
    numItem = int(input('How many items did you buy: '))
    totalOfItems = shoppingTotal(numItem)
    total = totalOfItems

    totalTax = amountTax(total)
    totalBill(amount=totalOfItems,tax=totalTax)

and it should allow other functions to access variables "totalOfItems" and "totalTax" since their scope is now global and are available to every function.