跳轉到內容

面向非程式設計師的 Python 2.6 教程 / 定義函式

來自華夏公益教科書,開放書籍,開放世界

建立函式

[編輯 | 編輯原始碼]

為了開始本章,我將給你一個你可以做但你不應該做的例子(所以不要把它輸入進去)。

a = 23
b = -23

if a < 0:
    a = -a
if b < 0:
    b = -b                         #Or use the command: elif (if+else)
if a == b:
    print "The absolute values of", a, "and", b, "are equal"
else:
    print "The absolute values of", a, "and", b, "are different"

輸出結果是

The absolute values of 23 and 23 are equal

這個程式看起來有點重複。程式設計師討厭重複的事情——畢竟,這就是計算機存在的意義!(還要注意,求絕對值改變了變數的值,這就是為什麼在輸出中輸出的是 23,而不是 -23。)幸運的是,Python 允許你建立函式來消除重複。以下是重寫的示例。

def absolute_value(n):
    if n < 0:
        n = -n
    return n

a = 23
b = -23

if absolute_value(a) == absolute_value(b):
    print "The absolute values of", a, "and", b, "are equal"
else:
    print "The absolute values of", a, "and", b, "are different"

輸出結果是

The absolute values of 23 and -23 are equal

這個程式的關鍵是 def 語句。def 關鍵字(“定義”的縮寫)開始函式定義。“def”後面跟著函式名 “absolute_value”。接下來,是單個函式引數,名為 “n”。引數儲存從“呼叫”函式的程式傳遞給函式的值。def 語句中函式的引數必須用括號括起來。傳遞給函式引數的值稱為引數。所以現在,引數和引數指的是同一件事。在 “:” 後面的縮排語句塊在每次使用該函式時都會被執行。函式內的語句將繼續執行,直到縮排語句結束,或者遇到“return”語句。return 語句將值返回到呼叫程式中呼叫函式的位置。

注意 ab 的值沒有改變。函式可以用來重複不返回值的任務。以下是一些示例

def hello():
    print "Hello"

def area(w, h):
    return w * h

def print_welcome(name):
    print "Welcome", name

hello()
hello()

print_welcome("Fred")
w = 4
h = 5
print "width =", w, "height =", h, "area =", area(w, h)

輸出結果是

Hello
Hello
Welcome Fred
width = 4 height = 5 area = 20

該示例展示了一些你可以用函式做的更多事情。注意你可以使用一個或多個引數,或者根本不使用引數。還要注意,函式不一定需要“返回”值,所以 return 語句是可選的。

函式中的變數

[編輯 | 編輯原始碼]

在消除重複程式碼時,你經常會注意到程式碼中重複了變數。在 Python 中,這些變數以一種特殊的方式處理。到目前為止,我們看到的所有變數都是全域性變數。函式使用一種稱為區域性變數的特殊型別的變數。這些變數只存在於函式內部,並且只在函式執行時存在。當一個區域性變數與另一個變數(如全域性變數)具有相同的名稱時,區域性變數會隱藏另一個變數。聽起來很混亂?嗯,以下這些例子(有點牽強)應該有助於澄清。

a = 4
 
def print_func():
    a = 17
    print "in  print_func a = ", a

print_func()
print "a = ", a,"which is global variable assigned prior to the function print_func"

執行後,我們將收到以下輸出。

in print_func a = 17
a = 4 which is global variable assigned prior to the function print_func

函式內部的變數賦值不會覆蓋全域性變數,它們只存在於函式內部。即使 a 在函式內部被賦值為一個新值,這個新賦值的值也只存在於 print_func 函式內部。在函式執行結束並再次列印 a 變數的值後,我們看到賦值給全域性 a 變數的值被打印出來。

複雜示例

[編輯 | 編輯原始碼]
a_var = 10
b_var = 15
c_var = 25

def a_func(a_var):
    print ("in a_func a_var = ", a_var)
    b_var = 100 + a_var
    d_var = 2 * a_var
    print ("in a_func b_var = ", b_var)
    print ("in a_func d_var = ", d_var)
    print( "in a_func c_var = ", c_var)
    return b_var + 10

c_var = a_func(b_var)

print ("a_var = ", a_var)
print ("b_var = ", b_var)
print ("c_var = ", c_var)
print ("d_var = ", d_var)

輸出結果是

 in a_func a_var =  15
 in a_func b_var =  115
 in a_func d_var =  30
 in a_func c_var =  25
 a_var =  10
 b_var =  15
 c_var =  125
 d_var = 
 
 Traceback (most recent call last):
  File "C:\Python24\def2", line 19, in -toplevel-
     print "d_var = ", d_var
 
 NameError: name 'd_var' is not defined

