[英]How do I condense my code? (formatting & calculations
sorry I am new to coding so I apologise if this is an amateur question.抱歉,我是编码新手,所以如果这是一个业余问题,我深表歉意。 An exercise has asked that I create code that calculates the 4% interest on an investment for 1,2 and 3 years.
一个练习要求我创建代码来计算 1,2 和 3 年投资的 4% 利息。 I have duplicated a lot of code and would like to know how I could do it differently: in a more condensed way.
我已经复制了很多代码,并且想知道如何以不同的方式进行操作:以更简洁的方式。
For example, is it possible to convert every year in one like such as this float(year1, year2, year3)
as appose to having multiple lines of code?例如,是否有可能将每年都转换成这样的
float(year1, year2, year3)
以适应多行代码?
startingBalance = input("Please enter your starting bank balance: ")
startingBalance = int(startingBalance)
year1 = (startingBalance * 1.04)
year2 = (year1 * 1.04)
year3 = (year2 * 1.04)
year1 = "{0:.2f}".format(year1)
year2 = "{0:.2f}".format(year2)
year3 = "{0:.2f}".format(year3)
print("Starting Balance: " + str(startingBalance) + "\n" + "Year 1 Balance: " + year1 + "\n" + "Year 2 Balance: " + year2 + "\n" + "Year 3 Balance: " + year3)
answer=str(input("would you like to withdraw your profits? Y/N: "))
if answer in ['Y', 'y']:
startingBalance = float(startingBalance)
year1 = float(year1)
year2 = float(year2)
year3 = float(year3)
year1Profit = year1 - startingBalance
year1Profit = "{0:.2f}".format(year1Profit)
year2Profit = year2 - startingBalance
year2Profit = "{0:.2f}".format(year2Profit)
year3Profit = year3 - startingBalance
year3Profit = "{0:.2f}".format(year3Profit)
str(year3Profit)
print("Year | Balance | Profit " + "\n" + "Year 1 " + str(year1) + " " + year1Profit + "\n" + "Year 2 " + str(year2) + " " + year2Profit + "\n" + "Year 3 " + str(year3) + " " + year3Profit)
elif answer in ['N', 'n']:
print("Goodbye")
else:
print("Invalid Entry")
Technically this is one line:从技术上讲,这是一行:
year1, year2, year3 = float(year1), float(year2), float(year3)
But I think it would be clearer if you didn't change the type of your variables after initialisation.但是我认为如果您在初始化后不更改变量的类型会更清楚。 You can keep them as floats all the time change your print line to:
您可以始终将它们保留为浮点数,将打印行更改为:
print("Starting Balance: " + str(startingBalance) + "\n" + "Year 1 Balance: " + "{0:.2f}".format(year1) + "\n" + "Year 2 Balance: " + "{0:.2f}".format(year2) + "\n" + "Year 3 Balance: " + "{0:.2f}".format(year3))
This saves you from converting to string and back again.这使您免于转换为字符串并再次转换回来。
This question might be more appropriate in Code Review but:这个问题在Code Review中可能更合适,但是:
year1 = "{0:.2f}".format(year1)
Can be replaced by:可以替换为:
year1 = round(year1, 2)
You use.format and print("foo" + bar) in the same code I recommend using one type:在我推荐使用一种类型的相同代码中使用 .format 和 print("foo" + bar):
F-strings if Python3.6 or above如果是 Python3.6 或更高版本,则为 F 字符串
print(f"Starting Balance: {startingBalance}\nYear 1 Balance: {year1}\nYear 2 Balance: {year2}\nYear 3 Balance: {year3}")
.format if Python2 or 3 < 3.6 .format 如果 Python2 或 3 < 3.6
print("Starting Balance: {}\nYear 1 Balance: {}\nYear 2 Balance: {}\nYear 3 Balance: {}".format(startingBalance, year1, year2, year3))
No need to put str() here:无需将 str() 放在这里:
answer=str(input("would you like to withdraw your profits? Y/N: "))
The input() always returns a string. input() 总是返回一个字符串。
Use "\t" when you want (i'm guessing) tabulations instead of a bunch of spaces (ugly):当你想要(我猜)列表而不是一堆空格(丑陋)时使用“\ t”:
print("Year | Balance | Profit " + "\n" + "Year 1 " + str(year1) + " " + year1Profit + "\n" + "Year 2 " + str(year2) + " " + year2Profit + "\n" + "Year 3 " + str(year3) + " " + year3Profit)
Same thing here use f-strings or.format to format your string.同样的事情在这里使用 f-strings 或 .format 来格式化你的字符串。
To avoid writing the same code, you can create a function to compute the final balance and the profit.为避免编写相同的代码,您可以创建 function 来计算最终余额和利润。 Then you can use the others answers to know how to format your variable and return them
然后您可以使用其他答案来了解如何格式化变量并返回它们
def compute_year(starting_balance, number_of_year):
return (startingBalance * 1.04 ** number_of_year, startingBalance * 1.04 ** number_of_year - startingBalance)
year1, year1Profit = compute_year(startingBalance, 1)
year2, year2Profit = compute_year(startingBalance, 2)
year3, year3Profit = compute_year(startingBalance, 3)
Yes, it is very much possible, When you find yourself writing repeating lines of code, try using functions !是的,很有可能,当你发现自己在写重复的代码行时,尝试使用函数! In that way you only have to define an expression once!
这样,您只需定义一次表达式!
example:例子:
year1 = (startingBalance * 1.04)
year2 = (year1 * 1.04)
year3 = (year2 * 1.04)
Can be change to可以改成
def interest(balance):
return balance * 1.04
year1 = interest(startingBalance)
year2 = interest(year1)
But this still seems repetitive, right?但这似乎仍然是重复的,对吧? Now try using a
for
-loop aswell:现在尝试使用
for
循环:
current_balance = startingBalance
for year in range(4):
current_balance = interest(current_balance)
print(current_balance)
Now in each loop, you can print the value of the new balance, Finally add in the line printg for a pretty output: and you could get something like this:现在在每个循环中,您可以打印新余额的值,最后在 printg 行中添加一个漂亮的 output:您可以得到如下内容:
def interest(balance, years):
return balance * (1.04 ** years)
def print_gains(balance, year):
header = 'Year | Balance | Profit '
print(header)
print('-' * len(header))
for year in range(1 + year):
new_balance = interest(balance, year)
print('%5d| %10.2f | %10.2f' % (year, new_balance, new_balance - balance))
print()
def main():
print_gains(10000, 5)
main()
resulting in the following output:产生以下 output:
Year | Balance | Profit
-----------------------------
0| 10000.00 | 0.00
1| 10400.00 | 400.00
2| 10816.00 | 816.00
3| 11248.64 | 1248.64
4| 11698.59 | 1698.59
5| 12166.53 | 2166.53
I hope this helps you!我希望这可以帮助你!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.