Python核心编程课后习题-第三章

3-1

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

3-2

Python 中每个函数都会有返回值,如果没有指定,则返回None
如果有return 语句,则返回 return 语句的值

3-3

单下划线 类似于protect
双下划线 类似于private
使用双下划线后,该变量只可以在类里面使用

3-4

可以写多个语句,用 分号 ; 隔开

3-5

一个语句可以分成多行写 ,使用 \ 连接在上一行的末尾

3-6

(a) 多元赋值 x = 1,y = 2,z = 3
(b) 多元赋值,可以看做是交换(同时执行), z = y = 2, x = z = 3,y = x =1

3-7

不合法的标识符
40XL $aving$ 0x40L big-daddy
2hot2touch thisIsn'tAvar counter-1

关键字
print self __name__ bool type True if

3-8

详情代码看Github

  • page52 makeTextFile.py 有错误,在10行应该添加
  • if 跟 else 还需要缩进,不然会报错
  • 在win环境下,输入的文件名应该包含路径,而且路径的分隔符是 / (正斜杠)

3-9

os.linesep不同操作系统下的输出

  • win '\r\n'
  • Linux '\n'
  • Mac '\r'

3-10

try ... catch 与 if 的使用:
当条件多为真时,使用if
当条件多为假时,使用try ... catch

makeFile.py

#!/usr/bin/env python
# coding = utf-8

'makeTextFile.py -- create text file'
import os
ls = os.linesep
# get filename
while True:
   fname = raw_input("Please input file name:\n")
   try:
      with open(fname,'r'):  # success ,file exists ; failed, file not exists
         print "File exists"
   except IOError: #open failed
      break
#get file content (text) linesall = []
print "\nEnter lines ('.' by itself to quite) ."
#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!'

readFile.py

#!/usr/bin/env python
import os
'readTextFile.py -- read and display text file'
while True:
   # get filename
   fname = raw_input("Enter filename: ")
   print
   # attempt to open file for reading
   if not os.path.exists(fname):
      print " *** file open error!\n"
   else:
      fobj = open(fname,'r')
      # display contents to the screen
      for eachLine in fobj:
         print eachLine,
      fobj.close()
      break

3-11

strip()函数,str.strip(rm) 是删除s字符串中开头、结尾处,位于 rm删除序列的字符
字符序列 : 该字符串的无序列表,可以由rm 组成就行。

  • 当rm为空时,默认删除空白符 包括 ('\n','\r','\t',' ')
  • 这里的rm删除序列是只要边(开头或结尾)上的字符在删除序列内,就删除掉。
>>> a = '123abc'
>>> a.strip('12')
'3abc'
>>> a.strip('21')
'3abc'
>>> a.strip('1a')
'23abc'
>>> a.strip('1c')
'23ab'
>>> a.strip('1b')
'23abc'
>>> a.lstrip('3a')
'123abc'
>>> a.lstrip('12')
'3abc'
>>> a.lstrip('21')
'3abc'
>>> a.lstrip('bc')
'123abc'
>>> a.rstrip('bc')
'123a'
>>> a.rstrip('bac')
'123'
>>> a.rstrip('bca')
'123'
>>> a.strip('3a')
'123abc'

原题答案,只需要把eachLine 后的 逗号改成 .strip()

3-12

思路:把两个文件的功能放在函数里,在main函数里通过while循环判断用户输入的功能序列,在执行相应的功能

#!/usr/bin/env python
__author__ = 'Yuriy'
import os
ls = os.linesep
# get filename
def writeFile():
   while True:
      fname = raw_input("Please input file name:\n")
      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 quite) ."
   #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!'

def readFile():
   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.strip()
      fobj.close()

if __name__ == '__main__':
   while True:
      print '''Input the function number: 
  1.MakeFile
   2.ReadFile
   3.Exit
      '''
      ch = int(raw_input(' Function :'))
      if ch == 1:
         writeFile()
      elif ch == 2:
         readFile()
      else:
         break
Input the function number:
    1.MakeFile
    2.ReadFile
    3.Exit
        
 Function :1
Please input file name:
e:/eee.txt

Enter lines ('.' by itself to quite) .
>>>my name
>>>is 
>>>who 
>>>.
Done!

Input the function number:
    1.MakeFile
    2.ReadFile
    3.Exit
        
 Function :2
Enter filename: e:/eee.txt

my name
is
who

Input the function number:
    1.MakeFile
    2.ReadFile
    3.Exit
        
 Function :3
Process finished with exit code 0

3-13

只需要在3-12的基础上再加上一个功能,调用win系统的命令:
os.system('notepad %s' %ch) 就可以使用文本编辑器编辑该txt文件

#!/usr/bin/env python
__author__ = 'Yuriy'
import os
ls = os.linesep
# get filename
def writeFile():
   while True:
      fname = raw_input("Please input file name:\n")
      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 quite) ."
   #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!'

def readFile():
   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.strip()
      fobj.close()

def changeFile():
   while True:
      ch = raw_input("input filename:")
      if not os.path.exists(ch):
         print "%s File not exists \n" % ch
      else:
         try:
            # call system command to change file content
            os.system('notepad %s' %ch 
            print
            print 'You have change %s' % ch
            break
         except IOError,e:
            print 'error command'

if __name__ == '__main__':
   while True:
      print '''Input the function number:
   1.MakeFile
   2.ReadFile
   3.changeFile
      '''
      ch = int(raw_input(' Function :'))
      if ch == 1:
         writeFile()
      elif ch == 2:
         readFile()
      elif ch == 3:
         changeFile()
      else:
         break
Input the function number:
    1.MakeFile
    2.ReadFile
    3.changeFile
        
 Function :3
input filename:e:/eee.txt

You have change e:/eee.txt

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 157,298评论 4 360
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,701评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 107,078评论 0 237
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,687评论 0 202
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,018评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,410评论 1 211
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,729评论 2 310
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,412评论 0 194
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,124评论 1 239
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,379评论 2 242
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,903评论 1 257
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,268评论 2 251
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,894评论 3 233
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,014评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,770评论 0 192
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,435评论 2 269
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,312评论 2 260

推荐阅读更多精彩内容