gpt4 book ai didi

python - 类型错误 : 'str' object is not callable

转载 作者:太空宇宙 更新时间:2023-11-03 12:33:56 25 4
gpt4 key购买 nike

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 我搜索了该站点,但似乎所有遇到相同问题的人都有更高级的脚本,而我什么都不懂。

最佳答案

第一个错误在行中

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.")

关于python - 类型错误 : 'str' object is not callable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14131780/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com