python核心编程第三章 python基础

#encoding=utf-8
from __future__ import division  #除法总是会返回真实的商
from __future__ import unicode_literals #运行时中文编码正确
# 'makeTextFile.py ----create text file'

#创建文件
import os
ls = os.linesep
fname = raw_input('Enter filename: ')
#get filename
while True:
    if os.path.exists(fname):
        print "Error:%s already exists" % fname
    else:
        break

#get file content (text) line
all = []  #初始化列表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)
        #append是list(列表)的方法,
        #函数参数是可以是任意一个元素,作用是在列表的最后添加上这个新元素。

#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!'


#!/usr/bin/env Python
'readTextFile.py -- read and display text file'
#读取文件
 # get filename
fname = raw_input('Enter filename: ')
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()



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

# 3–2. 标识符。为什么 Python 中不需要声明函数类型?
# 3–3. 标识符。为什么应当避免在变量名的开始和和结尾使用双下划线?
#__xxx__系统定义名字
# 3–4. 语句。在 Python 中一行可以书写多个语句吗?可以;
# 3–5. 语句。在 Python 中可以将一个语句分成多行书写吗?可以\
# 3–6. 变量赋值
# (a)赋值语句 x, y, z = 1, 2, 3 会在 x、y、z 中分别赋什么值?
x,y,z = 1,2,3
print '%d,%d,%d' %(x,y,z) #1,2,3
z,x,y = y,z,x
print '%d,%d,%d' %(x,y,z) #可以直接互换 3,1,2??

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

# 3–7. 标识符。下面哪些是 Python 合法的标识符?如果不是,请说明理由!在合法的标
# 识符中,哪些是关键字?
# 下面的问题涉及了 makeTextFile.py 和 readTextFile.py 脚本。
# 3–8. Python 代码。将脚本拷贝到您的文件系统中,然后修改它。可以添加注释,修改
# 提示符(‘>’太单调了)等等,修改这些代码,使它看上去更舒服。
# 3–9. 移植。 如果你在不同类型的计算机系统中分别安装有 Python, 检查一下,
# os.linesep 的值是否有不同。 记下操作系统的类型以及 linesep 的值。
# 3–10. 异常。使用类似 readTextFile.py 中异常处理的方法取代 readTextFile.py
# makeTextFile.py 中 对 os.path.exists() 的 调 用 。 反 过 来 , 用 os.path.exists() 取 代
# readTextFile.py 中的异常处理方法。 未完成


# 3–11.
# 字符串格式化 不再抑制 readTextFile.py 中 print 语句生成的 NEWLINE 字符, 修改你的
# 代码, 在显示一行之前删除每行末尾的空白。 这样, 你就可以移除 print 语句末尾的逗号了。
# 提示: 使用字符串对象的 strip()方法
# Edit By Vheavens
# Edit By Vheavens
# 3–12. 合并源文件。将两段程序合并成一个,给它起一个你喜欢的名字,比方
# readNwriteTextFiles.py。让用户自己选择是创建还是显示一个文本文件。

#encoding=utf-8
from __future__ import division  #除法总是会返回真实的商
from __future__ import unicode_literals #运行时中文编码正确
'makeTextFile.py ----create text file'
#创建文件
import os
print '------------select-----------'
print '1.create new file'
print '2.open exist file'
print '3.exit'
i = int(raw_input())
while True:
    if i == 1:
        ls = os.linesep
        #get filename
        while True:
            fname = raw_input('Enter filename: ')
            if os.path.exists(fname):
                print "Error:%s already exists" % fname
            else:
                break

        #get file content (text) line
        all = []  #初始化列表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)
                #append是list(列表)的方法,
                #函数参数是可以是任意一个元素,作用是在列表的最后添加上这个新元素。

        #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!'
    elif i == 2:
        #!/usr/bin/env Python
        'readTextFile.py -- read and display text file'
        #读取文件
         # get filename
        fname = raw_input('Enter filename: ')
        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()
    else:
        break
    print '------------select-----------'
    print '1.create new file'
    print '2.open exist file'
    print '3.exit'
    i = int(raw_input())

 


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

 1 #encoding=utf-8
 2 from __future__ import division  #除法总是会返回真实的商
 3 from __future__ import unicode_literals #运行时中文编码正确
 4 'makeTextFile.py ----create text file'
 5 #创建文件
 6 import os
 7 print '------------select-----------'
 8 print '1.create new file'
 9 print '2.open exist file'
10 print '3.exit'
11 i = int(raw_input())
12 while True:
13     if i == 1:
14         ls = os.linesep
15         #get filename
16         while True:
17             fname = raw_input('Enter filename: ')
18             if os.path.exists(fname):
19                 print "Error:%s already exists" % fname
20                 for line in fileinput.input(fname, inplace=1):   
21                     line = line.replace("oldtext", raw_input())    
22             else:
23                 break
24 
25         #get file content (text) line
26         all = []  #初始化列表all,用于保存每一行文本
27         print "\nEnter lines('.' by itself to quit)\n"
28 
29         #loop until user terminates input
30         while True:
31             entry = raw_input('>')
32             if entry == '.':
33                 break
34             else:
35                 all.append(entry)
36                 #append是list(列表)的方法,
37                 #函数参数是可以是任意一个元素,作用是在列表的最后添加上这个新元素。
38 
39         #write lines to file with proper line-ending
40         fobj = open(fname,'w')
41         fobj.writelines(['%s%s' % (x,ls) for x in all])    #列表解析
42         fobj.close()
43         print 'DOne!'
44     elif i == 2:
45         #!/usr/bin/env Python
46         'readTextFile.py -- read and display text file'
47         #读取文件
48          # get filename
49         fname = raw_input('Enter filename: ')
50         print
51 
52         # attempt to open file for reading
53         try:
54             fobj = open(fname, 'r')
55         except IOError, e:
56             print "*** file open error:", e
57         else:
58          # display contents to the screen
59             for eachLine in fobj:
60                 print eachLine,
61         fobj.close()
62     else:
63         break
64     print '------------select-----------'
65     print '1.create new file'
66     print '2.open exist file'
67     print '3.exit'
68     i = int(raw_input())


a = 10
b = 'c'
print type(a) == type(b) #判断同类型对象是否相等
print type(a) is type(b) #a is b这个表达式等价于id(a) == id(b)
#我们用对象身份的比较来替代对象值的比较。如果对象是不同的,那意

#味着原来的变量一定是不同类型的。(因为每一个类型只有一个类型对象),我们就没有必要去
#检查(值)了。
# if isinstance(num, int) 等价于 if type(num) is IntType
a = 1 #第一个数字对象被创建,赋值给a,是第一个对象的引用
b = 1
d = c = 10 #c和d指向相同的对象

print a is b #false
print c is d #true

posted @ 2016-08-01 15:35  zdmlcmepl  阅读(409)  评论(0)    收藏  举报