head first python菜鸟学习笔记(第四章)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了head first python菜鸟学习笔记(第四章)相关的知识,希望对你有一定的参考价值。
1,p124,错误:NameError: name ‘print_lol‘ is not defined
要想文件内如图显示,需要把调用BIF print()改为调用第二章的nester模块中的print_lol()函数,因此需要导入nester模块。
首先需要修改第二章nester模块中的print_lol()函数并更新该模块,更新方法如图:
然后在sketch.py中调用print_lol()函数。
1 ‘‘‘ 2 修改时间:0919 3 修改内容:把调用BIF print()改为调用第二章的nester模块中的print_lol()函数,需要导入nester模块 4 ‘‘‘ 5 import nester 6 7 man=[] 8 other=[] 9 try: 10 data=open(‘sketch.txt‘) 11 for each_line in data: 12 try: 13 (role,line_spoken)=each_line.split(‘:‘,1) 14 line_spoken=line_spoken.strip() 15 if role==‘Man‘: 16 man.append(line_spoken) 17 elif role==‘Other Man‘: 18 other.append(line_spoken) 19 except ValueError: 20 pass 21 data.close() 22 except IOError: 23 print(‘The datafile is missing!‘) 24 25 try: 26 with open(‘man_data.txt‘,‘w‘) as man_file,open(‘other_data.txt‘,‘w‘) as other_file: 27 print_lol(man,fh=man_file) 28 print_lol(other,fh=other_file) 29 except IOError as err: 30 print(‘File Error:‘+str(err))
这时会报错:
原因:
调用模块的函数时,格式为“模块名.函数名()”
因此代码更改为:
1 ‘‘‘ 2 修改时间:0919 3 修改内容:把调用BIF print()改为调用第二章的nester模块中的print_lol()函数,需要导入nester模块 4 注意:调用print_lol时,需要把模块名加上,nester.print_lol(),而不是直接调用print_lol(). 5 ‘‘‘ 6 import nester 7 8 man=[] 9 other=[] 10 try: 11 data=open(‘sketch.txt‘) 12 for each_line in data: 13 try: 14 (role,line_spoken)=each_line.split(‘:‘,1) 15 line_spoken=line_spoken.strip() 16 if role==‘Man‘: 17 man.append(line_spoken) 18 elif role==‘Other Man‘: 19 other.append(line_spoken) 20 except ValueError: 21 pass 22 data.close() 23 except IOError: 24 print(‘The datafile is missing!‘) 25 26 try: 27 with open(‘man_data.txt‘,‘w‘) as man_file,open(‘other_data.txt‘,‘w‘) as other_file: 28 nester.print_lol(man,fh=man_file) 29 nester.print_lol(other,fh=other_file) 30 except IOError as err: 31 print(‘File Error:‘+str(err))
以上是关于head first python菜鸟学习笔记(第四章)的主要内容,如果未能解决你的问题,请参考以下文章
Head First Python(如何向PYPI发布你的代码)学习笔记