3
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

什么接缝有问题?

PS 我搜索了该站点,但似乎所有有相同问题的人都有更高级的脚本,而我什么都不懂。

4

3 回答 3

4

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')
于 2013-01-03T01:16:30.980 回答
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') 的计算结果为布尔值 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.")
于 2013-01-03T01:18:43.610 回答
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()并将结果转换为小写。到那时,尝试传递您的提示字符串为时已晚。

于 2013-01-03T01:16:09.177 回答