# Python核心编程（第二版）课后习题部分答案

2-11：

# !/usr/bin/env python
# -*- coding:utf-8 -*-

print ('Please input corresponding number to run different function：\n(1)Calculate the sum of five numbers;\n(2)Calculate the average of five numbers;\n(3)Exit')
while True:
total = 0
flag = int(input('Select:'))
if flag==1:
group = []
for i in range(5):
group.append(int(input('Enter the %dth number:'%(i+1))))
for x in group:
total += x
print ('The SUM:%d'%total)
elif flag==2:
group = []
for i in range(5):
group.append(float(input('Enter the %dth number:'%(i+1))))
for x in group:
total += x
average = total/5
print ('The average:%d'%average)
elif flag==3:
break
else:
print ('You have entered the wrong number, please try again.')  

3-1：

Python是一门动态语言，也是一种强类型语言。它会根据你的赋值确定类型，在创建一个变量时开辟内存，而类型一旦确定就不再改变，当然，可以用工厂函数int()、float()来强制改变。

3-3:

3-4：

3-8：

#! /usr/bin/env python

'makeTextFile.py -- create text file in current path'

import os
ls = os.linesep #字符串给出当前平台的行终止符

#get filename
while True:
fname = input('\nCreate a filename:')#书上没有，我自己加上去的
if os.path.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 = 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.")


3-11：

#! /usr/bin/env python

'raedTextFile.py -- raed and display text file'

#get file
fname = input("Please enter the filename you want to open:")

#attempt to open file for reading

try:
fobj = open (fname,'r')
except (IOError,e):
print("*** file open error",e)
else:
#display contents to screen
for eachline in fobj:
print (eachline.rstrip())#截掉字符串右边的空格，split函数才是分割的
fobj.close()


4-1：

4-2:

4-3:

4-5:

str()函数得到的字符串可读性好，而repr()函数得到的字符串通常可以用来重新获得该对象；repr()对Python比较友好，而str()对用户比较友好。repr()和反引号()等价。

4-9：

Python仅缓存简单整型，因为他认为在程序中这些小整型会经常用到，现阶段Python3.6缓存的整型范围为（-5,256），在这个范围内，两个对象的值相等，他们就是一个对象，即id相同，而字符串也是不可变对象，只要指向相同的字符创，就是一个对象，只是有多个别名而已。

5-1：

5-6：

#coding:utf-8
""" 由于水平限制，只能实现2元运算"""
def calculator(expression):
operator = ['+','-','*','/']
sysmol = ''
for i in operator:
if i in expression:
sysmol = i
if sysmol == '':
print('操作符错误！')
return
num = expression.split(sysmol)
if '.' in num[0] or '.' in num[1]:
num1 = float(num[0])
num2 = float(num[1])
else:
num1 = int(num[0])
num2 = int(num[1])
if sysmol == operator[0]:
print (expression,'=',num1+num2)
elif sysmol == operator[1]:
print(expression,'=',num1-num2)
elif sysmol == operator[2]:
print(expression,'=',num1*num2)
elif sysmol == operator[3]:
print(expression,'=',num1/num2)
expression = input("Please input a math expression like'1+2':")
calculator(expression)


5-15：

def gcd(x,y):
if x%y==0:
return y
else:
while True:
res = x%y
if res==0:
return y
break
elif res==1:
return 1
break
x=y
y=res
def lcm(x,y):
return x*y/(gcd(x,y))  #It helps me review the Number theroy. Suddenly be enlightened. Take a tumble.  ~
def main():
while True:
string = input ('Please input two numbers:')
num = string.split()
print ("Their min multiple is ", lcm(int(num[0]),int(num[1])))
print ("Their max factor is ", gcd(int(num[0]),int(num[1])))
prompt = input("Would do you like to quit?(yes/no):")
if prompt == "yes":
break

if __name__ == '__main__':
main()



6-2：

#!usr/bin/env python3

import string
import keyword

alphas = string.ascii_letters + '_'
nums = string.digits
officalkey = keyword.kwlist

print ('Welcome to the Identifier Checker v1.0')
while True:
myInput= input('Identifier to test? (Press ctrl+C to exit)')
if myInput in officalkey:
print ("It's a offical Python identifier.")
elif len(myInput) > 1:
if myInput[0] not in alphas:
print ('''invalid: first symbol must be
alphabetic''')
else:
for otherChar in myInput[1:]:
if otherChar not in alphas + nums:
print ('''invalid: remaining
symbols must be alphanumeric''')
break
else:
print ("okay as an identifier")
elif len(myInput)==1 and myInput in alphas:
print ("It's a single indentifier.")
elif len(myInput)==1 and myInput in nums:
print ("Error!Not to be a number.")


