TypeError:'str'对象不可调用

时间:2013-01-03 01:13:31

标签: python string while-loop

name = raw_input("Welcome soldier. What is your name? ")
print('Ok,', name, ' we need your help.')
print("Do you want to help us? (Yes/No) ")
ans = raw_input().lower()

while True:
    ans = raw_input().lower()("This is one of those times when only Yes/No will do!" "\n"  "So what will it be? Yes? No?")

    ans = raw_input().lower()
    if ans() == 'yes' or 'no':
        break
    if ans == "yes":
        print ("Good!")
    elif ans == "no":
        print("I guess I was wrong about you..." '\n' "Game over.")

当我回答这种情况时;

首先是空白行,然后再次按回车键;

  File "test.py", line 11, in <module>
    ans = raw_input().lower()("This is one of these times when only Yes/No will
do!" "\n" "So what will it be? Yes? No?")
TypeError: 'str' object is not callable

问题是什么?

P.S我搜索了网站,但它发现所有遇到相同问题的人都有更高级的脚本而且我什么都不懂。

3 个答案:

答案 0 :(得分:4)

第一个错误出现在行

ans = raw_input().lower()("This is one of those times when only Yes/No will do!"
                          "\n"  "So what will it be? Yes? No?")

lower()的结果是一个字符串,后面的括号表示左边的对象(字符串)被调用。因此,您得到错误。你想要

ans = raw_input("This is one of those times when only Yes/No will do!\n"
                "So what will it be? Yes? No?").lower()

此外,

if ans() == 'yes' or 'no':

不是你所期望的。同样,ans是一个字符串,括号表示左侧的对象(字符串)被调用。因此,您会收到错误。

此外,or是一个逻辑运算符。即使在ans之后删除括号,代码也会被评估为:

if (ans == 'yes') or ('no'):

由于非空字符串('no')的计算结果为boolean True,因此该表达式始终为True。你只想要

if ans in ('yes', 'no'):

此外,你想要取消最后一行。总而言之,尝试:

name = raw_input("Welcome soldier. What is your name? ")
print('Ok, ' + name + ' we need your help.')
ans = raw_input("Do you want to help us? (Yes/No)").lower()
while True:
    if ans in ('yes', 'no'):
        break
    print("This is one of those times when only Yes/No will do!\n")
    ans = raw_input("So what will it be? Yes? No?").lower()

if ans == "yes":
    print("Good!")
elif ans == "no":
    print("I guess I was wrong about you..." '\n' "Game over.")

答案 1 :(得分:3)

您需要raw_input("This is one of those times when only Yes/No will do!" "\n" "So what will it be? Yes? No?").lower()

执行raw_input().lower()时,已调用raw_input()并将结果转换为小写。到那时,尝试传递你的提示字符串为时已晚。

答案 2 :(得分:3)

TypeError: 'str' object is not callable通常表示您在字符串上使用()表示法,Python尝试将该str对象用作函数。例如"hello world"()"hello"("world")

我认为你的意思是:

ans = raw_input("This is one of those times...").lower()

另一个错误:

if ans() == 'yes' or 'no':

您必须单独检查这两个条件,

应该是:

 if ans == 'yes' or ans == 'no':
        break

或者更符合您想要的内容:

if ans in ('yes', 'no')