简体   繁体   中英

How to use try-except block to validate the input, and use a while statement to prompt the user until a valid input in Python?

my task is to calculate the amount of money in a saving account in two ways and compare the results. It prompt the user for input principle, the interest rate(as a percent), and years of invest.I need to use try-except block to validate the input, and use a while statement to prompt the user until a valid input. I have issue on the validation and while process. When I had invalid input, it didn't print associated exception error as expected.The function parts are Ok, just ignore them. Also, "Going around again" is supposed to print before the next prompt input, but mine appeared by the end of correct input execution. Could you please help me? Thanks.

def calculate_compound_interest(principle, int_rate, years):
value = principle * (1 + int_rate)**years
return value


def calculate_compound_interest_recursive(principle, int_rate, years):
    if years == 0:
        return principle
    else:
        recursive_value = calculate_compound_interest_recursive(principle, int_rate, years-1)* 
        (1+int_rate)
    return recursive_value


def format_string_output(value, recursive_value):
    return "Interest calculated recursively is {:,.2f} and calculated by original formula is 
           {:,.2f}.These values are a match.".format(recursive_value,value)


print(__name__)
if __name__ == "__main__":

    while True: 
        principle_input = input("Please input principle:")
        interest_rate_input = input("Please input interest rate with %:")
        years_input = input("Please input years:")
        try:
            p = float(principle_input)
            i = (float(interest_rate_input.replace("%","")))/100
            n = int(years_input)
    
        except ValueError():
            print("Error: invalid principle.")  
        except ValueError():
            print("Error: invalid interest rate.")
        except ValueError():
            print("Error: invalid years.")
        else:
            print(calculate_compound_interest(p, i, n))
            print(calculate_compound_interest_recursive(p, i, n))
            print(format_string_output(calculate_compound_interest(p, i, n), 
                  calculate_compound_interest_recursive(p, i, n)))
            break
        finally:
            print("Going around again!")

Note: Finally block runs whenever a try or any except block runs.

The Try-Except blocks need to be paired up, easier to show than explain.

def calculate_compound_interest(principle, int_rate, years):
    value = principle * (1 + int_rate)**years
    return value


def calculate_compound_interest_recursive(principle, int_rate, years):
    if years == 0:
        return principle
    else:
        recursive_value = calculate_compound_interest_recursive(principle, int_rate, years-1)*(1+int_rate)
    return recursive_value


def format_string_output(value, recursive_value):
    return "Interest calculated recursively is {:,.2f} and calculated by original formula is {:,.2f}.These values are a match.".format(recursive_value,value)


if __name__ == "__main__":
    while True: 
        principle_input = input("Please input principle:")
        interest_rate_input = input("Please input interest rate with %:")
        years_input = input("Please input years:")
        
        try:
            p = float(principle_input)
        except ValueError():
            print("Error: invalid principle.")
            print("Going around again!")
            continue

        try:
            i = (float(interest_rate_input.replace("%","")))/100
        except ValueError():
            print("Error: invalid interest rate.")
            print("Going around again!")
            continue
        
        try:
            n = int(years_input)
        except ValueError():
            print("Error: invalid years.")
            print("Going around again!")
            continue
        

        print(calculate_compound_interest(p, i, n))
        print(calculate_compound_interest_recursive(p, i, n))
        print(format_string_output(calculate_compound_interest(p, i, n), 
              calculate_compound_interest_recursive(p, i, n)))
        break
            

Let me know any questions via a comment.

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