2017-09-25 72 views
0

我在介紹編程類中,並且已丟失。我們有幾個實驗室需要知識,我們沒有教過,但我已經設法找出我需要谷歌(因爲沒有人迴應類留言板),但這個讓我非常沮喪。我會包括這裏引擎收錄鏈接:https://pastebin.com/6JBD6NNA在輸出中使用逗號

`principal = input() 
print('Enter the Principal Value of your investment: $', float(principal)) 

time = input() 
print('\nEnter the Time(in years) you plan to save your investment: ', int(time)) 

rate = input() 
print('\nEnter the Rate (2% = 0.02) you will collect on your investment: ', float(rate)) 


interest = (float(principal) * float(rate)) * int(time) 
final_value = float(principal) + float(interest) 
print('\nThe Final Value of your investment will be: $%.2f' % final_value)` 

所以我需要的美元數額的輸出有一個逗號(27,500.00 $),但我不知道如何做到這一點。我在這個網站和其他網站上看到了一些解決方案,但我無法讓他們工作。請有人可以幫助我嗎?

+0

您是否試過'「{:,}」.format(value)'from https://stackoverflow.com/questions/1823058/how-to-print-number-with-commas-as-thousands-分離器 – deltatango

+0

是的,我無法讓它工作;我只在我的第四周上課,所以你們都必須忍受我。 :P在檢查了下面的解決方案之後,我看到我做錯了什麼。感謝大家! –

回答

1

這是一個工作示例:

principal = float(input('Enter the Principal Value of your investment: $')) 

time = int(input('\nEnter the Time(in years) you plan to save your investment: ')) 

rate = float(input('\nEnter the Rate (2% = 0.02) you will collect on your investment: ')) 


interest = principal * rate * time 
final_value = principal + interest 
print('The Final Value of your investment will be: ${:,.2f}'.format(final_value)) 
+0

我在輸入變量賦值的過程中遇到了語法問題,你的回答也有很大的幫助。謝謝! –

2

在Python 2.7或以上,你可以使用

print('The Final Value of your investment will be: ${:,.2f}'.format(final_value)) 

這在PEP記錄378

來源:Python Add Comma Into Number String

+0

當我嘗試用我的變量時,我得到「SyntaxError:EOL掃描字符串文字」 –

+0

在你的原始問題,你有整個代碼塊在後面滴答(爲什麼?)。也許你需要再次添加它們。這對我很好: '>>> print('您的投資的最終價值將是:$ {:,。2f}'。format(23456789)) 您的投資的最終價值將是:$ 23,456,789.00' –

+0

不知道爲什麼那些在那裏,他們不在我的原始代碼。也許當我把它變成一個代碼塊時,他們就被添加了。 –

1

你的最後一行應該是:

print ("\nThe Final Value of your investment will be: ${:,.2f}".format(final_value)) 
+0

所以雙引號的唯一區別是什麼?謝謝你的工作 (我的意思是你的解決方案和上面Stuart的唯一區別) –

+1

任何一個引用都應該起作用 –