MarkLutz编写Python第1章错误
我仔细阅读了MarkLutz的python编程书,在第一章中,当我试图运行脚本时,我总是遇到一个错误。以下是他在书中的代码:MarkLutz编写Python第1章错误,python,Python,我仔细阅读了MarkLutz的python编程书,在第一章中,当我试图运行脚本时,我总是遇到一个错误。以下是他在书中的代码: dbfilename = 'people-file' ENDDB = 'enddb.' ENDREC = 'endrec.' RECSEP = '=>' def storeDbase(db, dbfilename=dbfilename): "formatted dump of databse to flat
dbfilename = 'people-file'
ENDDB = 'enddb.'
ENDREC = 'endrec.'
RECSEP = '=>'
def storeDbase(db, dbfilename=dbfilename):
"formatted dump of databse to flat file"
dbfile = open(dbfilename, 'w')
for key in db:
print(key, file=dbfile)
for (name, value) in db[key].items():
print(name + RECSEP + repr(value), file=dbfile)
print(ENDREC, file=dbfile)
print(ENDDB, file=dbfile)
dbfile.close()
def loadDbase(dbfilename=dbfileame):
"parse data to reconstruct database"
dbfile = open(dbfilename)
import sys
sys.stdin = dbfile
db = {}
key = input()
while key != ENDDB:
rec = {}
field = input()
while field != ENDREC:
name, value = field.split(RECSEP)
rec[name] = eval(value)
field = input()
db[key] = rec
key = input()
return db
if __name__== '__main__':
for initdata import db
storeDbase(db)
当我运行脚本时,这是我不断遇到的错误:
-> Programming_Python python make_db_file.py
Welcome to Python! Lets do something cool
File "make_db_file.py", line 17
print(key, file=dbfile)
^
SyntaxError: invalid syntax
有人能帮我理解代码的错误吗
谢谢。我猜您正在使用两个不同版本的python。尝试升级到python 3,看看这是否有帮助: python 2:
>>> import sys
>>> sys.version
'2.7.6 (v2.7.6:3a1db0d2747e, Nov 10 2013, 00:42:54) \n[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)]'
>>> print('hi', file=open('file.txt', 'w'))
File "<stdin>", line 1
print('hi', file=open('file.txt', 'w'))
^
SyntaxError: invalid syntax
>>>
在python3中,
print
是一个函数,这意味着您可以传入参数。但是,在python2中,它是一个语句,意味着不能传入参数。我猜您使用的是两个不同版本的python。尝试升级到python 3,看看这是否有帮助:
python 2:
>>> import sys
>>> sys.version
'2.7.6 (v2.7.6:3a1db0d2747e, Nov 10 2013, 00:42:54) \n[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)]'
>>> print('hi', file=open('file.txt', 'w'))
File "<stdin>", line 1
print('hi', file=open('file.txt', 'w'))
^
SyntaxError: invalid syntax
>>>
在python3中,
print
是一个函数,这意味着您可以传入参数。但是,在python2中,它是一个语句,意味着不能传入参数。不要在python2中运行Python3代码。不要在python2中运行Python3代码。Downvoter,为什么要投反对票?(对所有其他人来说,计票是+1/-2)@user142900,如果这个答案对你有帮助,你介意点击我答案旁边的绿色复选框+1'并接受它吗?它给你+2的声誉:)它确实有帮助!但我无法超越它,因为我没有足够的因果报应。不知道该怎么办。@user142900没问题,你仍然可以点击我答案旁边的绿色复选框。**没关系,我记得。键入“python3命令或文件”。嗯**好吧,我又有麻烦了。如何在mac os x终端上运行python 3?我以前做过,但现在不行了。命令看起来像什么?否决票,为什么否决票?(对所有其他人来说,计票是+1/-2)@user142900,如果这个答案对你有帮助,你介意点击我答案旁边的绿色复选框+1'并接受它吗?它给你+2的声誉:)它确实有帮助!但我无法超越它,因为我没有足够的因果报应。不知道该怎么办。@user142900没问题,你仍然可以点击我答案旁边的绿色复选框。**没关系,我记得。键入“python3命令或文件”。嗯**好吧,我又有麻烦了。如何在mac os x终端上运行python 3?我以前做过,但现在不行了。这个命令看起来像什么?