Search code examples
pythonfunctionif-statementprogram-entry-pointdefinition

Why do the if/else statements not work within my function?


I am using if/else statements for the user to choose a customer option (Resident or Business), type in how many kilowatts they have used and the program will calculate the power bill. This must be used within functions (a chapter that we are learning in class). This is my code:

def main():
    customer = input("Enter R for residential or B for business")
    hours = int(input("Enter number of khw"))
    bill_calculator(hours, customer)


def bill_calculator(kwh,customer):
    if customer == 'R' :
        if kwh < 500:
            normal_amount = kwh * .12
        print ("Please pay this amount: ", normal_amount)
    elif kwh > 500:
        over_amount = kwh * .15
        print("Please pay this amount",over_amount)

    if customer == 'B':
        if kwh < 800:
            business_amount = kwh * .16
        print("Please pay this amount: ")
    elif kwh > 800:
        business_amount = kwh * .2
    print("Please pay this amount,", business_amount)

    main()

My "resident" calculation works and is displayed BUT the "business" calculation does not. I feel like this has to do with my indentation but I don't know where.

Here are my errors at the bottom:

Enter R for residential or B for businessR
Enter number of khw77
Please pay this amount:  9.24
Traceback (most recent call last):
  File "C:/Users/vanbe/PycharmProjects/Lesson7/L07P2.py", line 24, in <module>
    main()
  File "C:/Users/vanbe/PycharmProjects/Lesson7/L07P2.py", line 4, in main
    bill_calculator(hours, customer)
  File "C:/Users/vanbe/PycharmProjects/Lesson7/L07P2.py", line 22, in bill_calculator
    print("Please pay this amount,", business_amount)
UnboundLocalError: local variable 'business_amount' referenced before assignment

Thanks y'all


Solution

  • There are at least three problems with your code. First, as juanpa.arrivillaga mentions in the comment, you are printing business_amount in every case, but only assigning when customer == 'B'

    Second, you're not assigning if the kwh is equal to 500 for 'R' customers and 800 for 'B' customers.

    Finally, it looks like the elif kwh > 500 is meant to be on the same level as kwh < 500.

    You probably want your code to look something like this:

        if customer == 'R' :
            if kwh < 500:
                normal_amount = kwh * .12
                print ("Please pay this amount: ", normal_amount)
            elif kwh >= 500:
                over_amount = kwh * .15
                print("Please pay this amount",over_amount)