Write a Python function

Python Style

每一種語言都有自己的書寫規則,Python也不例外,這裡我參考的是PEP 8。每次碰到不明白的規則的時候可以來查詢一下。

現在的modern editor多帶有linter,用來檢測代碼中書寫不規範的地方併產生??。(這個暫時不重要)

Python Comments

# Python有兩種評論規則(comments style),一種是用#號,# 多用於對function的解釋。"""另一種是像這樣的區塊評論,所有在這六個雙引號之間的話都是評論。這樣就不用每一行前都加上#,多用於整個file的解釋,以及class類的解釋。"""

定義Python Function和Class

"""Block comments for this file example.py and its usage."""# 最上方需要最先導入需要用到的庫。import math# Public和private function不知道怎麼翻譯。。。# Function name is lowercase letters separated by underscores(_),# e.g. add_two_numbers(a, b), multiply_three_numbers(a, b, c).# def is used to define a function.def public_function(a, b): return a * b# 如果一個function經常被用於同樣的輸入,則可以定義初始值,這樣使用function# 的時候就可以不用再輸入數值了。# 如下面這個function,使用的時候可以這樣# e.g. default_parameters_function() # a = 1, b = 2# default_parameters_function(2, 3) # a = 2, b = 3# default_parameters_function(a=3) # a = 3, b = 2def default_parameters_function(a = 1, b = 2): return a - b# This is a naming convention of Python private function,# but it doesnt really do anything...def _private_function(a, b): return a + b# 下面是定義一個基本的Python類class ExampleClass(object): def __init__(self, a, b): # Do something with a and b. self.a = a self.b = b # 默認function的第一個輸入變數是self,這樣function中就可以使用 # 類初始化的時候生成的類變數,這裡的話就是self.a和self.b。 # # 如果一個function有返回值的話,比如我們要把輸出結果載入到另外一個 # 變數中,x = example.add_function_1(),這個時候我們要用return # 來返回function中的結果。 def add_function_1(self): return self.a + self.b def add_function_2(self): return _private_function(self.a, self.b) # 如果一個function只是做一些事情,比如print,這樣就不需要使用return來 # 返回function中的結果。 def print_a_function(self): print math.pow(2, self.a)# 一般Python最後輸出的地方在main里。def main(): # 首先declare兩個變數,變數名和function名的命名規則一樣, # lowercase_separated_by_underscores。 a_number = 2 b_number = 3 # 使用最上面定義的public_function。 print public_function(a_number, b_number) # Should output 6 # 輸入a_number和b_number初始化ExampleClass類的一個對象example。 example = ExampleClass(a_number, b_number) # 使用dot(.)來使用類中的function。 print example.add_function_1() # Should output 5 print example.add_function_2() # Should output 5 example.print_a_function() # Should output 4 # 如果這是最終要被運行的程序的話,下面這個需要加上。# 比如在command terminal跑python example.py,但是現在我們# 可以先忽略,這個不重要。if __name__ == __main__: main()

練習:

  1. 定義一個function用來計算(3*x + 8)並返回最終結果。
  2. 定義一個類ExerciseClass(a, b, c),和一個function名exercise_multiply()並返回a, b, c三個數值的乘積。

References:

9.2. math - Mathematical functions - Python 2.7.14 documentationdocs.python.org

Python 在線工具 | 菜鳥工具c.runoob.com

PEP 8 -- Style Guide for Python Codewww.python.org圖標
推薦閱讀:

TAG:Python | Python入門 |