[英]How to avoid a redundant and verbose if-else-structure?
Is there a simpler and more efficient way to writing this code? 编写此代码是否有更简单,更有效的方法? It is a calculator on how much it costs to smoke. 这是一个计算吸烟成本的计算器。
There must be a way of skipping all the if
and elif
tags, and make it into a loop and save a few minutes of typing the code, and there may be even a "standard" in how to type code like this that I have missed. 必须有一种方法可以跳过所有if
和elif
标签,并将其变成一个循环并节省几分钟的代码输入,甚至可能有一个“标准”如何输入这样的代码,我错过了。
how_many = int(input('How many ciggaretes do you smoke each day?\n'))
per_package = int(input('How much does your package cost?\n'))
contain = int(input('How many ciggaretes does the package contain?\n'))
cost_st = per_package / contain
choice = input('Do you want to calculate the cost per "Day (D)" / "Week (W)" / "Year (Y)" / "Decade (DE)"?\n')
if choice == 'D':
cost_day = cost_st * how_many
print("It will cost", cost_day ,"kr per day.")
elif choice == 'W':
cost_week = (cost_st * how_many) * 7
print('It will cost', cost_week,'kr per week.')
elif choice == 'Y':
cost_year = (cost_st * how_many) * 365
print('It will cost' ,cost_year, 'kr per year.')
elif choice == 'DE':
cost_DE = ((cost_st * how_many) * 365) * 10
print('It will cost' ,cost_DE, 'kr per decade.')
else:
print('Something went wrong! Try again please.')
You can use a dictionary and a predefined function: 您可以使用字典和预定义函数:
mappings = {'D': 1, 'W': 7, 'Y': 365, 'DE': 3650}
def calculate_cigarettes(arg):
cost = cost_st * how_many * mappings[arg]
print('It will cost', cost, 'kr total.')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.