本文實例講述了python開發之函數定義方法。分享給大家供大家參考,具體如下:
下面是我做的幾個用列:
#python中的函數定義,使用和傳參def_str = '''/ python中的函數以如下形式聲明: def 函數名稱([參數1,參數2,參數3......]): 執行語句 如: def helloWorld(): print('hello') if __name__ == '_main__': helloWorld() 輸出:hello '''print(def_str)#下面進行舉例說明def helloWorld(): print('輸出:hello')if __name__ == '__main__': helloWorld()print('''/ ################################################ 函數可以帶參數和返回值,參數將按從左到右的匹配, 參數可設置默認值,當使用函數時沒給相應的參數時, 會按照默認值進行賦值 ################################################ ''')#定義一個方法:x的y次方def myMethod(x,y): return x**ydef fib(n): a , b = 0 , 1 while a < n: print('a, end = ') a , b = b , a + b print()#獲取一個新的數組#@param oldList 原數組#@param length 要添加的長度def getList(oldList,length): if length > 0: for i in range(0,length): oldList.append(i) return oldList else: return '你輸入的長度小于0'def ask_ok(prompt, retries=4, complaint='Yes or no, please!'): while True: ok = input(prompt) if ok in ('y', 'ye', 'yes'): return True if ok in ('n', 'no', 'nop', 'nope'): return False retries = retries - 1 if retries < 0: raise IOError('refusenik user') print(complaint)if __name__ == '__main__': x = 3 y = 4 n = 2000 print(x , '的' , y , '次方(' ,x ,'**' , y ,') = ' , myMethod(x,y)) print('函數fib(n),當n =' ,n) fib(n) print(getList(['begin'],-10)) ask_ok('y')運行效果如下:
Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:03:43) [MSC v.1600 32 bit (Intel)] on win32Type "copyright", "credits" or "license()" for more information.>>> ================================ RESTART ================================>>> python中的函數以如下形式聲明: def 函數名稱([參數1,參數2,參數3......]): 執行語句 如: def helloWorld(): print('hello') if __name__ == '_main__': helloWorld() 輸出:hello 輸出:hello ################################################ 函數可以帶參數和返回值,參數將按從左到右的匹配, 參數可設置默認值,當使用函數時沒給相應的參數時, 會按照默認值進行賦值 ################################################的 4 次方( 3 ** 4 ) = 81函數fib(n),當n = 20001 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 你輸入的長度小于0y輸出:helloYes or no, please!yYes or no, please!yYes or no, please!yYes or no, please!yTraceback (most recent call last): File "E:/Python33/python_workspace/test_function.py", line 80, in <module> ask_ok('y') File "E:/Python33/python_workspace/test_function.py", line 69, in ask_ok raise IOError('refusenik user')OSError: refusenik user>>>希望本文所述對大家Python程序設計有所幫助。
新聞熱點
疑難解答
圖片精選