在這個例子中,變數 a_varb_vard_var 在函式 a_func 內部都是區域性變數。在 return b_var + 10 語句執行之後,它們都將不復存在。變數 a_var“自動”成為區域性變數,因為它是由函式定義命名的引數。變數 b_vard_var 是區域性變數,因為它們出現在函式內部語句的等號左側:b_var = 100 + a_vard_var = 2 * a_var

在函式內部,a_var 沒有賦值。當用 c_var = a_func(b_var) 呼叫函式時,15 被賦值給 a_var,因為在那個時間點 b_var 為 15,使得對函式的呼叫變為 a_func(15)。這最終將 a_var 的值設定為 15,當它在 a_func 函式內部時。

如你所見,一旦函式執行結束,隱藏了同名全域性變數的區域性變數 a_varb_var 就消失了。然後語句 print "a_var = ", a_var 列印了值 10 而不是值 15,因為隱藏全域性變數的區域性變數已經消失了。

另一個需要注意的是最後出現的 NameError。這是因為變數 d_var 不再存在,因為 a_func 已經結束。所有區域性變數在函式退出時都會被刪除。如果你想從函式中獲取一些東西,那麼你必須在函式中使用 return 語句。

最後要說明的是,c_var 的值在 a_func 內部保持不變,因為它不是引數,並且它從未出現在 a_func 函式內部等號的左側。當在函式內部訪問全域性變數時,函式只使用全域性變數的值,但它不能更改在函式外部分配給全域性變數的值。

函式允許區域性變數,這些變數只存在於函式內部,並且可以隱藏函式外部的其他變數。

temperature2.py

# converts temperature to fahrenheit or celsius

def print_options():
    print "Options:"
    print " 'p' print options"
    print " 'c' convert from celsius"
    print " 'f' convert from fahrenheit"
    print " 'q' quit the program"

def celsius_to_fahrenheit(c_temp):
    return 9.0 / 5.0 * c_temp + 32

def fahrenheit_to_celsius(f_temp):
    return (f_temp - 32.0) * 5.0 / 9.0

choice = "p"
while choice != "q":
    if choice == "c":
        temp = input("Celsius temperature: ")
        print "Fahrenheit:", celsius_to_fahrenheit(temp)
    elif choice == "f":
        temp = input("Fahrenheit temperature: ")
        print "Celsius:", fahrenheit_to_celsius(temp)
    elif choice == "p":
        print_options()
    choice = raw_input("option: ")

示例執行

Options:
 'p' print options
 'c' convert from celsius
 'f' convert from fahrenheit
 'q' quit the program
option: c
Celsius temperature: 30 
Fahrenheit: 86.0
option: f
Fahrenheit temperature: 60
Celsius: 15.5555555556
option: q

area2.py

# By Amos Satterlee
print
def hello():
    print 'Hello!'

def area(width, height):
    return width * height

def print_welcome(name):
    print 'Welcome,', name

name = raw_input('Your Name: ')
hello(),
print_welcome(name)
print
print 'To find the area of a rectangle,'
print 'enter the width and height below.'
print
w = input('Width: ')
while w <= 0:
    print 'Must be a positive number'
    w = input('Width: ')

h = input('Height: ')
while h <= 0:
    print 'Must be a positive number'
    h = input('Height: ')

print 'Width =', w, 'Height =', h, 'so Area =', area(w, h)

示例執行

Your Name: Josh
Hello!
Welcome, Josh

To find the area of a rectangle,
enter the width and height below.

Width: -4
Must be a positive number
Width: 4
Height: 3
Width = 4 Height = 3 so Area = 12

將上面示例中的 area2.py 程式重寫,使其分別使用一個函式來計算正方形的面積、矩形的面積和圓形的面積 (3.14 * radius ** 2)。這個程式應該包含一個選單介面。

解決方案

將上面示例中的 area2.py 程式重寫,使其分別使用一個函式來計算正方形的面積、矩形的面積和圓形的面積 (3.14 * radius ** 2)。這個程式應該包含一個選單介面。

def square(length):
    return length * length

def rectangle(width , height):
    return width * height

def circle(radius):
    return 3.14 * radius ** 2

def options():
    print
    print "Options:"
    print "s = calculate the area of a square."
    print "c = calculate the area of a circle."
    print "r = calculate the area of a rectangle."
    print "q = quit"
    print

print "This program will calculate the area of a square, circle or rectangle."
choice = "x"
options()
while choice != "q":
    choice = raw_input("Please enter your choice: ")
    if choice == "s":
        length = input("Length of square: ")
        print "The area of this square is", square(length)
        options()
    elif choice == "c":
        radius = input("Radius of the circle: ")
        print "The area of the circle is", circle(radius)
        options()
    elif choice == "r":
        width = input("Width of the rectangle: ")
        height = input("Height of the rectangle: ")
        print "The area of the rectangle is", rectangle(width, height)
        options()
    elif choice == "q":
        print "",
    else:
        print "Unrecognized option."
        options()


華夏公益教科書