您的位置:首页 > 编程语言 > Python开发

《Python核心编程》第二版课后习题——第三章(记录自己做的习题,可能有误)

2013-08-26 14:18 549 查看
3–1. 标识符。为什么Python 中不需要变量名和变量类型声明?

【答】 python中的赋值语句会在运行时动态的根据右边的类型确定变量的类型,变量也是当时分配的空间,并且,若该变量已经存在,其类型并不固定,可以在第二次赋值时改变成其右边的类型。

3–2. 标识符。为什么Python 中不需要声明函数类型?

【答】 和第一个问题类似,python会在运行时根据返回值的形式去定义函数类型。

3–3. 标识符。为什么应当避免在变量名的开始和和结尾使用双下划线?

【答】 变量名 __xxx__ 是python中系统定义名字的格式,正如Java中类的第一个字母要大写一样,属于约定范畴,虽然不会报错但大家约定俗成的避免了。

3–4. 语句。在Python 中一行可以书写多个语句吗?

【答】 可以,语句之间用";"隔开。

3–5. 语句。在Python 中可以将一个语句分成多行书写吗?

【答】 可以,可在前一行末尾加符号”\”。例外:'''....''',"""......"""

3–6. 变量赋值

(a)赋值语句 x, y, z = 1, 2, 3 会在 x、y、z 中分别赋什么值?

(b)执行z, x, y = y, z, x 后,x、y、z 中分别含有什么值?

【答】

(a) x,y,z=1,2,3 <==> x=1;y=2;z=3

(b) x=3,y=1,z=2

3–7. 标识符。下面哪些是Python 合法的标识符?如果不是,请说明理由!在合法的标

识符中,哪些是关键字?

【答】

合法:int32    printf    print    _print    this    self    __name__    bool    true    type    thisIsAVar    R_U_Ready    Int    True    if    do    acess    _

非法:40XL    $aving$    0x40L    big-daddy    thisIsn’tAVAR    counter-1

关键字:print    if   

下面的问题涉及了 makeTextFile.py 和readTextFile.py 脚本。

3–8. Python 代码。将脚本拷贝到您的文件系统中,然后修改它。可以添加注释,修改

提示符(‘>’太单调了)等等,修改这些代码,使它看上去更舒服。

【答】 读了好几次没读懂这道题想干嘛,我就尝试着修改了一点。

#!/usr/bin/env python
'makeTextFile.py -- create text file'
import os
ls = os.linesep
# get filename
fname = raw_input("Enter a file name: ")
while True:
if os.path.exists(fname):
print "ERROR: '%s' already exists" % fname
fname = raw_input("Enter a file name: ")
else:
break
# get file content (text) lines
all = []
print "\nEnter lines ('.' by itself to quit).\n"
# loop until user terminates input
line=1
while True:
print line,
entry = raw_input(': ')
if entry == '.':
break
else:
line+=1
all.append(entry)
# write lines to file with proper line-ending
fobj = open(fname, 'w')
fobj.writelines(['%s%s' % (x, ls) for x in all])
fobj.close()
print 'DONE!'

注:只是在最左侧添加了行数,另外将’>’改成’:’,还是想说读不懂题目意思。

3–9. 移植。 如果你在不同类型的计算机系统中分别安装有Python, 检查一下,os.linesep 的值是否有不同。 记下操作系统的类型以及 linesep 的值。

【答】 没有在不同的os里尝试过,理论上:Unix平台是’\n’;DOS或Win32平台是’\r\n’

3–10. 异常。使用类似readTextFile.py 中异常处理的方法取代 readTextFile.py,makeTextFile.py 中对os.path.exists() 的调用。反过来, 用os.path.exists() 取代readTextFile.py 中的异常处理方法。

【答】修改后的makeTextFile.py

