函数定义,TypeError

时间:2019-05-15 02:44:08

标签: python function typeerror

我编写了以下代码。当我输入1-5时,它运行良好,但是当我尝试输入a6之类的内容时,它将返回错误:

  

Python告诉“ TypeError:'str'对象不可调用”

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()

2 个答案:

答案 0 :(得分:2)

您正在将函数名a用作同名变量。更改函数或变量名称,它将起作用。

答案 1 :(得分:0)

  

Python告诉“ TypeError:'str'对象不可调用”

这意味着Python正在尝试调用局部变量a,即str

根据您的代码:

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

似乎您试图在先前的输入无效时再次调用a()函数以接受新的输入。您可以改为对函数的a()函数 outside 进行循环调用,当输入无效时将重复该调用。

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'
$