6-3:

nums = [0,1,2,3,4,5,6,7,8,9]
string = input("请输入一串数字：").split()
Tuple = []
for ch in string:
Tuple.append(int(ch))
res1 = sorted(Tuple)[::-1]
print (res1)

Dict = {}
for ch in string:
Dict[ch] = int(ch)
res2 = sorted(Dict)[::-1]
print (res2)

6-5：

#! /usr/bin/env python3.6
# __author__ =="spwpun" for python 6-5
import re
def testA():
string = input("Enter a string -->")
for i in range(len(string)):
print (string[i])
flag = input("Would do you like to see the previous character?")
if flag == 'yes':
print (string[i-1])
flag = input("Would do you like to see the later character?")
if flag == 'yes':
print (string[i+1])

def testB():
""" This function is to compare two strings. """
if len(str1) != len(str2):
print("They are not macth. They have different length.")
else:
for i in range(len(str1)):
if str1[i] != str2[i]:
print ("They are not matchs.")
break
elif i == (len(str1)-1):
print("They are matchs.")

def testC():
""" This function is to judge if a string is a palindrome. """
strC = input ("Enter a string -->")
long = len(strC)
if long%2 == 0:
for i in range(int(long/2)):
if strC[i] != strC[long-1-i]:
print ("Not repeat!")
break
else:
print ("Repeat!")
elif long%2 != 0:
for i in range(int(long/2)):
if strC[i] != strC[long-i-1]:
print ("Not repeat!")
break
else:
print("Repeat.")
def testD():
""" To get a palindrome. """
strd = input("Enter a string -->")
strd_ = strd[::-1]
strd = strd+strd_
print("The result is -->",strd)

if __name__ == "__main__":
if choice == 'A':
testA()
elif choice == 'B':
testB()
elif choice == 'C':
testC()
elif choice == 'D':
testD()


6-6：

#! /usr/bin/env python3.6
# __author__ == "spwpun" for python 6-6
""" To define a function can replace string.strip()."""
def mystrip(string):
i=0;k=-1
while True:
if string[i] != ' ':
string = string[i:]
break
i = i+1
while True:
if string[k] != ' ':
string = string[:k+1]
break
k =k-1
return string


6-8：

#!/usr/bin/env python

units = ['zero','one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelve',
'thirteen','forteen','fifteen','sixteen','seventeen','eighteen','nineteen']
tens = ['twenty','thirty','forty','fifty','sixty','seventy','eighty','ninety']
num_str = input("Please enter a number(0,999)-->")
num_int = int(num_str)
if num_int<=19:
print (units[num_int])
elif num_int<100:
ten = tens[int(num_str[0])-2]
unit = units[int(num_str[1])]
if unit == 'zero':
print (ten)
else:
print (ten+'-'+unit)
elif int(num_str[1:])<19:
hundred = units[int(num_str[0])]
rest = units[int(num_str[1:])]
print(hundred,' hundred ',rest)
else:
hund = units[int(num_str[0])]
ten = tens[int(num_str[1])-2]
uni = units[int(num_str[2])]
if uni == 'zero':
print(hund,' hundred ',ten)
else:
print(hund,' hundred ',ten+'-'+uni)

6-11：

split和join的简单用法。

#!/usr/bin/env python3.6

blocks = []
if length != 12:
else:
for i in range(4):
blocks.append(block)
return '.'.join(blocks)
ip = trans[0]+trans[1]+trans[2]+trans[3]
return ip


6-12：

#!/usr/bin/env python3.6
# by spwpun

def findchr(string, char):
for i in range(len(string)):
if char == string[i]:
return i
else:
return -1
def rfindchr(string,char):
k = -1
while True:
if char == string[k]:
return k+len(string)
k -=1
if k+len(string)<0:
return -1
break
def subchr(string, origchr, newchar):
newst = []
newstr = ''
for i in range(len(string)):
newst.append(string[i])
if origchr == string[i]:
newst[i] = newchar
for i in range(len(newst)):
newstr += newst[i]
return newstr


7-1：

dict.update(dict2) 字典dict2的键-值对添加到dict中。

7-2：

7-3：

(a)用sorted函数；(b)循环显示；

7-4:

list1 = ['a','b','c']
list2 = [1,2,3]
mydict = dict([ (list1[i],list2[i]) for i in range(len(list1)) ])