1. 程式人生 > >【零基礎】Python3學習課後練習題(十六)

【零基礎】Python3學習課後練習題(十六)

本文是跟著魚C論壇小甲魚零基礎學習Python3的視訊學習的,課後題也是跟隨每一課所附屬的題目來做的,根據自己的理解和標準答案記錄的筆記。

第十八課

測試題:

0.請問以下哪個是形參哪個是實參?

def MyFun(x):  return x**3 y = 3 print(MyFun(y))

答:x是形式引數,y是實際引數。函式定義過程中的引數是形參,呼叫函式過程中的引數是實參。

1.函式文件和直接用“#”為函式寫註釋有什麼不同?

答:函式文件是對函式的解釋和描述,可以呼叫 __.doc__ 進行檢視。而 # 所寫的函式解釋則只是在定義函式的過程中所進行的單行解釋。

2.使用關鍵字引數,可以有效避免什麼問題的出現呢?

答:可以有效避免參數使用過程中因為順序等其他方面原因呼叫函式時出錯的問題出現,使用關鍵字引數可以在呼叫函式時對引數定向賦值,以函式引數名引導呼叫引數,防止出錯。

3.使用help(print)檢視print()這個BIF有哪些預設引數?分別起到什麼作用?

答:

print(...)  
    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)  
      
    Prints the values to a stream, or to sys.stdout by default.  
    Optional keyword arguments:  
    file:  a file like object (stream); defaults to the current sys.stdout.  
    #檔案型別物件:預設是sys.stout(標準輸出流)  
    sep:   string inserted between values, default a space.  
    #第一個引數如果有多個值(第一個引數是手收集引數),各個引數之間預設使用空格(space)隔開  
    end:   string appended after the last value, default a newline.  
    #列印最後一個值之後預設引數一個換行標誌符(‘\n’)  
    flush: whether to forcibly flush the stream.  
    #是否強制重新整理流  

4.預設引數和關鍵字引數表面最大的區別是什麼?

答:預設引數是在函式定義時就為形參賦予初始值,若呼叫函式時沒有為形參傳遞實參,則使用用預設引數。關鍵字引數是在呼叫函式時,傳遞實參時指定對應的形參。

動動手:

0.編寫一個符合以下要求的函式:

   a)計算列印所有引數的和乘以基數(base = 3)的結果

   b)如果引數中最後一個引數為(base = 5),則設定基數為5,基數不參與求和運算。

答:

a)

def funx3(*numbers,base = 3):
	result = 0
	for each in numbers:
		result += each
	result *= base
	print("結果:",result)

b)

def funx5(*numbers):
	result = 0
	for each in numbers[0:-1]:
		result += each
	result *= numbers[-1]
	print("結果:",result)

1.尋找水仙花數

題目要求:如果一個3位數等於其各位數字的立方和,則稱這個數為水仙花數。例如153 = 1^3 + 5^3 + 3^3,因此153是一個水仙花數。編寫一個程式,找出所有水仙花數。

答:

def sxhnum():
    for x in range(100,1000):
        hund = x // 100
        ten = (x - hund*100) // 10
        zero = (x - hund*100 - ten*10)
        if x == hund**3 + ten**3 + zero**3:
            print(x)
        else:
            continue

2.編寫一個函式findstr(),該函式統計一個長度為2的字串在另一個字串出現的次數。例如:假定輸入的字串為“You cannot improve your past, but you can improve your future. Once time is wasted, life is wasted.”,字串為“im”,函式執行後列印“子字串在目標字串中共出現3次”。 

答:

>>> def findstr(strx,stry):
    count = 0
    length = len(stry)
    if strx not in stry:
        print('該字串未在目標字串中出現!')
    else:
        for each in range(length - 1):
            if stry[each] == strx[0]:
                if stry[each+1] == strx[1]:
                    count += 1
    print('該字串在目標字串中出現了%d次'% count)

    
>>> findstr('im','You cannot improve your past, but you can improve your future. Once time is wasted, life is wasted.')
該字串在目標字串中出現了3次
>>>