Python入門 8 函式

2021-08-15 22:39:17 字數 1168 閱讀 4415

1、函式的定義

def  函式名()

執行的內容

例:

def sayhello():       #定義函式sayhello

print('hello world!')

sayhello() #呼叫函式sayhello

sayhello() #可重複呼叫

2、函式的引數

定義的函式時允許呼叫者提供一些引數,就把這些引數寫在括號裡如:

def sayhello(someone):

print(someone+' says hello!') #呼叫函式時執行的語句

sayhello('mike')

得到的結果是

若有多個引數,用逗號隔開如:

def plus(num1,num2):     #定義函式plus,其中有連個引數num1,num2

print(num1+num2)

plus(1,3)

plus('say','hello')

plus(1.11,2.22)

也可以先賦予函式引數的值,得到的結果一樣:

3、函式的應用

小遊戲,在0-100中產生乙個隨機數,猜一猜數的大小,當太小時,就回答「太小了!」;太大時,就回答「太大了!」;當相等時就說「你猜對了!」

首先定義乙個函式可以判斷這個數的大小:

def guess(num1,num2):             #定義函式guess,比較兩個數的大小

if num1>num2:

print('too big')

return 'a'; #函式返回值(返回值可以為0、1、true、false、字串等任意型別),函式中任何地方的return被執行到的時候,函式執行結束

if num1函式中任何地方的return被執行到的時候,函式執行結束

python入門day8(函式)

近期在忙網路大賽,故更新的速度就會慢一些 一 函式 1.定義函式 def greet user 顯示簡單的問候語 print hello greet user 向python指出了函式名,還可能在括號內支出函式為完成其任務需要什麼樣的資訊。在這裡,函式名為greet user 他不需要任何資訊就能完...

Python入門 第8章 函式

此系列文章的創作初衷是作為讀書過程中的筆記,而非教程類文章。def greet print hello def greetuser name print hello,name.title def greet 顯示簡單的問候語 print hello 乙個良好的 編寫習慣是,在每個函式頭後都用文件字串...

Python入門記錄8

分針時針秒針什麼時候重合 coincide forhourinrange 0,12 forminuteinrange 0,60 forsecondinrange 0,60 secondangle second 360 60 minuteangle int minute second 60 360 6...