《Python核心編程》第二版第五章答案


本人python新手,答案自己做的,如果有問題,歡迎大家評論和討論!

更新會在本隨筆中直接更新。

 

5-1.整型。講講Python普通整型和長整型的區別。

  Python的標准整形類型是最通用的數字類型。在大多數32位機器上,標准整形類型的取值范圍是-2**32~2**32 - 1。

  Python的長整型類型能表達的數值僅僅與你的機器支持的(虛擬)內存大小有關,換句話說,Python能輕松表達很大的整數。

  長整型類型是標准整形類型的超集,當程序需要使用比標准整形更大的整型時,可以使用長整型類型,在整型值后面添加L,表示這個為長整型,這兩種整形類型正在逐漸統一為一種。

5-2.操作符。
(a)寫一個函數,計算並返回兩個數的乘積。
(b)寫一段代碼調用這個函數,並顯示它的結果。

1 def x(a, b):
2 ...     c = a * b
3 ...     return c
4 ... 
5 
6 x(2, 3)

5-3.標准類型操作符。寫一段腳本,輸入一個測驗成績,根據下面的標准,輸出他的評分成績(A-F)。
  A:90~100

  B:80~89

  C:70~79

  D:60~69

  F:<60

 1 #!/usr/bin/python
 2 
 3 def grade(num):
 4      if 90 <= num <= 100:
 5              print 'A'
 6      elif 80 <= num <= 89:
 7              print 'B'
 8      elif 70 <= num <= 79:
 9              print 'C'
10      elif 60 <= num <= 69:
11              print 'D'
12      elif 0 <= num <= 59:
13              print 'F'
14      else:
15              print " The num is invalid."
16 
17 try:
18         num = int(raw_input("Input a num:"))
19         grade(num)
20 except ValueError, e:
21         print "You must input digits."

 5-4.取余。判斷給定年份是否是閏年。使用下面的公式。
  一個閏年就是指它可以被4整除,但不能被100整除,或者它既可以被4又可以被100整除。比如1992年、1996年和2000年是閏年,但1967年和1900年則不是閏年。下一個是閏年的整世紀是2400年。

 1 #!/usr/bin/python
 2 
 3 try:
 4         year = int(raw_input("Please input a year:"))
 5         if year % 4 == 0 and year % 100 != 0:
 6                 print "%d is a leap year." %year
 7         elif year % 400 == 0:
 8                 print "%d is a leap year." %year
 9         else:
10                 print "%d is not a leap year." %year
11 except ValueError, e:
12         print "You must input a digits."

 

5-5.取余。取一個任意小於1美元的金額,然后計算可以換成最少多少枚硬幣。硬幣有1美分、5美分、10美分、25美分4種。1美元等於100美分。舉 例來說,0.76美元計算結果應該是3枚25美分,1枚1美分。類似於76枚1美分,2枚25美分+2枚10美分+1枚5美分+1枚1美分這樣的結果都是不符合要求的。

 1 #!/usr/bin/python
 2 
 3 try:
 4         dollar = float(raw_input("Input the money that less than 1 dollar:"))
 5         if dollar >= 1:
 6                 print "money is too large."
 7         elif 0 < dollar < 1:
 8                 temp = int(dollar * 100)
 9                 (N25, temp) = divmod(temp, 25)
10                 print "%d 25 coins." %N25
11                 (N10, temp) = divmod(temp, 10)
12                 print "%d 10 coins." %N10
13                 (N5, temp) = divmod(temp, 5)
14                 print "%d 5 coins." %N5
15                 (N1, temp) = divmod(temp, 1)
16                 print "%d 1 coins." %N1
17         else:
18                 print "You must input larger than 0."
19 except ValueError, e:
20         print "You must input a digits."

 5-6   算術。寫一個計算器程序。你的代碼可以接受這樣的表達式,兩個操作數加一個操作符:N1操作符N2。其中N1和N2為整型或浮點型,操作符可以是+、 -、*、/、%、**,分別表示加法、減法、乘法、整型除、取余和冪運算。計算這個表達式的結果,然后顯示出來。提示:可以使用字符串方法 split(),但不可以使用內建函數eval()。

 1 #!/usr/bin/python
 2 
 3 print "Enter the expression"
 4 expression = raw_input('>')
 5 
 6 if len(expression.split('+')) == 2:
 7         try:
 8                 splitExpression = expression.split('+')
 9                 m = float(splitExpression[0])
10                 n = float(splitExpression[1])
11                 print m + n
12         except ValueError, e:
13                 print "Input ValueError !"
14 elif len(expression.split('-')) == 2:
15         try:
16                 splitExpression = expression.split('+')
17                 m = float(splitExpression[0])
18                 n = float(splitExpression[1])
19                 print m - n
20         except ValueError, e:
21                 print "Input ValueError !"
22 elif len(expression.split('*')) == 2:
23         try:
24                 splitExpression = expression.split('*')
25                 m = float(splitExpression[0])
26                 n = float(splitExpression[1])
27                 print m * n
28         except ValueError, e:
29                 print "Input ValueError !"
30 elif len(expression.split('/')) == 2:
31         try:
32                 splitExpression = expression.split('/')
33                 m = float(splitExpression[0])
34                 n = float(splitExpression[1])
35                 print m / n
36         except ValueError, e:
37                 print "Input ValueError !"
38 elif len(expression.split('%')) == 2:
39         try:
40                 splitExpression = expression.split('%')
41                 m = float(splitExpression[0])
42                 n = float(splitExpression[1])
43                 print m % n
44         except ValueError, e:
45                 print "Input ValueError !"
46 elif len(expression.split('**')) == 2:
47         try:
48                 splitExpression = expression.split('**')
49                 m = float(splitExpression[0])
50                 n = float(splitExpression[1])
51                 print m ** n
52         except ValueError, e:
53                 print "Input ValueError !"
54 else:
55         print "Input Error !"

 5-8.幾何。計算面積和體積。
