簡體   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