代码之家  ›  专栏  ›  技术社区  ›  Francis Bradley

为什么if/else语句不能在我的函数中工作?

  •  -1
  • Francis Bradley  · 技术社区  · 8 年前

    我使用if/else语句让用户选择客户选项(居民或企业),输入他们使用的千瓦数,然后程序将计算电费。这必须在函数中使用(我们在课堂上学习的一章)。这是我的代码:

    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()
    

    我的“常驻”计算工作并显示,但“业务”计算不工作。我觉得这和我的压痕有关,但我不知道在哪里。

    下面是我的错误:

    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
    

    谢谢大家

    1 回复  |  直到 8 年前
        1
  •  2
  •   Brad Dre    8 年前

    您的代码至少有三个问题。 首先,作为juanpa。arrivillaga在评论中提到,您在任何情况下都在打印business\u金额,但仅在客户==“B”时分配

    其次,如果“R”客户的kwh等于500,而“B”客户的kwh等于800,则不需要进行分配。

    最后,它看起来像elif kwh>500意味着与kwh处于同一水平<500

    您可能希望您的代码如下所示:

        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)