python - 如何避免冗余和冗长的 if-else-结构?

标签 python

有没有更简单高效的方法来编写这段代码?这是一个计算吸烟费用的计算器。

必须有一种方法可以跳过所有的ifelif标签,并使其成为一个循环并节省几分钟的代码输入,并且可能有甚至成为我错过的如何键入这样的代码的“标准”。

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.') 

最佳答案

您可以使用字典和预定义函数:

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.')

关于python - 如何避免冗余和冗长的 if-else-结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30443558/

相关文章:

python - 当数据为 str 时,找出满足数值条件的索引

python - 使用库 xarray (python) 进行分组后,时间维度错误

python - 如果条件成立,计算嵌套组的平均值

python - matplotlib 泛缩放颜色条轴

python - Numpy 等级 1 数组

python - 通过检查多个条件更改 Pandas 列值

python - 从脚本和命令行访问函数

python - 测试一个字符串的子字符串

c# - 用于 Unity3d 5.x 的极简主义 Python 服务器

python - 拆分列表字符串并创建字典