类型错误:“str”对象不可调用

Lon*_*rts 5 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.")
Run Code Online (Sandbox Code Playgroud)

当我回答时,就会发生这种情况;

首先是一个空行,然后如果我再次按回车键;

  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
Run Code Online (Sandbox Code Playgroud)

到底是什么问题呢?

PS 我搜索了该网站,但似乎所有有同样问题的人都有更高级的脚本,而我什么也不明白。

phi*_*hag 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?")
Run Code Online (Sandbox Code Playgroud)

的结果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()
Run Code Online (Sandbox Code Playgroud)

还,

if ans() == 'yes' or 'no':
Run Code Online (Sandbox Code Playgroud)

不符合您的预期。同样,ans是一个字符串,括号意味着调用左侧的对象(字符串)。因此,你会得到你的错误。

另外,or是一个逻辑运算符。即使删除了后面的括号ans,代码也会被计算为:

if (ans == 'yes') or ('no'):
Run Code Online (Sandbox Code Playgroud)

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

if ans in ('yes', 'no'):
Run Code Online (Sandbox Code Playgroud)

此外,您想要取消最后几行的缩进。总而言之,尝试:

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.")
Run Code Online (Sandbox Code Playgroud)

  • @AdrianLarsson 更新了完整的解决方案。 (2认同)