[英]Multiple User Input with Try Except Python
我的任務是創建一個 python 程序,該程序將要求用戶輸入並計算每月的貸款還款額,這是我必須解決的公式:公式。 這樣做並不難,但是作為獎勵,導師要求嘗試使用戶輸入“牢不可破”,這意味着如果輸入了預期之外的任何值,它不會破壞程序。 我認為這可以通過 Try except 輕松完成,這就是我所做的,但是我相信我的代碼可以以更簡潔的方式編寫,而不是對每個輸入進行 Try except 如下:
err = "Please enter a number only!!"
while True:
try:
A = int(input("How much were you loaned? "))
except ValueError:
print(err)
continue
else:
break
while True:
try:
R = float(input("At what monthly rate interest? ")) / 100
except ValueError:
print(err)
continue
else:
break
while True:
try:
N = int(input("And how many years is the loan for? "))
except ValueError:
print(err)
continue
else:
break
RA = R * A
RN = 1 - (1 + R) ** -N
P = RA / RN
print("You will pay £", P, "yearly", "or, £", P / 12, "monthly")
我覺得好像用戶輸入可以放入 For 循環,或者所有這些都放入一個 Try except 塊中? 考慮之后,我將所有輸入放入一個 Try except 塊中,但是一旦您未能正確輸入用戶輸入的預期數據,它就會回到開頭,而不是您所提出的問題。 這不是我想要的。 看一看:
err = "Please enter a number only!!"
while True:
try:
A = int(input("How much were you loaned? "))
R = float(input("At what monthly rate interest? ")) / 100
N = int(input("And how many years is the loan for? "))
except ValueError:
print(err)
continue
else:
break
RA = R * A
RN = 1 - (1 + R) ** -N
P = RA / RN
print("You will pay £", P, "yearly", "or, £", P / 12, "monthly")
您認為我如何修改此代碼以使其更簡潔、更短、更高效,而無需對每個用戶輸入進行 Try except?
對其進行模塊化,並使用一個通用函數來處理輸入和循環,直到用戶輸入所要求的內容。
def get_num(prompt="Enter number: "):
"""
(str) -> num
Outputs a prompt and loops until a valid number is
entered by the user, at which point that value is
returned and the function terminates
"""
while True:
num = input(prompt)
try:
num = float(num)
return num
except:
print("Must enter a valid number")
def do_calc():
"""(None) -> None
Get user input, perform calculations and output results
"""
A = int(get_num("How much were you loaned? "))
R = get_num("At what monthly rate interest? ") / 100
N = int(get_num("And how many years is the loan for? "))
RA = R * A
RN = 1 - (1 + R) ** -N
P = RA / RN
print(f"You will pay £{round(P, 2)} yearly or £{P/12:.2f} monthly")
do_calc()
使用 Python 3 中的 f-string 非常好和優雅 - 只需將值或計算插入花括號內。 根據評論中的建議,您可能希望使用如圖所示的舍入函數或格式選項顯示兩位小數。
命名變量的更pythonic方法是
使用所有相關輸入提取函數中的重復過程。
我在最終輸出中添加了一些格式以避免小數點過多
def get_value(message, func, denominator = 1):
try_again = True
v = None
while try_again:
try:
v = func(input(message))/denominator
except ValueError:
print("Please enter a number only!!")
else:
try_again= False
return v
A = get_value("How much were you loaned? ", int)
R = get_value("At what monthly rate interest? ", float, denominator=100.0)
N = get_value("And how many years is the loan for? ", int)
RA = R * A
RN = 1 - (1 + R) ** -N
P = RA / RN
print("You will pay £ {:.2f} yearly or £ {:.2f} monthly".format(P, P / 12))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.