zoukankan      html  css  js  c++  java
  • 第三章 python基础练习题自我总结的答案

    前言:我学习python是学习的python核心编程这本书,第三章是python的基础,这部分讲的是python的一些基础知识,我读了一遍但是收获不大,于是我自己总结了这一章的课后题答案,希望加深自己对于这一章的理解。
    3-1标识符。为什么Python中不需要变量名和变量类型声明?
            答:  python语言中,对象的类型和内存占用都是运行时确定的。python是一种解释型语言,在创建----也就是赋值时,解释器会根据语法和右侧的操作数来决定新对象的类型,在对象创建后,一个该对象的应用就会赋值给左侧的变量。
    3-2标识符。为什么Python中不需要声明函数类型?
            答:同上吧
    3-3标识符。为什么应当避免在变量名的开始和结尾使用下划线?
            答:因为下划线对解释器有特殊的意义,而且是内建标识符所使用的符号,_xxx是类中的私有变量名,当变量是私有的话,_xxx可以作为一种好的习惯,__xxx__是系统定义的名字。
    3-4语句。在Python中一行可以书写多个语句吗?
            答:可以,Python语句中一般使用换行分隔,也就是说一行一个语句。分号(\)允许将多个语句写在同一行。但是python不提倡
    3-5语句。在Python中可以将一个个语句分成多行书写吗?
            一行过长的语句可以使用反斜杠(\)分成几行。
            x,y,z=1,\
                       2,3
            使用闭合操作符时,单一语句可以跨行。
            >>> (x,y,z)=(1,2,
             3)
             >>> (x,y,z)
            (1, 2, 3)
            >>> 
             三个引号包括下的字符串也可以跨行书写。
            x='qwewerqwerqwer\
                          qwerqwererqwer'
    3-6至3-7没有做
    3-8 python代码,修改makeTextFile.py的代码
            答:参照书上makeTextFile.py代码自己写的代码,通过文件名,文件内容和写文件分别用三个函数实现。
    参见书上代码:
    #!/usr/bin/env python 
    'makeTextFile.py -- create text file' 
    import os
    # get filename
    while True:
        fname = raw_input('Enter file name: ')
        if os.path.exists(fname):
            print"*** ERROR: '%s' already exists" % fname
        else:
            break
    # get file content (text) lines
    all = []
    print "\nEnter lines ('.' by itself to quit).\n"
    # loop until user terminates input
    while True:
        entry = raw_input('> ')
        if entry == '.':
            break
        else:
            all.append(entry)
    # write lines to file with NEWLINE line terminator
    fobj = open(fname, 'w')
    fobj.write('\n'.join(all))
    fobj.close()
    print 'DONE!'
    我的代码:
    import os
    def getFileName():
        'get a filename'
        while True:
            fname=raw_input('Enter file name:')
            if os.path.exists(fname):
                print 'oops! "%s" already exists '% fname
            else:
               # print fname
                break
        return fname
        
    def getFileContentLines():
        'get file content (text) lines'
        all=[]
        print "\n Enter lines ('.' by itself to quit).\n"
        #loop until user terminates input
        while True:
            entry =raw_input('->')
            if entry=='.':
                break
            else:
                all.append(entry)
        return all
    def writeFile(fname,content):
        'write lines to file with NEWLINE line terminator'
        fobj=open(fname,'w')
        fobj.write('\n'.join(content))
        fobj.close()
        print 'DONE'
     
    fname=getFileName()
    #print fname
    content=getFileContentLines()
    #print content
    writeFile(fname,content)
    我的makeTextFile代码
    3-9移植。在不同类型的计算机系统查看os.linesep的不同。
    对于Unix平台,linesep是'\n',对于DOS或者是win32平台,linesep是'\r\n'
    3-10 异常。使用异常代替makeTextFile 中os.path.exists()调用,使用os.path.exists()代替readTextFile中的异常
            答:思路是使用open函数,如果没有文件就会产生异常
    def getFileName():
    'get a filename'
        while True:
            fname=raw_input('Enter file name:')
                try:
                    open(fname,'r')
                except:
                    break
                else:
                    print 'Error'
                    print 'oops! "%s" already exists ' % fname    
    readTextFile.py的源代码
    #!/usr/bin/env python
     
    'readTextFile.py -- read and display text file'
     
    # get filename
    fname = raw_input('Enter file name: ')
    print
     
    # attempt to open file for reading
    try:
        fobj = open(fname, 'r')
    except IOError, e:
        print"*** file open error:", e
    else:
        # display contents to the screen
        for eachLine in fobj:
            print eachLine,
        fobj.close()
    书上的readTextFile代码
    在readTextFile模块中,使用os.path.exists代替异常
    import os
    #get filename
    fname=raw_input('Enter file name:')
    print
    #attempt to open file for reading
    if os.path.exists(fname):
       #display contents to the screen
        fobj=open(fname,'r')
        for eachLine in fobj:
            print eachLine,
            fobj.close()
    else:
        print "oop! the file is not exist"
        print 'current path:',os.path.abspath('.')
    os.path.exists代替
    3-11字符串格式化。print语句会自动输出内容后会自动添加换行符,因此在readTextFile读取文件向屏幕输出时,print 输出每行内容还要加一个‘,’,因为文件中本身就包括换行符,尝试用strip()代替‘,’
    代码
    import os
    #get filename
    fname=raw_input('Enter file name:')
    #attempt to open file for reading
    if os.path.exists(fname):
       #display contents to the screen
        fobj=open(fname,'r')
        for eachLine in fobj:
            print eachLine.strip()    
        fobj.close()
    else:
        print "oop! the file is not exist"
        print 'current path:',os.path.abspath('.')
    print 中的','用strip()代替
    3-12合并源文件。将两个程序合并成一个,用户可以选择创建文件还是现实文件。
    我使用的是引用模块,根据选择执行相应的代码块。readTextFile.py,makeTextFile.py,和这个文件放在同一目录下,不同目录的引用我目前不会。
    choice =raw_input("""choose make file press M/m
    chose read file press R/r""")
    if choice=='M'or choice=='m':
        import makeTextFile
    elif choice=='R' or 'r':
        import readTextFile

    3-13不会做

                                                                                                                                                菜包子
                                                                                                                               2013年6月10日0:46:24  于宿舍
     
  • 相关阅读:
    CPA财务管理例题汇总
    Vulkan(1)用apispec生成Vulkan库
    Vulkan(0)搭建环境-清空窗口
    [译]可见性判断之门系统
    《资本论》核心思想
    [译]为任意网格计算tangent空间的基向量
    [译]Vulkan教程(33)多重采样
    [译]Vulkan教程(32)生成mipmap
    [译]Vulkan教程(31)加载模型
    [译]Vulkan教程(30)深度缓存
  • 原文地址:https://www.cnblogs.com/CaiBaoZi/p/3130297.html
Copyright © 2011-2022 走看看