简化用户输入的万无一失,Python

Simplifying user-input foolproofing, Python

我有以下代码来确保用户在 python 中输入一个浮点数:

while True:
    try:
        some_variable = int(input("Input Prompt: "))
        break
    except ValueError:
        print("Please enter a whole number (in digits)")

代码工作正常,但我有一个程序需要很多这样的代码,我想知道是否有办法简化它。

即我不必使用:

while True:
    try:
        some_variable = int(input("Input Prompt: "))
        break
    except ValueError:
        print("Please enter a whole number (in digits)")

对于每个用户输入。如果能得到任何帮助,我将不胜感激。

好的,我对 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

再次感谢您的帮助。 另外,如果有人对代码有更多建议,请发表评论,我将不胜感激。

也许您可以使用 https://github.com/asweigart/pyinputplus 指定哪些范围或输入有效?