函数定义,类型E

2024-10-03 17:26:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我写了下面的代码。当我键入1-5时,它运行良好,但当我尝试键入a6之类的内容时,它会返回一个错误:

Python tell "TypeError: 'str' object is not callable"

def a():
    a = input("Type 1-5\n")
    if a == '1':
        print("Your abnswer is \'1'")
    elif a == '2':
        print("Your abnswer is \'2'")
    elif a == '3':
        print("Your abnswer is \'3'")
    elif a == '4':
        print("Your abnswer is \'4'")
    elif a == '5':
        print("Your abnswer is \'5'")
    else:
        a()

a()

Tags: 代码内容your键入objectis错误not
2条回答

您正在将函数名a作为同名变量重用。更改函数或变量名,它就会工作

Python tell "TypeError: 'str' object is not callable"

这意味着Python试图调用局部变量a,它是一个str

从您的代码:

def a():
    a = input("Type 1-5\n")
    ...
    else:
        a()

似乎您正在尝试再次调用a()函数,以便在前一个输入无效时接受新的输入。相反,可以在函数的外部循环调用a()函数,当输入无效时,该函数将重复

def get_input():
    a = input("Type 1-5\n")

    if a == '1':
        print("Your answer is \'1'")
    elif a == '2':
        print("Your answer is \'2'")
    elif a == '3':
        print("Your answer is \'3'")
    elif a == '4':
        print("Your answer is \'4'")
    elif a == '5':
        print("Your answer is \'5'")
    else:
        print("Invalid input")
        return False  # we did not get a valid input

    return True  # we successfully received a valid input

is_valid_input = False
while not is_valid_input:
    is_valid_input = get_input()

注意,我还将函数重命名为get_input,以使其更清晰。它还将它与同名的局部变量(a)区分开来,这有助于避免出现那种TypeError,因为更清楚的是哪个是str,哪个是函数

$ python3 test.py
Type 1-5
6
Invalid input
Type 1-5
a
Invalid input
Type 1-5
1
Your answer is '1'
$

相关问题 更多 >