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

查看:45
本文介绍了如何使用 try-except 块来验证输入,并使用 while 语句来提示用户直到 Python 中的有效输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的任务是通过两种方式计算储蓄账户中的金额并比较结果.它提示用户输入原则、利率(百分比)和投资年限.我需要使用 try-except 块来验证输入,并使用 while 语句来提示用户直到输入有效.我在验证和过程中遇到问题.当我输入无效时,它没有按预期打印相关的异常错误.功能部分没问题,只需忽略它们.还有,《再转》应该在下一个提示输入之前打印,但我的出现在正确输入执行结束时.请你帮助我好吗?谢谢.

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

推荐答案

注意:只要 try 或 any except 块运行,Finally 块就会运行.

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

Try-Except 块需要配对,显示比解释更容易.

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.

这篇关于如何使用 try-except 块来验证输入,并使用 while 语句来提示用户直到 Python 中的有效输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