函式的好處:復用,減少重複**的編寫。
小練習:
寫乙個除法的函式,且需要處理除數不能為0
#encoding=utf-8
defdiv
(a,b):if
notisinstance
(a,(
int,
float))
:return
none
ifnot
isinstance
(b,(
int,
float))
:return
none
if b ==0:
return
none
return a/b
print
(div(
100,10)
)print
(div(20,
0))print
(div(
"a",10)
)print
(div(
100,
"b")
)
執行結果:
1、寫乙個函式,統計一下一句話中數字的個數。
#encoding=utf-8
s ='i am a 19 years old boy!666!'
defcount_digits_in_a_sentence
(s):
ifnot
isinstance
(s,str):
print
("the parameter is not a unicode string!"
)return
0 result =
0for i in s:
if i in
"0123456789"
: result+=
1return result
print
(count_digits_in_a_sentence(s)
)
執行結果:
2、寫乙個函式,統計一下一句話中字母的個數。
#encoding=utf-8
s ='i am a 19 years old boy!666!'
defcount_letters_in_a_sentence
(s):
ifnot
isinstance
(s,str):
print
("the parameter is not a unicode string!"
)return
0 result =
0for i in s:if(
ord(i)
>=
65and
ord(i)
<=91)
or\ (
ord(i)
>=
97and
ord(i)
<=
122)
: result+=
1return result
print
(count_letters_in_a_sentence(s)
)
3、寫乙個函式,統計一下一句話中字母和數字的個數。
print(count_digits_in_a_sentence(s)+count_letters_in_a_sentence(s))
4、寫乙個函式,統計一下一句話中非字母和非數字的個數。
def
count_non_alphabetnum_in_a_sentence
(s):
count =
len(s)
return count-
(count_letters_in_a_sentence(s)
+count_digits_in_a_sentence(s)
)print
(count_non_alphabetnum_in_a_sentence(s)
)
執行結果:
函式傳入的引數為不可變的,對外部的變數就沒影響。按值傳----傳入的不是變數對應的記憶體位址。
函式傳入的引數為可變的,對外部的變數就有影響。按引用傳----傳入的是變數對應的記憶體位址。
練習:寫乙個函式,使用可變引數,計算函式所有引數之和。
def
f(a,b,
*arg)
: result =
0 result = a+b
for i in arg:
result+=i
return result
def
f(a,b,
**kw)
:print
(type
(kw)
)for k,v in kw.items():
print
(k,v)
print
(f(1,2
,c=3
,d=4
,e=5
))
執行結果:
*arg:表示把可變的多個非命名引數,轉換成了乙個元組
kw:表示把可變的多個命名引數,轉換為了乙個字典
練習:1、請使用kw的方式,把可變的所有引數算乙個乘積
2、同時使用*arg和**kw,算一下字母的長度之和,注意所有引數均使用字串,字串都是字母。
Matlab函式學習(1)
1.find函式 語法 1 ind find x 找出矩陣x中的所有非零元素,並將這些元素的線性索引值 linear indices 按列 返回到向量ind中。如果x是乙個行向量,則ind是乙個行向量 否則,ind是乙個列向量。如果x不含非零元素或是乙個空矩陣,則ind是乙個空矩陣。2 ind fi...
Matlab plot函式學習(1)
1.plot x,y x y 為相應點集 2.plot x,y1,x,y2 在乙個視窗下繪製多條曲線之方法一 3.hold on 在乙個視窗下繪製多條曲線之方法二 plot x,y1 plot x,y2 hold off 4.plot後 xlabel x axis name 設定x y軸名稱 yla...
fork函式學習1
返回0給子程序 返回其他值說明fork失敗了 1 include 2 include 3 4 int main void 5 15 else if 0 pid 16 19 else 20 23 24 return 0 25 編譯後執行結果如下 第一次接觸fork函式,不少同學還以為該程式既執行了 0...