简体   繁体   中英

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. 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?

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:

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:

F-strings if Python3.6 or above

print(f"Starting Balance: {startingBalance}\nYear 1 Balance: {year1}\nYear 2 Balance: {year2}\nYear 3 Balance: {year3}")

.format if Python2 or 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:

answer=str(input("would you like to withdraw your profits? Y/N: "))

The input() always returns a string.

Use "\t" when you want (i'm guessing) tabulations instead of a bunch of spaces (ugly):

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.

To avoid writing the same code, you can create a function to compute the final balance and the profit. 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:

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:

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:

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM