我有以下代码来确保用户在python中输入浮点值:
while True:
try:
some_variable = int(input("Input Prompt: "))
break
except ValueError:
print("Please enter a whole number (in digits)")
代码运行良好,但我有一个程序需要很多这样的代码,我想知道是否有一种方法可以简化它
ie我不必使用:
while True:
try:
some_variable = int(input("Input Prompt: "))
break
except ValueError:
print("Please enter a whole number (in digits)")
对于每个用户输入。如果能得到任何帮助,我将不胜感激。
也许您可以使用https://github.com/asweigart/pyinputplus指定哪些范围或输入是有效的?
好的,我对Thierry Lathuille的建议做了一些研究。我使用函数来简化代码。以下是供所有人使用的简化代码:
def int_input(prompt):
while True:
try:
variable_name = int(input(prompt))
return variable_name
except ValueError:
print("Please enter a whole number (in digits)")
def float_input(prompt):
while True:
try:
variable_name = float(input(prompt))
return variable_name
except ValueError:
print("Please enter a number (in digits)")
def yes_input(prompt):
while True:
variable_name = input(prompt).lower()
if variable_name in ["y", "yes"]:
return "yes"
elif variable_name in ["n", "no"]:
return "no"
else:
print("""Please enter either "yes" or "no": """)
while True:
print("Volume of a right circular cone")
print("Insert the radius and height of the cone below:")
one_third = 1 / 3
radius = float_input("Radius: ")
height = float_input("Perpendicular Height: ")
pi_confirm = yes_input("""The value of π is 22/7, "yes" or "no": """)
if pi_confirm == "yes":
pi = 22/7
if pi_confirm == "no":
pi = float_input("Type the value of pi, for eg ➡ 3.141592653589: ")
volume = one_third * pi * radius ** 2 * height
accuracy = int_input("How many decimal places do you want your answer to?: ")
print(f"""{volume:.{accuracy}f}""")
new_question = yes_input("""New question? "yes" or "no": """)
if new_question == "no":
break
再次感谢您的帮助。此外,如果有人对代码有更多建议,如果你留下评论,我将不胜感激。