【问题标题】:python see the code and try to help me friendspython查看代码并尝试帮助我的朋友
【发布时间】:2018-03-05 14:00:30
【问题描述】:

价格 = { “1”:1000, “2”:2000, “3”:3000, “4”:4000, “5”:5000, }

def get_total_challan_cost(): total_price = 0

while True:
    challan_type = input("Enter the Challan Type: ")

    if challan_type == "":
        break

    price = prices[challan_type]
    total_price += price

    print("The price for Challan is: {}".format(price))

print("")
print("Total price: {}".format(total_price))

定义主(): # 生成 machine_cost、diesel_cost 等的代码 ...

# machine_cost = ...?
# diesel_cost = ...?
challan_cost = get_total_challan_cost()

# print(machine_cost + diesel_cost + challan_cost + ...)

如果 name == "ma​​in": 主要()

到这里就OK了

现在我在新行中打印以下内容 打印(get_total_challan_cost) 它应该只给出总挑战成本,而不需要再次输入

【问题讨论】:

  • 只有一个输入?其他输入的总和?
  • 您能否具体说明您想要求和的内容以及预期的输出?
  • 我假设 OP 意味着 while 循环的每次迭代
  • 该程序将迭代直到我们输入空格
  • 输入查伦类型:1查伦价格为:1000 输入查伦类型:4查伦价格为:4000 输入查伦类型:5查伦价格为:5000

标签: python python-3.x


【解决方案1】:

对目前的总成本使用累加器变量,对价格使用dict

试试这样的:

prices = {
    '1': 1000,
    '2': 2000,
    '3': 3000,
    '4': 4000,
    '5': 5000,
}

def get_total_challan_cost():
    total_price = 0

    while True:
        challan_type = input("Enter the Challan Type: ")

        if challan_type == "":
            break

        price = prices[challan_type]
        total_price += price

        print("The price for Challan is: {}".format(price))

    print("")
    print("Total price: {}".format(total_price))

def main():
    # code that generates machine_cost, diesel_cost etc ...

    # machine_cost = ...?
    # diesel_cost = ...?
    challan_cost = get_total_challan_cost()

    # print(machine_cost + diesel_cost + challan_cost + ...)

if __name__ == "__main__":
    main()

【讨论】:

  • 非常感谢兄弟的帮助你能说任何我可以学习pythod编码的网站吗
  • @Dhanvanth 我不能专门推荐任何 Python 教程,但互联网上有很多可以帮助您了解基础知识的内容。 一般而言的一个好的编程原则是 DRY - “不要重复自己”。如果您发现自己编写的程序包含大量包含几乎相同代码块的 if-else 语句,请尝试弄清楚如何重构它。
  • @Dhanvanth 不客气。如果此答案解决了您的问题,请考虑接受它:-)
  • 在上面一切都很好,但我想在其他行打印总价它不起作用(total_price)
  • @Dhanvanth 即现在的输出是什么样的,你希望它是什么样的?
猜你喜欢
  • 2015-11-30
  • 2021-03-21
  • 2022-07-28
  • 1970-01-01
  • 2010-11-20
  • 2019-11-01
  • 1970-01-01
  • 2016-02-03
  • 2022-11-29
相关资源
最近更新 更多