简体   繁体   中英

How to loop with two conditions, in python?

I need to write a code that displays the a return of investments for 0 to 20 years or when the today's value has reached.5 * of the investment initial invested amount. I am stuck with the latter part. When I use an IF statment, I couldn't get any value. Here is my code.

def getExpInvestAmt(investAmt, i, n):
    expInvestAmt = int(investAmt * pow(1 + i / 100, n))
    return expInvestAmt

def getPresentValue(exp_invest_amt, d, n):
    adjAmt = int(exp_invest_amt / pow(1 + d / 100, n))
    return adjAmt


def main():
    investAmt = float(input("Enter investment amount:"))
    i = float(input("Enter the expected investment growth rate:"))
    d = float(input("Enter the discount rate:"))
    n = 0
    adjA = 0
    print("Year \t Value at year($) \t Today's worth($)")
    for x in range(0, 21):  
        if adjA < 0.5 * investAmt
            break 
        expected_value = getExpInvestAmt(investAmt, i, n)
        present_value = getPresentValue(expected_value, d, n)
        n += 1
        adjA += 1
        print("{} \t {:,} \t {:,}".format(x, expected_value, present_value))


main()

This is what I am suppose to get,

Enter investment amount: 10000
Enter the expected investment growth rate: 5
Enter the discount rate: 6.25
Year Value at Year($) Today's worth($)
 1       10,500           9,346
 2       11,025           8,734
 3       11,576           8,163
 4       12,155           7,629
 5       12,763           7,130
 6       13,401           6,663
 7       14,071           6,227
 8       14,775           5,820
 9       15,513           5,439
 10      16,289           5,083
 11      17,103           4,751  # today's value have reached <= 50% of the initial amount program stops.

I think you can simplify your code; you don't need adjA or x . Where you are using adjA you should just be using present_value , and you can just iterate n over the range instead of x :

def main():
    investAmt = float(input("Enter investment amount:"))
    i = float(input("Enter the expected investment growth rate:"))
    d = float(input("Enter the discount rate:"))
    print("Year \t Value at year($) \t Today's worth($)")
    for n in range(1, 21):  
        expected_value = getExpInvestAmt(investAmt, i, n)
        present_value = getPresentValue(expected_value, d, n)
        print("{} \t {:,} \t {:,}".format(n, expected_value, present_value))
        if present_value < 0.5 * investAmt:
            break 

To get your expected results for an investAmt of 10000 and i of 5, you need a d value of 12.347528.

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