1. 程式人生 > >Python核心程式設計第二版第五章數字(課後習題)----我的答案

Python核心程式設計第二版第五章數字(課後習題)----我的答案

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

標準整型型別是最通用最基本的數字型別等價於C語言的長整型,一般以十進位制表示。

長整型則是標準整型型別的超集,當需要用到比標準整型型別更大的整型時,長整型就大有作為了。在一個整型後面加上L(l也是可行的),表示整型為長整型。

5-2.操作符。

(a).寫一個函式,計算並返回兩個數的乘積。

def Multipliers(a, b):
    return a * b

(b).寫一段程式碼呼叫這個函式,並顯示它的結果。

def Multipliers(a, b):
    return a * b

result = Multipliers(2, 3)
print("The result is %d" % result)

5-3.標準型別操作符。寫一段指令碼,輸入一個測驗成績,根據下面的標準,輸出他的評分成績(A-F).

A:90~100

B:80~89

C:70~79

D:60~69

F:<60

def testScore():
    score = int(raw_input("Input your real grade: "))
    if score >= 90 and score <= 100:
        print("Your testscore is A.")
    elif score >= 80 and score <= 89:
        print("Your testscore is B."
) elif score >= 70 and score <= 79: print("Your testscore is C.") elif score >=60 and score <= 69: print("Your testscore is D.") elif score < 60: print("Your failed in this test and got a F.") else: print("Try input some numbers.") testScore()

5-4.取餘。判斷給定年份是否是閏年。使用下面的公式。

def testYear():
    years = int(raw_input("Input a year in your mind: "))
    if (years % 4 == 0 and years % 100 != 0) or (years % 4 == 0 and years % 100 == 0):
        print("This year is a leap year.")
    else:
        print("This is a normal year.")

testYear()

5-5.取餘。取一個任意小於1美元的金額,然後計算可以換成最少多少枚硬幣。

def usDollar():
    dollars = float(raw_input("Input under 1 dollar like 0.76: "))
    dollars *= 100
    quartcoin = dollars // 25
    tencoin = (dollars - quartcoin * 25) // 10
    fivecoin = (dollars - quartcoin * 25 - tencoin * 10) // 5
    onecoin = (dollars - quartcoin * 25 - tencoin * 10 - fivecoin * 5)
    print("Dollars is %d Quartcoin and %d Tencoin and %d Fivecoin and %d Onecoin."
          % (quartcoin, tencoin, fivecoin, onecoin))

usDollar()

5-6.算術。寫一個計算器程式。你的程式碼可以接受這樣的表示式,兩個運算元加一個操作符:N1操作符N2。

def Calculator():
    N1 = int(raw_input("Input number 1: "))
    N2 = float(raw_input("Input number 2: "))
    sign = raw_input("Input what you want N1 N2 do: ")
    if sign == '+':
        print("N1 + N2 == %f" % (N1 + N2))
    elif sign == '-':
        print("N1 - N2 == %f" % (N1 - N2))
    elif sign == '*':
        print("N1 * N2 == %f" % (N1 * N2))
    elif sign == '/':
        print("N1 / N2 == %f" % (N1 / N2))
    elif sign == '%':
        print(N1 % N2)
    elif sign == '**':
        print("N1 ** N2 == %f" % (N1 ** N2))
    else:
        print("Out of ranges.")

Calculator()

5-7.營業稅。隨意取一個商品金額,然後根據當地營業稅額度計算應該交納的營業稅。

假設稅率為5%

def taxes(m):
    percent = 0.05
    tax = earnmoney * percent
    return tax
if __name__ == '__main__':
    earnmoney = int(raw_input("Input your earn money number: "))
    print taxes(earnmoney)

5-8.幾何。計算面積和體積。

(a).正方形和立方體

def geo():
    side = int(raw_input("Input one side with figure: "))
    print("[s] means square, [c] means cubic")
    figures = raw_input("input figure you want to calculate: ")
    if figures == 's':
        a = side * side
        print("The area is %d. " % a)
    elif figures == 'c':
        a = side * side * 6
        b = side * side * side
        print("The area is %d. The bulk is %d." % (a ,b))

geo()

(b).圓和球

