2015-05-25 89 views
2

有沒有更簡單,更有效的方式來編寫這段代碼?這是一個計算吸菸成本的計算器。如何避免冗餘和冗長的if-else結構?

必須有一種方法可以跳過所有的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.') 

回答

7

您可以使用字典和預定義的函數:

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

謝謝!爭取它會是這樣的事情:) – Salviati

+0

請標記爲答案與旁邊的檢查。 –

+0

它的20秒鐘去 – Salviati