我是python的新手,我一直在尝试从Head First Python运行此代码。 我目前的Python 2.7.9Nester模块在Python中不工作
跑这里是代码:
from __future__ import print_function
import sys
import nester
man = []
other = []
try:
data = open('sketch.txt')
for each_line in data:
try:
(role, line_spoken) = each_line.split(':' , 1)
line_spoken = line_spoken.strip()
if role == 'Man':
man.append(line_spoken)
elif role == 'Other Man':
other.append(line_spoken)
except ValueError:
pass
data.close()
except IOError:
print('the data file is missing')
try:
with open('man_data.txt', 'w') as man_file:
print_lol(man, file = man_file)
with open('other_data.txt', 'w') as other_file:
print_lol(other, file = other_file)
man_file.close()
other_file.close()
except IOError as err:
print('File error: ' + str(err))
这里是巢代码:
from __future__ import print_function
import sys
def print_lol(the_list, indent=False, level=0, fh=sys.stdout):
for each_item in the_list:
if isinstance(each_item, list):
print_lol(each_item , indent, level+1, fh)
else:
if indent:
for tab_stop in range(level):
print("\t", end='', file=fh)
print(each_item, file=fh)
但我不断收到此错误:
Traceback (most recent call last):
File "C:\Users\Olusegun\Desktop\Python codes\HeadFirstPython\Chapter 3\data.py", line 30, in <module>
print_lol(man, file = man_file)
NameError: name 'print_lol' is not defined
请帮助
是很好......在每行的开头已经在它 – brw59
代码你太前添加一个额外的4位远离学习,*请*切换到Python 3. Python 2是过去,Py3是语言的现在和未来。除非你有第一个学习2的非常具体的原因,否则使用3.你可以在以后总是找到差异。 Py2可以教会你一些会妨碍你进步的坏习惯。HFP也使用Py3,IIRC。 – MattDMo