如何使用 try-except 块来验证输入,并使用 while 语句提示用户直到 Python 中的有效输入?

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?

我的任务是用两种方法计算储蓄账户中的金额并比较结果。提示用户输入原则,利率(百分比),年数invest.I需要用try-except块来验证输入,用while语句提示用户,直到输入有效.我在验证和过程中遇到问题。当我有无效输入时,它没有打印相关的异常错误,因为 expected.The 函数部分是好的,忽略它们。此外,“Going around again”应该在下一个提示输入之前打印,但我的出现在正确输入执行结束时。请你帮助我好吗?谢谢

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!")

注意:只要 try 或任何 except 块运行,finally 块就会运行。

Try-Except 块需要配对,展示比解释容易。

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
            

通过评论让我知道任何问题。