《趣學Python編程》習題總結
上周買了本書叫《趣學Python編程》(英文名:Python for kids),昨天看完后把書后面的題都做了下。由于第1、2章沒有習題,第13章及之后都是描寫實例的章節,因此這個總結性的文章中只包含了第3-12章的習題答案。
1.我的調試環境
我分別在我的Win7上和RedHat上調試過Python:
1)Win7的IDE可以從Python的官網上下載:
https://www.python.org/downloads/windows/
點擊鏈接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']))</pre>
4.第四章:用海龜畫圖
1)用turtle的Pen函數創建一個畫布,然后畫一個長方形
import time import turtlewidth = 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)</pre>
2)用turtle的Pen函數創建一個畫布,然后畫一個三角形
import math import time import turtlet = 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)</pre>
3)畫一個沒有角的方格
import time import turtlet = 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)</pre>
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 = 50twinkies = 300
twinkies = 550
if twinkies < 100 or twinkies > 500: print("Too less or too more")</pre>
3)用一個if語句檢查變量money是否在100到500之間,或是1000到5000之間
#money = 250money = 2500
money = 9999
if (money >= 100 and money <= 500) or (money >= 1000 and money <= 5000): print("money in [100, 500] or in [1000, 5000]") else: print("Neither in [100, 500] nor in [1000, 5000]")</pre>
4)創建一組if語句,在變量ninja小于10時打印“我能打過”、小于30時打印“有點難”、小于50時打印“太多了”
ninjas = 5ninjas = 10
ninjas = 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!")</pre>
6.循環
1)解釋下面的代碼會發生什么
for x in range(0, 20): print('hello %s' % x) if x < 9: break第一次循環時就因x<9觸發了break,因此只能打印一次 hello 0
2)如果你的年齡是偶數,從2開始打印知道你的年齡為止,如果是你的年齡是奇數,從1開始
age = 23start = 2 if age % 2 != 0: start = 1
for x in range(start, age + 2, 2): print(x)</pre>
3)創建一個列表,包含5種不同的三明治制作材料,創建一個循環,按順序打印這個列表并寫出順序號
ingredients = ['snails', 'leeches', 'gorilla belly-button lint', 'caterpillar eyebrows', 'centipede toes']for x in range(0, 5): print("%d %s" % (x + 1, ingredients[x]))</pre>
4)月球上你的體重是在地球上的16.5%,假設你每年增長1公斤,打印未來15年你的體重狀況
weight = 9999 #體重 increment = 1 #體重年增量 coefficient = 0.165 #體重轉換系數for x in range(1, 16): print("%d years later: %f" % (x, (weight + increment x) coefficient))</pre>
7.第七章:使用函數和模塊來重用你的代碼
1)用函數計算題目6.4中你的體重(參數為當前體重和體重的年增量)
def func_MoonWeight(weight, increment): coefficient = 0.165 #體重轉換系數 for x in range(1, 16): print("%d years later: %f" % (x, (weight + increment x) coefficient))func_MoonWeight(30, 0.25)</pre>
2)用函數計算題目6.4中你的體重(參數為當前體重、體重的年增量和統計的年數)
def func_MoonWeight(weight, increment, deadline): coefficient = 0.165 #體重轉換系數 for x in range(1, deadline + 1): print("%d years later: %f" % (x, (weight + increment x) coefficient))func_MoonWeight(90, 0.25, 5)</pre>
3)用函數計算6.4中你的體重,當前體重、體重的年增量和統計年數都由輸入給出
import sysdef func_MoonWeight(weight, increment, deadline): coefficient = 0.165 #體重轉換系數 for x in range(1, deadline + 1): print("%d years later: %f" % (x, (weight + increment x) coefficient))
讀取信息并調用函數
print("Please enter your current Earth weight") para1 = int(sys.stdin.readline()) print("Please enter the amount your weight might increase each year") para2 = float(sys.stdin.readline()) print("Please enter the number of years") para3 = int(sys.stdin.readline())
func_MoonWeight(para1, para2, para3)</pre>
8.第八章:如何使用類和對象
1)給Giraffes類增加函數讓長頸鹿左、右、前、后四只腳移動,通過dance函數打印一整套舞步
class Giraffes(): #函數:左腳向前 def funcLeftFootForward(self): print('left foot forward') #函數:右腳向前 def funcRightFootForward(self): print('right foot forward') #函數:左腳向后 def funcLeftFootBack(self): print('left foot back') #函數:右腳向后 def funcRightFootBack(self): print('right foot back') #函數:原地不動 def funcStand(self): print() #函數:跳舞 def funcDance(self): self.funcLeftFootForward() self.funcLeftFootBack() self.funcRightFootForward() self.funcRightFootBack() self.funcLeftFootBack() self.funcStand() self.funcRightFootBack() self.funcRightFootForward() self.funcLeftFootForward()reginald = Giraffes() reginald.funcDance()</pre>
2)使用4只Pen對象的turtle畫出一個叉子
import time import turtle線1
t1 = turtle.Pen() t1.forward(100) t1.left(90) t1.forward(50) t1.right(90) t1.forward(50)
線2
t2 = turtle.Pen() t2.forward(100) t2.right(90) t2.forward(50) t2.left(90) t2.forward(50)
線3
t3 = turtle.Pen() t3.forward(120) t3.left(90) t3.forward(25) t3.right(90) t3.forward(20)
線4
t4 = turtle.Pen() t4.forward(120) t4.right(90) t4.forward(25) t4.left(90) t4.forward(20)
time.sleep(5)</pre>
9.第九章:Python的內建函數
1)運行代碼,解釋結果
a = abs(10) + abs(-10) print(a) b = abs(-10) + -10 print(b)a是數學算式“10+|-10|=10+10”,結果為20
b是數學算式“|-10|+(-10)=10-10”,結果為0
2)嘗試用dir和help找出如何把字符串拆成單詞
dir函數可以返回關于任何值的相關信息
help函數可以返回關于其參數中描述函數的幫助信息
經過dir和help函數最后確定的代碼為:
string = '''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)</pre>
3)拷貝文件,這里采用先讀取信息再寫入到新文件的方式
#讀取文件內容 test_file1 = open("d:\input.txt") text = test_file1.read() test_file1.close()將讀取到的內容寫入到一個新文件
test_file2 = open("d:\output.txt", 'w') test_file2.write(text) test_file2.close()</pre>
10.第十章,常用的Python模塊
1)解釋下面代碼會打印出什么
import copyclass Car: pass
car1 = Car() car1.wheels = 4
car2 = car1 car2.wheels = 3 print(car1.wheels) #這里打印什么? (3)
car3 = copy.copy(car1) car3.wheels = 6 print(car1.wheels) #這里打印什么? (3)</pre>
第一個print打印3,因為car1和car2是同一個對象,改一個另一個也會改
第二個print打印3,因為car3是從car1通過copy得到的,和car1不是一個對象,修改car3不會同時改變car1
2)將一個信息用pickle序列化并保存到一個*.dat文件中,再從該文件中讀取信息反序列化并打印
import pickleinfo = { 'Name' : 'Tsybius', 'Age' : 23, 'hobby' : ['hobby1', 'hobby2', 'hobby3'] }
序列化寫入文件
outputfile = open('d:\save.dat', 'wb') pickle.dump(info, outputfile) outputfile.close()
反序列化讀取文件
inputfile = open('d:\save.dat', 'rb') info2 = pickle.load(inputfile) inputfile.close print(info2)</pre>
11.第十一章:高級海龜作圖
1)畫八邊形
import time import turtlet = turtle.Pen() for x in range(1, 9): t.forward(100) t.left(45)
time.sleep(5)</pre>
2)畫一個填好色的帶輪廓的八邊形
import time import turtlet = turtle.Pen()
繪制實心八邊形(紅色)
t.color(1, 0, 0) t.begin_fill() for x in range(1, 9): t.forward(100) t.left(45) t.end_fill()
為八邊形描邊(黑色)
t.color(0, 0, 0) for x in range(1, 9): t.forward(100) t.left(45)
time.sleep(5)</pre>
3)給出大小size和星星的角數,繪制一個星星
import time import turtlex邊形內角和180*(x-3)
函數:給出大小和頂點數繪制星星
size:星星的核心是個等邊多邊形,這是該多邊形的頂點到其中心的距離
point:頂點數
def funcDrawStar(size, point): t = 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 + 1): t.forward(size) if x % 2 == 0: t.left(120) else: t.right(180 (point - 2) / point - 60) t.end_fill()
funcDrawStar(100, 6)
funcDrawStar(100, 9)
time.sleep(5)</pre>
12.第十二章:用tkinter畫高級圖形
1)在屏幕上畫滿三角形,位置隨機、顏色隨機
from tkinter import * import randomcolor = ["green", "red", "blue", "orange", "yellow", "pink", "purple", "violet", "magenta", "cyan"]
tk = Tk() canvas = Canvas(tk, width = 400, height = 400) canvas.pack()
函數:創建隨機位置、隨機顏色的三角形
def funcRandomTriangle(): x1 = random.randrange(400) y1 = random.randrange(400) x2 = random.randrange(400) y2 = random.randrange(400) x3 = random.randrange(400) y3 = random.randrange(400) fillcolor = random.randrange(10) canvas.create_polygon(x1, y1, x2, y2, x3, y3, fill = color[fillcolor], outline = "black")
for x in range(0, 15): funcRandomTriangle()</pre>
2)移動三角形,先向右,再向下,再向左,再向上回到原來位置
import time from tkinter import *tk = Tk() canvas = Canvas(tk, width = 400, height = 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)</pre>
3)移動照片(gif格式)
import time from tkinter import *tk = Tk() canvas = Canvas(tk, width = 400, height = 400) canvas.pack()
myimg = PhotoImage(file = "d:\temp.gif") canvas.create_image(0, 0, anchor = NW, image = myimg)
向右移動
for x in range(0, 25): canvas.move(1, 5, 0) tk.update() time.sleep(0.05)</pre>
END
來自:http://my.oschina.net/Tsybius2014/blog/351236