我的代码行中的字符串格式有什么问题,为什么它会说:TypeError:'NoneType'对象不可调用?

2021-10-17 15:27:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我最近刚开始编写代码,遇到了这个我似乎无法解决的问题。这是我的密码:

name = input("What is your name? ")
quest = input("What is your quest? ")
color =input("What is your favorite color? ")
print ("Ah, so your name is %s, your quest is %s, ") \
("and your favorite color is %s." % (name, quest, color))

这就是问题所在:

line 6, in <module>
  ("and your favorite color is %s.") % (name, quest, color)
TypeError: 'NoneType' object is not callable
3条回答
网友
1楼 ·

问题是没有正确使用行分隔运算符,因此将print的结果None视为可调用的。你知道吗

请看以下内容:

print ("Ah, so your name is %s, your quest is %s, ")

将打印:

Ah, so your name is %s, your quest is %s,

并且调用print将返回None,因此您将拥有以下代码:

None("and your favorite color is %s." % (name, quest, color))

产生了这个错误。你知道吗

您可以通过以下方法解决此问题:

print ("Ah, so your name is %s, your quest is %s, "
    "and your favorite color is %s." % (name, quest, color))

如果您使用的是python3.6+,我强烈建议您使用f-string:

name = input("What is your name? ")
quest = input("What is your quest? ")
color = input("What is your favorite color? ")

print(f"Ah, so your name is {name}, your quest is {quest}, and your favorite color is {color}")

注意使用f字符串如何提高代码的可读性。你知道吗

网友
2楼 ·

去掉多余的parethes

print ("Ah, so your name is %s, your quest is %s, \

and your favorite color is %s." % (name, quest, color))
网友
3楼 ·

使用.format()或偶数formatted string interpolation

name = input("What is your name? ")
quest = input("What is your quest? ")
color =input("What is your favorite color? ")
print ("Ah, so your name is {}, your quest is {}, and your favorite color is {}"
       .format(name, quest, color))

或者

print (f"Ah, so your name is {name}, your quest is {quest}, "\
       "and your favorite color is {color}")

用于:

What is your name? What is your quest? What is your favorite color? Ah, so your name is a, your quest is b, and your favorite color is c

独行:

相关问题