def geo():
    side = float(raw_input("Input one side with figure: "))
    print("[s] means square, [c] means cubic, [r] means round, [sp] means spheres.")
    figures = raw_input("input figure you want to calculate: ")
    if figures == 's':
        a = side * side
        print("The area is %d. " % a)
    elif figures == 'c':
        a = side * side * 6
        b = side * side * side
        print("The area is %d. The bulk is %d." % (a, b))
    elif figures == 'sp':
        a = 4 * 3.14 * side * side
        b = 4 / 3 * 3.14 * side * side * side
        print("The area is %f. The bulk is %f." % (a, b))
    elif figures == 'r':
        a = 3.14 * side * side
        print("The area is %f." % a)
    else:
        print("Please follow the orders.")
geo()
轉:
# -*- coding: utf-8 -*-   
import math      
      
if __name__=='__main__':  
    ss = input()  
    print '正方形面積:',ss*ss  
    print '立方體面積:',ss*ss*6  
    print '立方體體積:',ss*ss*ss  
    print '圓面積:',ss*ss*math.pi  
    print '球面積:',ss*ss*math.pi*4  
    print '球體積:',ss*ss*ss*math.pi*4/3.0 
5-9.(a).
>>> 17 + 32
49
>>> 017 + 32
47
>>> 017 + 032
41

因為在整型的數值前加上0表示這個數是一個八進位制的數。所以017換算成十進位制為15,032轉換成十進位制為26,與下面兩個計算結果符合。在十進位制數前加0x表示十六進位制數。

(b).使用長整型運算更高效。

5-10.轉換。寫一對函式來進行華氏度到攝氏度的轉換。

from __future__ import division
def transForm():
    print("[f] means Fah, [c] means Cel.")
    Fah = float(raw_input("Input Fahrenheit: "))
    Cel = float(raw_input("Input Celsius: "))
    choice = raw_input(">>> ")
    if choice == 'f':
        Cel = (Fah - 32) * (5 / 9)
        print(Cel)
    elif choice == 'c':
        Fah = (Cel * (9 / 5)) + 32
        print(Fah)
    else:
        print("Please follow orders.")

transForm()

5-11.取餘。

(a).使用迴圈和算術運算,求出0~20之間的所有偶數。

def reMainder():
    for i in range(21):
        if i % 2 == 0:
            print("The dual is %d" % i)

reMainder()
(b).
def reMainder():
    for i in range(21):
        if i % 2 == 1:
            print("The dual is %d" % i)

reMainder()

(c).對該數除2取餘數,為0就是偶數,為1就是奇數。

(d).

def reMainder():
    inti1 = int(raw_input("Input an int number: "))
    inti2 = int(raw_input("Input an other number: "))
    if inti1 % inti2 == 0:
        return True
else:
        return False
print(reMainder())

5-12.系統限制。寫一段指令碼確認一下你的Python所能處理的整型,長整型,浮點型和複數的範圍。

Pass

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

def tranS(h, m):
    mins = hour * 60 + min
    return mins

hour = int(raw_input("Input hours: "))
min = int(raw_input("Input minutes: "))
if (hour < 23 and hour > -1) and (min < 60 and min > -1):
    print("The times is %d." % tranS(hour, min))
else:
    print("Input some right numbers.")
5-14. 銀行利息。寫一個函式,以定期存款利率為引數, 假定該賬戶每日計算複利,請計算並返回年回報率。
def inTerest(i, p):
    return p * (1 + i) ** 365

i = float(raw_input("Input rates: "))
p = int(raw_input("Input your money: "))
print("Your interest is %f." % inTerest(i, p))

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

# -*- coding: utf-8 -*-   
  
def gongyueshu(m , n):  
    if m< n:  
        min = m  
    else:  
        min = n  
    for i in range(min , 0 ,-1):  
        if m % i ==0 and n % i ==0:  
            return i  
    return 0  
  
def gongbeishu(m , n):  
    l = gongyueshu(m,n)  
    return m * n / l  
  
if __name__ == '__main__':  
    m = input()  
    n = input()  
    print '最大公約數:',gongyueshu(m, n)  
    print '最小公倍數:',gongbeishu(m, n) 

5-16.轉

# -*- coding: utf-8 -*-  
  
def Payment(cost,total):  
    count = 0  
    print '             Amount Remaining'  
    print 'Pymt#   Paid        Balance'  
    print '-----   ------   --------'  
    while True:  
        print '%-2d       $%.2f      $%6.2f'%(count,total,cost)  
        if cost - total >=0:  
            cost = cost-total  
        else:  
            if cost !=0:  
                print '%-2d       $%.2f       $%6.2f'%(count+1,cost,0)  
            break  
        count += 1  
  
if __name__=='__main__':  
    cost = input('Enter opening balance:')  
    total = input('Enter monthly payment:')  
    Payment(cost,total)