繁体   English   中英

如何使用 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?

我的任务是以两种方式计算储蓄账户中的金额并比较结果。 它提示用户输入原则,利率(百分比)和投资年限。我需要使用try-except块来验证输入,并使用while语句提示用户直到输入有效。 我在验证和过程中有问题。 当我输入无效时,它没有按预期打印相关的异常错误。function 部分没问题,忽略它们。 此外,“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!")

注意: finally 块在 try 或任何 except 块运行时运行。

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
            

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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