(a)正方形和立方體
(b)圓和球

 1 #!/usr/bin/python
 2 
 3 from math import pi
 4 
 5 def square(length):
 6     area = length ** 2
 7     print "The area of square is %0.2f" %area
 8 
 9 def cube(length):
10     volume = length ** 3
11     print "The volume of cube is %0.2f" %volume
12 
13 def circle(radius):
14     area = pi * radius ** 2
15     print "The area of circle is %0.2f" %area
16 
17 def sphere(radius):
18     volume = 4 * pi * radius ** 2
19     print "The volume of sphere is %0.2f" %volume
20 
21 if __name__ == "__main__":
22     try:
23         print "*****Direct execute*****"
24         num = float(raw_input("Enter a num:"))
25         square(num)
26         cube(num)
27         circle(num)
28         sphere(num)
29     except ValueError, e:
30         print " Input a invaild num !"
31 
32 if __name__ == "test":
33     try:
34         print "*****Module called*****"
35         num = float(raw_input("Enter a num:"))
36         square(num)
37         cube(num)
38         circle(num)
39         sphere(num)
40     except ValueError, e:
41         print " Input a invaild num !"

 5-10.轉換。寫一對函數來進行華氏度到攝氏度的轉換。轉換公式為C = (F - 32) * (5 / 9)應該在這個練習中使用真正的除法,否者你會得到不正確的結果。

 1 #!/usr/bin/python
 2 
 3 def convert(x):
 4     c = (x - 32) * (5.0 / 9)
 5     print "The temperature of C is %0.2f" %c
 6 
 7 if __name__ == "__main__":
 8     try:
 9         m = float(raw_input("Enter the temperature of F:"))
10         convert(m)
11     except ValueError, e:
12         print "Input Error !"

5-11.取余。
(a)使用循環和算術運算,求出0~20之間的所有偶數。
(b)同上,不過這次輸出所有的奇數。
(c)綜合(a)和(b),請問辨別奇數和偶數的最簡單的辦法是什么?
(d)使用(c)的成果,寫一個函數,檢測一個整型能否被另一個整型整除。現要求用戶輸入兩個數,然后你的函數判斷兩者是否有整除關系,根據判斷結果分別返回True和False。

 1 #!/usr/bin/python
 2 
 3 def even():
 4     for i in range(0,21):
 5         if i % 2 == 0:
 6             print i,
 7 
 8 def odd():
 9     for i in range(0,21):
10         if i % 2 <> 0:
11             print i,
12 
13 def div(m, n):
14     if m % n == 0:
15         print "TRUE"
16     else:
17         print "FALSE"
18     
19 if __name__ == "__main__":
20     print "Print the even:"
21     even()
22     print 
23     print "Print the odd:"
24     odd()
25     print
26     m = float(raw_input("Enter a num:"))
27     n = float(raw_input("Enter an anoher num:"))
28     div(m, n)

 

5-13 轉換。寫一個函數把由小時和分鍾表示的時間轉換為只用分鍾表示的時間。

 1 #!/usr/bin/python
 2 
 3 def convert(a, b):
 4     min = 60*int(a) + int(b)
 5     print "min = %d"%min
 6 
 7 if __name__ == '__main__':
 8     hour = raw_input("Enter the time:")
 9     try:
10         (h, m) = hour.split(":")
11         convert(h, m)
12     except ValueError, e:
13         print "Input a invaild num !"

 

5–15.最大公約數和最小公倍數。請計算兩個整數的最大公約數和最小公倍數。

 1 #!/usr/bin/python
 2 
 3 def common_divisor(a, b):
 4     for i in range(1, min(a, b) + 1):
 5         if a % i == 0 and b % i ==0:
 6             m = i
 7     print "The common divisor is %d" %m
 8 
 9 def common_mutiple(i, j):
10     maxnum = max(i, j)
11     while True:
12         if maxnum % i == 0 and maxnum % j ==0:
13             print "The common mutiple is %d" %maxnum
14             break
15         else:
16             maxnum = maxnum + 1
17 
18 if __name__ == '__main__':
19     try:
20         num1 = int(raw_input("Enter num1:"))
21         num2 = int(raw_input("Enter num2:"))
22         common_divisor(num1, num2)
23         common_mutiple(num1, num2)
24     except ValueError, e:
25         print "Input a invalid num !"

 5-17 隨機數。熟讀隨機數模塊然后解下面的題:
生成一個有 N 個元素的由隨機數 n 組成的列表, 其中 N 和 n 的取值范圍分別為: (1 <
N <= 100), (0 <= n <= 231 -1)。然后再隨機從這個列表中取 N (1 <= N <= 100)個隨機數
出來, 對它們排序,然后顯示這個子集。

#!/usr/bin/python

import random

N = random.randint(2, 100)
randlist = random.sample(xrange(0, 2**31 - 1), N)
randlist.sort()
print randlist


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM