无一例外地限制用户输入

Limiting user input without exceptions

我尝试了标准的“猜 运行dom 数字游戏”作为我在 python 中的第一个小项目,并决定稍微改进一下。我的目标是使程序能够抵抗用户输入导致的 ValueError 崩溃,同时使其尽可能灵活(我的微薄技能)。我 运行 解决了 input() 函数只返回字符串的问题,而我的具有多级异常的解决方案看起来非常笨拙和冗长。

我有这个功能,可以询问用户他们想要猜多少次,然后 returns 给出答案。

def guess_max_asker():
    while True:

        guess_max_temp = input("How many guesses do you want? (1 - 10)\n> ")

        try:  # lvl 1 checks if input is a valid int
            guess_max_temp2 = int(guess_max_temp) #ugly 
            if 11 > guess_max_temp2 > 0:
                print(f"Ok! You get {guess_max_temp2} tries!")
                return guess_max_temp2
            else:
                print("That's not a valid number..")
                continue

        except ValueError:
            print("ValueError!") # It's alive!
            try:  # lvl 2 checks if input is float that can be rounded
                guess_max_temp2 = float(guess_max_temp)
                print(f"I asked for an integer, so I'll just round that for you..")
                return round(guess_max_temp2)

            except ValueError:  # lvl 3 checks if input is a valid string that can be salvaged
                emergency_numbers_dict = {"one": 1, "two": 2, "three": 3, "four": 4, "five": 5,
                                          "six": 6, "seven": 7, "eight": 8, "nine": 9, "ten": 10}
                if guess_max_temp.lower() in emergency_numbers_dict:
                    print(f'I asked for an integer, but I will let "{guess_max_temp}" count..')
                    return emergency_numbers_dict[guess_max_temp]
                else:
                    print("That's not a valid answer..")
                    continue

guess_max = guess_max_asker()

有没有比“while True”循环更优雅的方法?我尝试并未能找到一种方法来使 Python 重新运行类似于“继续”和“while”循环的简单 if 语句。如果我可以让 Python 将输入识别为不同的类型,我可以尝试使用 isinstance(),但我不知道该怎么做。我确信答案显而易见,但相信我,我已经尝试过了。

“围绕 try/except 循环”的方法非常标准,所以您走在正确的轨道上。

您可以使用以下辅助函数稍微清理一下:

def input_int(prompt):
    while True:
        response = input(prompt)
        try:
            return int(response)
        except ValueError:
            print("ValueError -- try again")

你可以像这样使用:

user_int = input_int("Input an integer: ")
print("Accepted: ", user_int)

示例:

Input an integer: c
ValueError -- try again

Input an integer: 1.2
ValueError -- try again

Input an integer: 1
Accepted:  1

尽可能坚持你原来的代码,你可以试试:

def guess_max_asker():
    while True:
        guess_max_temp = input("How many guesses do you want? (1 - 10)\n> ")
        if guess_max_temp.isnumeric():
            if int(guess_max_temp)>11:
                print("That's not a valid number")
            else:
                return int(guess_max_temp)
        else:
            emergency_numbers_dict = {"one": 1, "two": 2, "three": 3, "four": 4, "five": 5,
                                      "six": 6, "seven": 7, "eight": 8, "nine": 9, "ten": 10}
            if guess_max_temp not in emergency_numbers_dict:
                print("That's not a valid answer..")
            else:
                print(f'I asked for an integer, but I will let "{guess_max_temp}" count..')
                return emergency_numbers_dict[guess_max_temp]     
        
guess_max = guess_max_asker()