【问题标题】:getting error with learn python the hard way exercise 14学习 python 遇到错误练习 14
【发布时间】:2012-04-07 13:57:45
【问题描述】:

我正在关注 zed shaw 的 learn python hard way 和练习 14。这是我正在谈论的程序:

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 e:\python\ex14.py

我收到以下错误消息:

Traceback (most recent call last):
File "e:\python\ex14.py", line 3, in (module)
script, user_name=argv
ValueError: need more than 1 value to unpack.

现在,我不确定问题出在哪里。唯一的原因可能是我输入的是文件路径,而不是只输入文件名。

【问题讨论】:

  • 如果您的目标是学习 Python,我建议您尝试更传统的教程。
  • 你能提供一个更传统的教程的链接吗?我是新来的,只是遵循这个网站的一些建议。到目前为止,我喜欢这个教程,但也希望看到一个传统的教程。
  • @agf Learn Python the Hard Way 不是传统的教程吗?

标签: python


【解决方案1】:

这个脚本需要在命令行中接受一个参数。你没有提供一个。

在终端输入python e:\python\ex14.py YourNameHere

【讨论】:

  • 哇!有效!但我无法理解发生这种情况的原因或程序中的哪一行导致这种情况发生。你能解释一下吗?
  • sys.argv 是一个列表,其中包含在命令行中传递给 Python 解释器的所有参数,以脚本名称开头。 script, user_name = argvargv 的第一个元素分配给script,将第二个元素分配给user_name。当你在没有参数的情况下运行它时,没有第二个元素,所以你得到了一个运行时错误。
  • user_name = argv 如果您将 Python 作为第一语言学习,我会推荐一个解释 argvargc 含义的教程。
  • 嗯,我想我明白了。不过,必须了解更多关于 argv 命令的信息。谢谢你的解释。
  • @Nunoxic Python 中没有argc。不需要,因为 Python 列表(与 C 数组不同)知道它们自己的长度。
猜你喜欢
  • 1970-01-01
  • 2015-05-01
  • 2014-08-16
  • 2013-05-16
  • 2013-04-06
  • 2011-12-04
  • 2016-06-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多