user3290698
user3290698

Reputation: 1

Python Programming Using multiple functions

Hey im new to python and my teacher wants us to create a function with multiple functions. Here is what my program looks like

def main():
    carpetyards = float(input("Enter amount of yards the carpet is"))
    carpetcost = 5.50 * carpetyards
    fee = carpetcost + 25.00
    tax = .06 * fee
    totalcost = fee + tax  
results() 

def results():
    print()
    print('carpetyards    :' , format (carpetyards))
    print('carpetcost     :' , format (carpetcost, '9,.2f'))
    print('fee            :' , format (fee,        '9,.2f'))
    print('tax            :' , format (tax,        '9,.2f'))
    print('totalcost      :' , format (totalcost,  '9,.2f'))   

main() 

I get either nameerror or results is not defined error. Can someone please help?

Upvotes: 0

Views: 120

Answers (2)

hydronium
hydronium

Reputation: 316

The line at the end of main() (results()) is not indented, so it the program does this:

  1. Define main()
  2. Run results()
  3. Define results()
  4. Run main()

As you can see, there will be several errors, because you are not only running results() before it is defined, but the variables used in results() (which are set in main()) are out of its scope (variables set in main() only work inside main() unless you make them global).

Upvotes: 1

rae1
rae1

Reputation: 6144

You need to define results inside the main function for this to work,

def main():
   carpetyards = float(input("Enter amount of yards the carpet is"))
   carpetcost = 5.50 * carpetyards
   fee = carpetcost + 25.00
   tax = .06 * fee
   totalcost = fee + tax  

   # 'main' function scope
   def results():
     print()
     print('carpetyards    :' , format (carpetyards))
     print('carpetcost     :' , format (carpetcost, '9,.2f'))
     print('fee            :' , format (fee,        '9,.2f'))
     print('tax            :' , format (tax,        '9,.2f'))
     print('totalcost      :' , format (totalcost,  '9,.2f'))   

   results() 

# outer scope
main()

You could further define other functions inside main as long as you properly indent them.

Upvotes: 0

Related Questions