Python核心编程(第二版)第三章练习题

来源:互联网 发布:html 按钮代码运行php 编辑:程序博客网 时间:2024/05/17 09:12

3.8

3-1

标识符。为什么 Python 中不需要变量名和变量类型声明?

答:因为Python语言中,对象的类型和内存占用都是运行时确定的。在创建时候,解释器其会根据语法和右侧的操作数来决定新对象的类型。在对象创建后,一个该对象的引用会被复制给左侧的变量。


3-2

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

答:简单理解为和变量名和变量类型是一样的。


3-3

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

答:因为下划线对解释器有着特殊的意义,而且是内建标识符的符号。


3-4

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

答:可以。

print("Pyhton");print("very well")

3-5

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

答:可以。

print("Hello\good")

3-6

变量赋值
(a)赋值语句 x, y, z = 1, 2, 3 会在 x、y、z 中分别赋什么值?
(b)执行 z, x, y = y, z, x 后,x、y、z 中分别含有什么值?

答(a):x=1,y=2,z=3
答(b):z=2,x=3,y=1


3-7

标识符。下面哪些是 Python 合法的标识符?如果不是,请说明理由!在合法的标识符中,哪些是关键字?
这里写图片描述

答:

分类 包含 合法标识符 int32、_print、bool、if、this、true、thisIsAVar、do、self、R_U_Ready、printf、__name__、Int、access、print、type、True、_ 关键字 bool、if、print、type、True 非法标识符 thisIs’tAVar、40XL、$aving$、big—daddy、counter-1、2hot2touch、0x40L

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

makeTextFile.py(Python3.0版本下的编写)

# coding=utf-8"makeTextfile.py -- create text file"import osls = os.linesepwhile True:    fname = input("please input your file name: ")    if os.path.exists(fname):        print("ERROR:'%s'already exists" % fname)    else:        breakall = []print("\nEnter lines('.' by iteself to quit).\n")while True:    entry = input(">")    if entry == '.':        break    else:        all.append(entry)fobj = open(fname, "w")fobj.writelines(["%s%s" % (x, ls) for x in all])fobj.close()print("DONE!")

readTextFile.py(Python2.7下编写)

# coding=utf-8"readTextFile.py--read and display text file"fname = raw_input("Enter filename: ")print fnametry:    fobj = open(fname, "r")except IOError, e:    print "*** file open error:", eelse:    for eachLine in fobj:        print eachLine,    fobj.close()

3-8

Python 代码。将脚本拷贝到您的文件系统中,然后修改它。可以添加注释,修改提示符(‘>’太单调了)等等,修改这些代码,使它看上去更舒服。

答:可以添加适当的注释提示一些必要的信息。
风格


3-9

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

答:os.linesep字符串表示当前平台所使用的行结束符。Windows下使用的是“\r\n”,Linux下使用的是“\n”,Mac下使用的是“\r”。


3-10

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

答:

# coding=utf-8"makeTextfile.py -- create text file"import osls = os.linesepwhile True:    fname = input("please input your file name: ")    try:        open(fname,"r")        print "文件名已经存在"    except IOError:        break    # if os.path.exists(fname):    #     print("ERROR:'%s'already exists" % fname)    # else:    #     breakall = []print("\nEnter lines('.' by iteself to quit).\n")while True:    entry = input(">")    if entry == '.':        break    else:        all.append(entry)fobj = open(fname, "w")fobj.writelines(["%s%s" % (x, ls) for x in all])fobj.close()print("DONE!")
# coding=utf-8"readTextFile.py--read and display text file"import osfname = raw_input("Enter filename: ")if os.path.exists(fname):    fobj = open(fname, "r")    for eachLine in fobj:        print eachLine,    fobj.close()else:    print "file open error"    # try:    #     fobj = open(fname, "r")    # except IOError, e:    #     print "*** file open error:", e    # else:    #     for eachLine in fobj:    #         print eachLine,    #     fobj.close()

3-11

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

答:

    for eachLine in fobj:        print eachLine.split()[0]

3-12

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

答:

# coding=utf-8"readNwriteTextFiles.py -- choose"import osls = os.lineseppromp = """your choice:[r]eadTextFile[m]akeTextFile"""while True:    choice = raw_input(promp).split()[0].lower()[0]    if choice == "r":        fname = raw_input("Enter filename: ")        if os.path.exists(fname):            fobj = open(fname, "r")            for eachLine in fobj:                print eachLine.split()[0]            fobj.close()        else:            print "file open error"    elif choice == "m":        fname = raw_input("please input your file name: ")        try:            open(fname, "r")            print "文件名已经存在"        except IOError:            break        all = []        print("\nEnter lines('.' by iteself to quit).\n")        while True:            entry = raw_input(">")            if entry == '.':                break            else:                all.append(entry)        fobj = open(fname, "w")        fobj.writelines(["%s%s" % (x, ls) for x in all])        fobj.close()        print("DONE!")    else:        print "Exit"        break

3-13

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

答:

# coding=utf-8"makeTextfile.py -- create text file"import osls = os.lineseppromp = """your choice:[r]eadTextFile[m]akeTextFile[e]ditorTextFile"""while True:    choice = raw_input(promp).split()[0].lower()[0]    if choice == "r":        fname = raw_input("Enter filename: ")        if os.path.exists(fname):            fobj = open(fname, "r")            for eachLine in fobj:                print eachLine.split()            fobj.close()        else:            print "file open error"    elif choice == "e":        fname = raw_input("Enter filename: ")        all = []        if os.path.exists(fname):            fobj = open(fname, "r+")            for eachLine in fobj:                print eachLine.split()                cc = raw_input("Edit?y/n")                if cc == "y":                    try:                        eachLine = raw_input("请输入你的数据: ")                    except :                        fobj.close()                        print "输入有问题"                        break                    all.append(eachLine)                else:                    all.append(eachLine)                    continue            fobj.seek(0)            fobj = open(fname, "w")            print all            for i in all:                fobj.write(i)            fobj.close()        else:            print "file open error"    elif choice == "m":        fname = raw_input("please input your file name: ")        try:            open(fname, "r")            print "文件名已经存在"        except IOError:            break        all = []        print("\nEnter lines('.' by iteself to quit).\n")        while True:            entry = raw_input(">")            if entry == '.':                break            else:                all.append(entry)        fobj = open(fname, "w")        fobj.writelines(["%s%s" % (x, ls) for x in all])        fobj.close()        print("DONE!")    else:        print "Exit"        break
阅读全文
0 0
原创粉丝点击