習題 18: 命名蛤袒、變量、代碼膜赃、函數(shù)
在文本編輯器中,編輯以下內容并保存到ex18.py文件中揉忘,同時在終端中運行該文件:
##-- coding: utf-8 --
# this one is like your scripts with argv
def print_two(*args):
arg1, arg2 = args
# 將參數(shù)解包跳座,這和腳本參數(shù)解包的原理差不多
print "arg1: %r, arg2: %r" % (arg1, arg2)
# ok, that *args is actually pointless, we can just do this
def print_two_again(arg1, arg2):
print "arg1: %r, arg2: %r" % (arg1, arg2)
# this just takes one argument
def print_one(arg1):
print "arg1: %r" % arg1
# this one takes no arguments
def print_none():
print "I got nothin'."
print_two("Zed", "Shaw")
print_two_again("Zed", "Shaw")
print_one("First!")
print_none()
執(zhí)行結果:
$ python ex18.py
arg1: 'Zed', arg2: 'Shaw'
arg1: 'Zed', arg2: 'Shaw'
arg1: 'First!'
I got nothin'.
加分習題
為自己寫一個函數(shù)注意事項以供后續(xù)參考。你可以寫在一個索引卡片上隨時閱讀泣矛, 直到你記住所有的要點為止疲眷。注意事項如下:
- 函數(shù)定義是以 def 開始的嗎?
- 函數(shù)名稱是以字符和下劃線 _ 組成的嗎?
- 函數(shù)名稱是不是緊跟著括號 ( ?
- 括號里是否包含參數(shù)?多個參數(shù)是否以逗號隔開?
- 參數(shù)名稱是否有重復?(不能使用重復的參數(shù)名)
- 緊跟著參數(shù)的是不是括號和冒號 ): ?
- 緊跟著函數(shù)定義的代碼是否使用了 4 個空格的縮進 (indent)?
- 函數(shù)結束的位置是否取消了縮進 (“dedent”)?
當你運行(或者說“使用 use”或者“調用 call”)一個函數(shù)時,記得檢查下面的要 點: - 調運函數(shù)時是否使用了函數(shù)的名稱?
- 函數(shù)名稱是否緊跟著 ( ?
- 括號后有無參數(shù)?多個參數(shù)是否以逗號隔開?
- 函數(shù)是否以 ) 結尾?
按照這兩份檢查表里的內容檢查你的練習您朽,直到你不需要檢查表為止狂丝。 最后,將下面這句話閱讀幾遍:
“‘運行函數(shù)(run)’哗总、‘調用函數(shù)(call)’几颜、和 ‘使用函數(shù)(use)’是同一個意思”