【问题标题】:TypeError while running argv Python code运行 argv Python 代码时出现 TypeError
【发布时间】:2017-07-19 09:47:00
【问题描述】:
from sys import argv

script, user_name = argv
prompt = '> '

print ("Hi %s, I'm the %s script.") % (user_name, script)
print ("I'd like to ask you a few questions.")
print ("Do you like me %s?") % user_name
likes = raw_input(prompt)

print ("Where do you live %s?") % (user_name)
lives = raw_input(prompt)

print ("What kind of computer do you have?")
computer = raw_input(prompt)

print """
Alright, so you said %r about liking me.
You live in %r. Not sure where that is.
And you have a %r computer. Nice.
""" % (likes, lives, computer)

在 PowerShell 中运行此 (Python 3) 代码时,我得到了

类型错误“%:'Nonetype' 和 'str' 的操作数类型不受支持”

这里有什么错误?

【问题讨论】:

  • 未来:请同时发布您看到的错误的完整堆栈跟踪。否则我们只需要猜测错误发生在哪里。如果你自己看,你可能已经看到错误出现在print调用的行上,因此它与argv或任何东西无关。
  • 这段代码好像很破。你用的是python3吗?但是不要使用打印功能(带括号),您使用raw_input。你确定它不是py2吗?
  • @PaulRooney 修复问题中的错误后,OP 可能会看到NameError 用于raw_input。
  • 你 not 在 Python 3 中运行 this 脚本。它会抛出 SyntaxError。请重新检查您问题中的代码是否与您实际运行的代码匹配并产生同样的问题。

标签: python python-3.x python-3.6


【解决方案1】:
print ("Hi %s, I'm the %s script.") % (user_name, script)

print 是 Python 3 中的一个函数,因此它的作用与您的预期不同。第一组括号属于print函数调用,所以你有的是这样的:

print("Hi %s, I'm the %s script.")  %  (user_name, script)
#    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^    
# only that is the argument to the print call

因此,如果您将其拆分为单独的语句,它将如下所示:

print_result = print("Hi %s, I'm the %s script.")
format_args = (user_name, script)

print_result % format_args

现在,调用 print() 不会返回任何内容,即 None。所以你基本上是在做以下事情:

None % format_args

这会导致您看到的确切错误。

您想要做的是确保字符串格式化发生在传递给print 调用的参数 中,如下所示:

print("Hi %s, I'm the %s script." % (user_name, script))

请注意,您不需要将字符串放在额外的括号中。因此,print 调用只有一个左括号,它在最后关闭。


正如 Paul Rooney 在 cmets 中指出的那样,一旦您修复了这些 print 调用,您可能会遇到 NameError 以供您使用 raw_input。 raw_input 在 Python 3 中不存在,因此您也需要修复它。另见this question on that topic。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-04
    • 2022-07-08
    • 1970-01-01
    • 1970-01-01
    • 2018-01-24
    • 2017-08-19
    • 2019-08-30
    相关资源
    最近更新 更多