【问题标题】:exercise 14 learning python the hard way练习 14 艰难地学习 Python
【发布时间】:2013-01-23 17:54:18
【问题描述】:

这是练习中的代码:

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) 

现在我正在运行 Windows 7,并且正在使用代码运行 CMD 行

python ex14.py myname

我收到此错误:

File "ex14.py", line 3
Python ex14.py, user_name
SyntaxError: invalid syntax

【问题讨论】:

  • @lc ... err 我应该认为问题是'为什么它在字符串格式化代码的第 3 行出错? (顺便说一句,我相信现在不推荐使用 % 进行字符串格式化,您应该使用 format.()
  • 脚本,user_name = argv 正在解包数组。我会在此之前打印 argv 并确保它是您所期望的。还要检查你的空白。顺便说一句,这在我的 linux 机器上工作得很好。
  • @PaulSullivan -- 虽然.format 现在更强大且值得学习,但 % 格式仍然存在并且没有被弃用。

标签: python windows python-2.7


【解决方案1】:

可见字符中有nothing wrong with the script

  • 检查源中没有 Unicode 空格,例如 NO-BREAK SPACE 字符。在同一目录中创建一个新脚本:
with open('ex14.py', 'rb') as file:
     s = file.read()
     print(repr(s)[:60])
     u = s.decode('ascii') # this line should raise an error
                           # if there are bytes outside ascii
  • 检查 Python 版本以确保它是 2.7(以正确解释错误消息):

    $ python -V
    
  • 检查文件是否未使用 utf-16/32 编码保存(@abarnert 在 cmets 中的建议)。

    在这种情况下,您应该在repr() 结果中看到许多零字节'\x00'

【讨论】:

  • +1。鉴于这是 Windows,另一种可能性是脚本保存为 UTF-16-LE(而不是与 ASCII 兼容的东西,如 UTF-8)。
  • @abarnert:好点。在 Ubuntu 上,utf-16-le 生成带有 OP 代码的 NameError
【解决方案2】:

安装python2并在终端输入

python2 ex14.py 我的名字

解决问题 您正在最新的 python 版本中运行脚本 并且您的代码语法适用于 python 版本 2 这就是您收到语法错误的原因

【讨论】:

    猜你喜欢
    • 2015-05-01
    • 2013-04-06
    • 2011-12-04
    • 2016-06-28
    • 1970-01-01
    • 1970-01-01
    • 2014-08-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多