TypeError: in python in custom input function, exception handling

TypeError: in python in custom input function, exception handling

在 python 中创建 guess_the_number 游戏时,我想在用户输入无效数字时捕获异常,即在将输入的字符串类型转换为整数时出现 ValueError,我创建了一个 takeInput()功能。 它工作正常,除了当我引发异常并在那之后输入有效数字时,我得到一个 TypeError。

import random
randInt = random.randint(1, 100)
count = 1
print("RandInt: " + str(randInt))


def takeInput(message):
    userInput = input(message)
    try:
        userInput = int(userInput)
        print("takeInput try " + str(userInput)) #This line is printing correct value every time
        return userInput
    except ValueError as e:
        takeInput("Not a valid number, try again: ")


userInput = takeInput("Please enter a number: ")

while(not(userInput == randInt)):
    print("while loop " + str(userInput)) #I am receiving a none value after I raise an exception and then enter a valid number
    if(userInput < randInt):
        userInput = takeInput("Too small, try again : ")
    else:
        userInput = takeInput("Too large, try again : ")
    count += 1

print("Congratulations, you guessed it right in " + str(count) + " tries.")

你需要return函数发生异常时的值。由于您没有 returning 任何东西,因此默认情况下 returns None 即使函数被调用也是如此。

def takeInput(message):
    userInput = input(message)
    try:
        userInput = int(userInput)
        print("takeInput try " + str(userInput)) #This line is printing correct value every time
        return userInput
    except ValueError as e:
        return takeInput("Not a valid number, try again: ")

一些与错误无关的事情,

  • 尝试在 python 中使用 snake_case 而不是驼峰命名法。
  • f 字符串非常好,print(f"takeInput try {userInput}")
  • 考虑while userInput != randInt: