善用良好的函式名稱
好的函式名稱,能大幅提升使用者與維護者的理解。好的名稱應清楚描述函式在做什麼。本練習要你為一個函式挑選合適的名稱,讓它在使用時更容易閱讀。
本練習屬於課程
Python 的軟體工程原則
練習說明
- 已在你的環境中預先載入
math模組,你可以使用其中的sqrt函式。 - 從以下選項中,為函式取一個最合適的名稱:
do_stuff、hypotenuse_length、square_root_of_leg_a_squared_plus_leg_b_squared、pythagorean_theorem。 - 用你選定的函式名稱,完成 docstring 的範例。
- 使用你重新命名的函式,計算直角三角形兩股長為
6與8時的斜邊長,並將結果以print印出。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
def ____(leg_a, leg_b):
"""Find the length of a right triangle's hypotenuse
:param leg_a: length of one leg of triangle
:param leg_b: length of other leg of triangle
:return: length of hypotenuse
>>> ____(3, 4)
5
"""
return math.sqrt(leg_a**2 + leg_b**2)
# Print the length of the hypotenuse with legs 6 & 8
print(____)