#!/usr/bin/env python
'makeTextFile.py -- create text file'
import os
ls = os.linesep
# get file content (text) lines
all = []
# get filename
fname = raw_input("Enter a file name: ")
while True:
try:
fobj = open(fname,'r')
print "File is exist:"
fobj.close()
fname = raw_input("Enter a file name: ")
except:
# loop until user terminates input
print "\nEnter lines ('.' by itself to quit).\n"
line=1
while True:
print line,
entry = raw_input(': ')
if entry == '.':
break
else:
line+=1
all.append(entry)
break
# write lines to file with proper line-ending
fobj = open(fname, 'w')
fobj.writelines(['%s%s' % (x, ls) for x in all])
fobj.close()
print 'DONE!'


修改后的readTextFile.py

#!/usr/bin/env Python
'readTextFile.py -- read and display text file'
import os
# get filename
fname = raw_input('Enter filename: ')
print
# attempt to open file for reading
if os.path.exists(fname):
fobj = open(fname, 'r')
# display contents to the screen
for eachLine in fobj:
print eachLine,
fobj.close()
else:
print 'file is not exist.'


3–11.字符串格式化 不再抑制readTextFile.py 中 print 语句生成的 NEWLINE 字符,修改你的代码, 在显示一行之前删除每行末尾的空白。这样, 你就可以移除 print 语句末尾的逗号了。提示: 使用字符串对象的 strip()方法

【答】修改后的readTextFile.py

#!/usr/bin/env Python

'readTextFile.py -- read and display text file'
import os
import string
# get filename
fname = raw_input('Enter filename: ')
print

# attempt to open file for reading

if os.path.exists(fname):
fobj = open(fname, 'r')

# display contents to the screen
for eachLine in fobj:
print string.strip(eachLine)
fobj.close()
else:
print 'file is not exist.'


3–12. 合并源文件。将两段程序合并成一个,给它起一个你喜欢的名字,比方readNwriteTextFiles.py。让用户自己选择是创建还是显示一个文本文件。

【答】

#!/usr/bin/env Python

def read():
'readTextFile.py -- read and display text file'
import os
import string
# get filename
fname = raw_input('Enter filename: ')
print

# attempt to open file for reading

if os.path.exists(fname):
fobj = open(fname, 'r')

# display contents to the screen
for eachLine in fobj:
print string.strip(eachLine)
fobj.close()
else:
print 'file is not exist.'

def make():
'makeTextFile.py -- create text file'

import os
ls = os.linesep

# get file content (text) lines
all = []

# get filename
fname = raw_input("Enter a file name: ")

while True:
try:
fobj = open(fname,'r')
print "*** file open error:"
fobj.close()
fname = raw_input("Enter a file name: ")
except:
# loop until user terminates input
print "\nEnter lines ('.' by itself to quit).\n"
line=1
while True:
print line,
entry = raw_input(': ')
if entry == '.':
break
else:
line+=1
all.append(entry)
break
# write lines to file with proper line-ending
fobj = open(fname, 'w')
fobj.writelines(['%s%s' % (x, ls) for x in all])
fobj.close()
print 'DONE!'
notice =  '''Enter a character to make your choice:
'm' : make a file
'r' : read a file
other characters : quit of the function
: '''
choice = raw_input(notice)
if choice == 'm':
make()
elif choice == 'r':
read()
else:
print 'exiting of the function...'
exit(0)


 

3–13. 添加新功能。将你上一个问题改造好的 readNwriteTextFiles.py 增加一个新功能:允许用户编辑一个已经存在的文本文件。 你可以使用任何方式,无论是一次编辑一行,还是一次编辑所有文本。需要提醒一下的是, 一次编辑全部文本有一定难度,你可能需要借助 GUI工具包或一个基于屏幕文本编辑的模块比如 curses 模块。要允许用户保存他的修改(保存到文件)或取消他的修改(不改变原始文件),并且要确保原始文件的安全性(不论程序是否正常关闭)。

【答】暂时没做.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