【问题标题】:Why do the if/else statements not work within my function?为什么 if/else 语句在我的函数中不起作用?
【发布时间】:2018-07-30 05:59:26
【问题描述】:

我正在使用 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

谢谢大家

【问题讨论】:

  • 您的if-elif 结构允许没有执行分配给business_amountifelif 块,即customer != 'B'kwh &lt;= 800,在这种情况下,你从不分配business_amount...
  • 什么意思,你应该将两个 elif 块缩进一个缩进

标签: python function if-statement main definition


【解决方案1】:

您的代码至少存在三个问题。 首先,正如 juanpa.arrivillaga 在评论中提到的那样,您在每种情况下都在打印 business_amount,但只有在 customer == 'B' 时才分配

其次,如果“R”客户的千瓦时等于 500,“B”客户的千瓦时等于 800,则您没有分配。

最后,elif kwh > 500 似乎与 kwh

您可能希望您的代码看起来像这样:

    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)

【讨论】:

  • 谢谢你们两位发现了一些错误,现在我明白了:
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-07-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多