我在python 3中制作了一个简单的mad libs程序,用户在其中输入名词和代词,并且该程序应该打印出用户的输入。
这是我的代码:
print ("Welcome to Mad Libs. Please enter a word to fit in the empty space.")
proper_noun = input("One day _________ (Proper Noun)").lower()
ing_verb = input("Was __________ (Verb + ing) to the").lower()
noun1= input("to the _________ (Noun)").lower()
pronoun1 = input("On the way, _____________ (Pronoun)").lower()
noun2 = input("Saw a ________ (Noun).").lower
pronoun2 = input("This was a surprise so ________ (Pronoun)").lower()
verb2 = input("_________ (verb) quickly.").lower()
#Asks user to complete the mad libs
print ("One day " + proper_noun)
print ("Was " + ing_verb + " to the")
print (noun1 + ". " + "On the way,")
print (pronoun1 + " saw a " + noun2 + ".")
print ("This was a surprise")
print ("So " + pronoun2 + " " + verb2 + " quickly.")
获取此错误代码: TypeError: Can't convert 'builtin_function_or_method' object to str implicitly
在这行上:
print (pronoun1 + " saw a " + noun2 + ".")
对python来说还算是新手,所以我不完全确定此错误的含义以及如何解决它,有人可以向我解释此错误代码吗?
问题出在名词2变量上
noun2 = input("Saw a ________ (Noun).").lower
您要为其分配功能.lower,而不是调用它的结果。您应该将函数调用为.lower()-
noun2 = input("Saw a ________ (Noun).").lower()
对于未来的读者
当遇到诸如--的问题TypeError: Can't convert 'builtin_function_or_method' object to str implicitly
时,尝试使用+
运算符连接变量时包含字符串。
基本上,问题在于变量之一实际上是函数/方法,而不是实际的字符串。
当您尝试在字符串上调用某个函数,但是却错过了()
语法(如OP的情况)时,通常会发生这种情况(如OP的情况)-
name = name.lower #It should have been `name.lower()`
没有()
语法,您将只是将函数/方法分配给变量,而不是调用函数的实际结果。要调试此类问题,您可以检查出分配给变量的行,在抛出错误的行中使用该行,并检查是否错过了调用任何函数的过程。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句