上周买了本书叫《趣学Python编程》(英文名:Python for kids),昨天看完后把书后面的题都做了下。由于第1、2章没有习题,第13章及之后都是描写实例的章节,因此这个总结性的文章中只包含了第3-12章的习题答案。
1.我的调试环境
我分别在我的Win7上和RedHat上调试过Python:
1)Win7的IDE可以从Python的官网上下载:
点击链接Python 3.4.2→Download Windows x86 MSI installer,可以下载到文件Python-3.4.2.msi
2)在RedHat上可以用yum命令直接安装python,需要用到turtle的地方,还需要用yum安装tkinter
另外,在RedHat上,turtle弹出的窗口会在运行后立即消失,因此我用time.sleep()函数来拖延一些时间方便观察结果
2.关于python脚本的运行
1)win7中下载后的IDLE(Python 3.4 GUI - 32 bit),通过File→New打开一个编辑器,输入代码后按F5可以运行
2)RedHat中直接输入命令“python xxx.py”就可以运行脚本xxx.py了
3.第三章:字符串、列表、元组和字典
1)用列表games列出爱好,用列表foods列出你喜欢的食物,把这两个列表连在一起并把结果命名为favorites并打印之
games = [‘game0‘, ‘game1‘, ‘game2‘, ‘game3‘]
foods = [‘food0‘, ‘food1‘, ‘food2‘, ‘food3‘]
favorites = games + foods
print(favorites)
2)有三座建筑,每座藏了25个忍者,有两个地道,每个藏了40个武士,问一共有多少人可以投入战斗?
building = 3
ninja_per_building = 25
tunnel = 2
samurai_per_tunnel = 40
total = building * ninja_per_building + tunnel * samurai_per_tunnel
print(total)
3)创建两个变量:一个姓和一个名,创建一个字符串,用占位符使用这两个变量打印你名字的信息
namemap = {
‘Tsybius‘ : ‘A‘,
‘Galatea‘ : ‘B‘,
‘Gaius‘ : ‘C‘,
‘Flavia‘ : ‘D‘ }
text = "Name %s %s"
print(text % (‘Tsybius‘, namemap[‘Tsybius‘]))
print(text % (‘Galatea‘, namemap[‘Galatea‘]))
print(text % (‘Gaius‘, namemap[‘Gaius‘]))
print(text % (‘Flavia‘, namemap[‘Flavia‘]))
4.第四章:用海龟画图
1)用turtle的Pen函数创建一个画布,然后画一个长方形
import time
import turtle
width = 40
height = 30
t = turtle.Pen()
t.forward(width)
t.left(90)
t.forward(height)
t.left(90)
t.forward(width)
t.left(90)
t.forward(height)
time.sleep(5)
2)用turtle的Pen函数创建一个画布,然后画一个三角形
import math
import time
import turtle
t = turtle.Pen()
#画一个等边三角形
t.forward(50)
t.left(120)
t.forward(50)
t.left(120)
t.forward(50)
t.left(120)
#把坐标换到另一个位置
t.up()
t.right(90)
t.forward(200)
t.left(90)
t.down()
#画一个内角分别为30°、30°、120°的三角形
t.forward(80 * math.sqrt(3))
t.left(150)
t.forward(80)
t.left(60)
t.forward(80)
t.left(150)
time.sleep(5)
3)画一个没有角的方格
import time
import turtle
t = turtle.Pen()
#下
t.forward(100)
t.up()
t.forward(50)
t.left(90)
t.forward(50)
t.down()
#右
t.forward(100)
t.up()
t.forward(50)
t.left(90)
t.forward(50)
t.down()
#上
t.forward(100)
t.up()
t.forward(50)
t.left(90)
t.forward(50)
t.down()
#左
t.forward(100)
time.sleep(5)
5.用if和else来提问
1)输入代码验证答案
原代码
money = 2000
if money > 1000:
print("I‘m rich!!")
else:
print("I‘m not rich")
print("But I might be later...")
这个代码是错误的,第五行和第六行的开头应该处于同一列,如下:
money = 2000
if money > 1000:
print("I‘m rich!!")
else:
print("I‘m not rich")
print("But I might be later...")
2)用if语句判断一个数是否少于100或大于500,如果这个条件为真则打印“不是太少就是太多”
#twinkies = 50
#twinkies = 300
twinkies = 550
if twinkies <100 or twinkies > 500:
print("Too less or too more")
3&#xff09;用一个if语句检查变量money是否在100到500之间&#xff0c;或是1000到5000之间
#money &#61; 250
#money &#61; 2500
money &#61; 9999
if (money >&#61; 100 and money <&#61; 500) or (money >&#61; 1000 and money <&#61; 5000):
print("money in [100, 500] or in [1000, 5000]")
else:
print("Neither in [100, 500] nor in [1000, 5000]")
4&#xff09;创建一组if语句&#xff0c;在变量ninja小于10时打印“我能打过”、小于30时打印“有点难”、小于50时打印“太多了”
ninjas &#61; 5
#ninjas &#61; 10
#ninjas &#61; 30
if ninjas <10:
print("I can beat them")
elif ninjas <30:
print("It‘s a little difficult but I can deal with it")
elif ninjas <50:
print("Too more ninjas there!")
6.循环
1&#xff09;解释下面的代码会发生什么
for x in range(0, 20):
print(‘hello %s‘ % x)
if x <9:
break
第一次循环时就因x<9触发了break&#xff0c;因此只能打印一次 hello 0
2&#xff09;如果你的年龄是偶数&#xff0c;从2开始打印知道你的年龄为止&#xff0c;如果是你的年龄是奇数&#xff0c;从1开始
age &#61; 23
start &#61; 2
if age % 2 !&#61; 0:
start &#61; 1
for x in range(start, age &#43; 2, 2):
print(x)
3&#xff09;创建一个列表&#xff0c;包含5种不同的三明治制作材料&#xff0c;创建一个循环&#xff0c;按顺序打印这个列表并写出顺序号
ingredients &#61; [‘snails‘, ‘leeches‘, ‘gorilla belly-button lint‘,
‘caterpillar eyebrows‘, ‘centipede toes‘]
for x in range(0, 5):
print("%d %s" % (x &#43; 1, ingredients[x]))
4&#xff09;月球上你的体重是在地球上的16.5%&#xff0c;假设你每年增长1公斤&#xff0c;打印未来15年你的体重状况
weight &#61; 9999 #体重
increment &#61; 1 #体重年增量
coefficient &#61; 0.165 #体重转换系数
for x in range(1, 16):
print("%d years later: %f" % (x, (weight &#43; increment * x) * coefficient))
7.第七章&#xff1a;使用函数和模块来重用你的代码
1&#xff09;用函数计算题目6.4中你的体重&#xff08;参数为当前体重和体重的年增量&#xff09;
def func_MoonWeight(weight, increment):
coefficient &#61; 0.165 #体重转换系数
for x in range(1, 16):
print("%d years later: %f" % (x, (weight &#43; increment * x) * coefficient))
func_MoonWeight(30, 0.25)
2&#xff09;用函数计算题目6.4中你的体重&#xff08;参数为当前体重、体重的年增量和统计的年数&#xff09;
def func_MoonWeight(weight, increment, deadline):
coefficient &#61; 0.165 #体重转换系数
for x in range(1, deadline &#43; 1):
print("%d years later: %f" % (x, (weight &#43; increment * x) * coefficient))
func_MoonWeight(90, 0.25, 5)
3&#xff09;用函数计算6.4中你的体重&#xff0c;当前体重、体重的年增量和统计年数都由输入给出
import sys
def func_MoonWeight(weight, increment, deadline):
coefficient &#61; 0.165 #体重转换系数
for x in range(1, deadline &#43; 1):
print("%d years later: %f" % (x, (weight &#43; increment * x) * coefficient))
#读取信息并调用函数
print("Please enter your current Earth weight")
para1 &#61; int(sys.stdin.readline())
print("Please enter the amount your weight might increase each year")
para2 &#61; float(sys.stdin.readline())
print("Please enter the number of years")
para3 &#61; int(sys.stdin.readline())
func_MoonWeight(para1, para2, para3)
8.第八章&#xff1a;如何使用类和对象
1&#xff09;给Giraffes类增加函数让长颈鹿左、右、前、后四只脚移动&#xff0c;通过dance函数打印一整套舞步
class Giraffes():
#函数&#xff1a;左脚向前
def funcLeftFootForward(self):
print(‘left foot forward‘)
#函数&#xff1a;右脚向前
def funcRightFootForward(self):
print(‘right foot forward‘)
#函数&#xff1a;左脚向后
def funcLeftFootBack(self):
print(‘left foot back‘)
#函数&#xff1a;右脚向后
def funcRightFootBack(self):
print(‘right foot back‘)
#函数&#xff1a;原地不动
def funcStand(self):
print()
#函数&#xff1a;跳舞
def funcDance(self):
self.funcLeftFootForward()
self.funcLeftFootBack()
self.funcRightFootForward()
self.funcRightFootBack()
self.funcLeftFootBack()
self.funcStand()
self.funcRightFootBack()
self.funcRightFootForward()
self.funcLeftFootForward()
reginald &#61; Giraffes()
reginald.funcDance()
2&#xff09;使用4只Pen对象的turtle画出一个叉子
import time
import turtle
#线1
t1 &#61; turtle.Pen()
t1.forward(100)
t1.left(90)
t1.forward(50)
t1.right(90)
t1.forward(50)
#线2
t2 &#61; turtle.Pen()
t2.forward(100)
t2.right(90)
t2.forward(50)
t2.left(90)
t2.forward(50)
#线3
t3 &#61; turtle.Pen()
t3.forward(120)
t3.left(90)
t3.forward(25)
t3.right(90)
t3.forward(20)
#线4
t4 &#61; turtle.Pen()
t4.forward(120)
t4.right(90)
t4.forward(25)
t4.left(90)
t4.forward(20)
time.sleep(5)
9.第九章&#xff1a;Python的内建函数
1&#xff09;运行代码&#xff0c;解释结果
a &#61; abs(10) &#43; abs(-10)
print(a)
b &#61; abs(-10) &#43; -10
print(b)
a是数学算式“10&#43;|-10|&#61;10&#43;10”&#xff0c;结果为20
b是数学算式“|-10|&#43;(-10)&#61;10-10”&#xff0c;结果为0
2&#xff09;尝试用dir和help找出如何把字符串拆成单词
dir函数可以返回关于任何值的相关信息
help函数可以返回关于其参数中描述函数的帮助信息
经过dir和help函数最后确定的代码为&#xff1a;
string &#61; ‘‘‘this if is you not are a reading very this good then way
to you to have hide done a it message wrong‘‘‘
for x in string.split():
print(x)
3&#xff09;拷贝文件&#xff0c;这里采用先读取信息再写入到新文件的方式
#读取文件内容
test_file1 &#61; open("d:\\input.txt")
text &#61; test_file1.read()
test_file1.close()
#将读取到的内容写入到一个新文件
test_file2 &#61; open("d:\\output.txt", ‘w‘)
test_file2.write(text)
test_file2.close()
10.第十章&#xff0c;常用的Python模块
1&#xff09;解释下面代码会打印出什么
import copy
class Car:
pass
car1 &#61; Car()
car1.wheels &#61; 4
car2 &#61; car1
car2.wheels &#61; 3
print(car1.wheels) #这里打印什么&#xff1f; (3)
car3 &#61; copy.copy(car1)
car3.wheels &#61; 6
print(car1.wheels) #这里打印什么&#xff1f; (3)
第一个print打印3&#xff0c;因为car1和car2是同一个对象&#xff0c;改一个另一个也会改
第二个print打印3&#xff0c;因为car3是从car1通过copy得到的&#xff0c;和car1不是一个对象&#xff0c;修改car3不会同时改变car1
2&#xff09;将一个信息用pickle序列化并保存到一个*.dat文件中&#xff0c;再从该文件中读取信息反序列化并打印
import pickle
info &#61; {
‘Name‘ : ‘Tsybius‘,
‘Age‘ : 23,
‘hobby‘ : [‘hobby1‘, ‘hobby2‘, ‘hobby3‘]
}
#序列化写入文件
outputfile &#61; open(‘d:\\save.dat‘, ‘wb‘)
pickle.dump(info, outputfile)
outputfile.close()
#反序列化读取文件
inputfile &#61; open(‘d:\\save.dat‘, ‘rb‘)
info2 &#61; pickle.load(inputfile)
inputfile.close
print(info2)
11.第十一章&#xff1a;高级海龟作图
1&#xff09;画八边形
import time
import turtle
t &#61; turtle.Pen()
for x in range(1, 9):
t.forward(100)
t.left(45)
time.sleep(5)
2&#xff09;画一个填好色的带轮廓的八边形
import time
import turtle
t &#61; turtle.Pen()
#绘制实心八边形&#xff08;红色&#xff09;
t.color(1, 0, 0)
t.begin_fill()
for x in range(1, 9):
t.forward(100)
t.left(45)
t.end_fill()
#为八边形描边&#xff08;黑色&#xff09;
t.color(0, 0, 0)
for x in range(1, 9):
t.forward(100)
t.left(45)
time.sleep(5)
3&#xff09;给出大小size和星星的角数&#xff0c;绘制一个星星
import time
import turtle
#x边形内角和180*(x-3)
#函数&#xff1a;给出大小和顶点数绘制星星
#size&#xff1a;星星的核心是个等边多边形&#xff0c;这是该多边形的顶点到其中心的距离
#point&#xff1a;顶点数
def funcDrawStar(size, point):
t &#61; turtle.Pen()
#调校坐标位置
t.up()
t.backward(200)
t.right(90)
t.forward(100)
t.left(90)
t.down()
#开始画图
t.color(1, 0, 0)
t.begin_fill()
for x in range(1, point * 2 &#43; 1):
t.forward(size)
if x % 2 &#61;&#61; 0:
t.left(120)
else:
t.right(180 * (point - 2) / point - 60)
t.end_fill()
#funcDrawStar(100, 6)
funcDrawStar(100, 9)
time.sleep(5)
12.第十二章&#xff1a;用tkinter画高级图形
1&#xff09;在屏幕上画满三角形&#xff0c;位置随机、颜色随机
from tkinter import *
import random
color &#61; ["green", "red", "blue", "orange", "yellow",
"pink", "purple", "violet", "magenta", "cyan"]
tk &#61; Tk()
canvas &#61; Canvas(tk, width &#61; 400, height &#61; 400)
canvas.pack()
#函数&#xff1a;创建随机位置、随机颜色的三角形
def funcRandomTriangle():
x1 &#61; random.randrange(400)
y1 &#61; random.randrange(400)
x2 &#61; random.randrange(400)
y2 &#61; random.randrange(400)
x3 &#61; random.randrange(400)
y3 &#61; random.randrange(400)
fillcolor &#61; random.randrange(10)
canvas.create_polygon(x1, y1, x2, y2, x3, y3,
fill &#61; color[fillcolor], outline &#61; "black")
for x in range(0, 15):
funcRandomTriangle()
2&#xff09;移动三角形&#xff0c;先向右&#xff0c;再向下&#xff0c;再向左&#xff0c;再向上回到原来位置
import time
from tkinter import *
tk &#61; Tk()
canvas &#61; Canvas(tk, width &#61; 400, height &#61; 400)
canvas.pack()
#创建一个三角形
canvas.create_polygon(10, 10, 10, 60, 50, 35)
#向右移动
for x in range(0, 60):
canvas.move(1, 5, 0)
tk.update()
time.sleep(0.05)
#向下移动
for x in range(0, 60):
canvas.move(1, 0, 5)
tk.update()
time.sleep(0.05)
#向左移动
for x in range(0, 60):
canvas.move(1, -5, 0)
tk.update()
time.sleep(0.05)
#向上移动
for x in range(0, 60):
canvas.move(1, 0, -5)
tk.update()
time.sleep(0.05)
3&#xff09;移动照片&#xff08;gif格式&#xff09;
import time
from tkinter import *
tk &#61; Tk()
canvas &#61; Canvas(tk, width &#61; 400, height &#61; 400)
canvas.pack()
myimg &#61; PhotoImage(file &#61; "d:\\temp.gif")
canvas.create_image(0, 0, anchor &#61; NW, image &#61; myimg)
#向右移动
for x in range(0, 25):
canvas.move(1, 5, 0)
tk.update()
time.sleep(0.05)
END
时间&#xff1a; 11-29