《Python核心编程》 第三章 Python基础 - 练习

时间:2023-03-09 15:08:03
《Python核心编程》 第三章 Python基础 - 练习

创建文件:

# -*- coding: gbk -*-
#! /auto/ERP/python_core/chapter

'''
Created on 2014年5月21日

@author: user
function : create a new file
'''

import os
ls = os.linesep

#get file name
while True:
    fname = raw_input('PLS enter a file name:')
    if os.path.exists(fname):
        print "ERROR:'%s' already exists!"%fname
    else:
            break

#get file content
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 proper line-ending
fobj = open(fname,'w')
fobj.writelines(['%s%s'%(x,ls)for x in all])
fobj.close()
print "DONE!"

读文件内容

# -*- coding: gbk -*-
#! /auto/ERP/python_core/chapter3

'''
Created on 2014年5月21日

@author: user
function: read the content of the text
'''

fname = raw_input("PLS enter the file name:")
print
try:
    fobj =open(fname,'r')
except IOError,e:
    print "*** file open error ***",e
else:
    for eachLine in fobj:
        print eachLine
    fobj.close()
    

课后习题:


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

答:因为它们是动态类型,使用的时候自动进行类型声明。

  在Python语言中,对象的类型和内存占用都是运行时确定的。


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

答:函数类型是一个动态类型返回值,在运行的时候确定。


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

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


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

答: 分号(;),将两个语句写在一行,抑或更多行。


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

答:反斜线(\),继续上一行。


3-6 变量赋值

  1. 赋值语句x,y,z=1,2,3会在x、y、z中分别赋什么值?
    答:x:1,y:2,z:3
  2. 执行z,x,y = y,z,x后,x,y,z分别赋什么值? 
    答:默认初始值,x,y,z=1,2,3
    z=y,z=2
    x=z,x=3
    y=x,y=1
    (和c语言的赋值不一样)