2015-10-13 48 views
0
percentage = int(input("\nWhat percentage of your bill would you like to calculate? ")) 
percentage = float(round(percentage/100 * bill, 2)) 

大家好我可以縮短這個嗎? IE沒有百分比=被使用兩次?

新的Python,不知道上面的代碼兩行是否可縮短至僅包括「百分比=」一次?

由於「百分比」變量是由用戶輸入定義的,我假設在這樣做之前,我無法將「百分比」定義爲方程式,因此兩個單獨的代碼行?

如果它有助於瞭解最終目標,那麼這裏是代碼作爲一個整體 - 這是一個簡單的小費計算器:

# Tip calculator 
# calculates a %15 and %20 tip for any given meal 
# code by c07vus 


print("\nHello, welcome to tip calculator!") 

bill = float(input("\nIn £'s what was the bill total? ")) 

fifteen = float(round(15/100 * bill, 2)) 

twenty = float(round(20/100 * bill, 2)) 

print("\nA %15 tip of your bill would be:", fifteen, "pounds") 
print("\nA %20 tip of your bill would be:", twenty, "pounds") 

print("\nYou can also calculate any percentage you like!") 

percentage = int(input("\nWhat percentage of your bill would you like to calculate? ")) 
percentage = float(round(percentage/100 * bill, 2)) 

print("\nThank you, your tip would be:", percentage, "pounds") 

input("\n\nPress the enter key to exit") 

感謝所有幫助和建議!

回答

1

當然,你可以把它放在一行:只要把你指定的表達式percentage放到你在第二行使用該值的地方。但不要指望這條線是漂亮的,或可讀......

percentage = float(round(int(input("\nWhat percentage of your bill would you like to calculate? "))/100 * bill, 2)) 

一般情況下,我會跟你現在的版本棒。但是,在這種特殊情況下,我會重命名第二個變量,因爲這不再是百分比!這是小費。

percentage = int(input("\nWhat percentage of your bill would you like to calculate? ")) 
tip = float(round(percentage/100 * bill, 2)) 

此外,你做了三次計算!這應該是足夠的理由讓這樣的功能:

to_tip = lambda percent: float(round(percent/100 * bill, 2)) 
... # use that same function to calculate fifteen and twenty 
tip = to_tip(percentage) 

最後,如果你想顯示的結果正好兩位小數,使用格式字符串比四捨五入更好。

print("\nThank you, your tip would be: {:.2f} pounds".format(tip)) 
+0

哇!謝謝! – c07vus