Try Except Python 的多用户输入
Multiple User Input with Try Except Python
我的任务是创建一个 python 程序,该程序将要求用户输入并计算每月的贷款还款额,这是我必须计算的公式:Formula。这样做并不太难,但是作为奖励,导师要求尝试让用户输入 'unbreakable',这意味着如果输入了预期之外的任何值,它不会破坏程序。我认为这可以通过 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")
您认为我可以如何修改这段代码,使其更简洁、更短、更高效,而无需对每个用户输入进行尝试?
使用所有相关输入提取函数中的重复过程。
我在最终输出中添加了一些格式以避免小数点太多
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))
将其模块化,并使用处理输入和循环的通用函数,直到用户输入要求的内容。
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 字符串非常漂亮和优雅 - 只需将值或计算插入花括号内即可。根据评论中的建议,您可能希望使用所示的舍入函数或格式选项显示两位小数。
一种更符合 Python 风格的变量命名方式是
- 金额而不是 A
- 比率而不是 R
- num_years 而不是 N
等等。
我的任务是创建一个 python 程序,该程序将要求用户输入并计算每月的贷款还款额,这是我必须计算的公式:Formula。这样做并不太难,但是作为奖励,导师要求尝试让用户输入 'unbreakable',这意味着如果输入了预期之外的任何值,它不会破坏程序。我认为这可以通过 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")
您认为我可以如何修改这段代码,使其更简洁、更短、更高效,而无需对每个用户输入进行尝试?
使用所有相关输入提取函数中的重复过程。
我在最终输出中添加了一些格式以避免小数点太多
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))
将其模块化,并使用处理输入和循环的通用函数,直到用户输入要求的内容。
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 字符串非常漂亮和优雅 - 只需将值或计算插入花括号内即可。根据评论中的建议,您可能希望使用所示的舍入函数或格式选项显示两位小数。
一种更符合 Python 风格的变量命名方式是
- 金额而不是 A
- 比率而不是 R
- num_years 而不是 N 等等。