本文來自於千鋒教育在阿里雲開發者社區學習中心上線課程《Python入門2020最新大課》,主講人姜偉。
函數案例講解
1.編寫函數,求1+2+3+......+N的和
def get_sum(n):
sum = 0
for i in range(int(n)):
sum += i
return sum
print(get_sum(100)) # 4950
2.編寫一個函數,求多個數中的最大值
def get_max(*args):
x = args[0]
for arg in args:
if arg > x:
x = arg
return x
print(get_max(1, 9, 6, 3, 4, 5)) # 9
3.編寫一個函數,實現搖骰子的功能,打印N個骰子的點數和
import random
def get_sum(n):
m = 0
for i in range(n):
x = random.randint(1, 6)
m += x
return m
print(get_sum(5)) # 23
4.編寫一個函數,交換指定字典的key和value
例如:dict1={'a':1, 'b':2, 'c':3} --> dict1={1:'a', 2:'b', 3:'c'}
def swap(dict1):
dict = {}
for k, v in dict1.items():
dict[v] = k
return dict
dict1 = {'a': 1, 'b': 2, 'c': 3}
print(swap(dict1))
5.編寫一個函數,提取指定字符串中的所有字母,然後拼接在一起產生一個新的字符串
例如:傳入'12a&bc12d-+' -->'abcd'
def get_alphas(word):
new_str = ''
for w in word:
if w.isalpha():
new_str += w
return new_str
print(get_alphas('hello123good456')) # hellogood
6.寫一個函數,求多個數的平均值
def get_averange(*args):
x = 0
for arg in args:
x += arg
return x / len(args)
print(get_average(1, 2, 3, 4, 5, 6)) # 3.5
7.寫一個函數,默認求10的階乘,也可以求其他數字的階乘
def get_factorial(n=10):
x = 1
for i in range(1, n+1):
x *= i
return x
print(get_factorial(4)) # 24
8.寫一個自己的capitalize函數,能夠將指定字符串的首字母變成大寫字母
例如:'abc' -> 'Abc' '12asd' --> '12asd'
def my_capitalize(word):
c = word[0]
if 'z' >= c >= 'a':
new_str = word[1:]
return c.upper() + new_str
return word
print(my_capitalize('hello')) # Hello
print(my_capitalize('34hello')) # 34hello
9.寫一個自己的endswith函數,判斷一個字符串是否以指定的字符串結束
例如:字符串1:'abc231ab' 字符串2:'ab' 函數結果為:True
字符串1:'abc231ab' 字符串2:'ab1' 函數結果為:False
def my_endswith(old_str, str1):
return old_str[-len(str1):] == str1
print(my_endswith('hello', 'llo')) # True
print(my_endswith('hello', 'lxo')) # False
10.寫一個自己的isdigit函數,判斷一個字符串是否是純數字字符串
例如:'1234921' 結果:True
`'23函數' 結果:False`
`'a2390' 結果:False`
def my_digit(old_str):
for s in old_str:
if not '0' <= s <= '9':
return False
return True
print(my_digit('123hd90')) # False
print(my_digit('12390')) # True
11.寫一個自己的upper函數,將一個字符串中的所有的小寫字母變成大寫字母
例如:'abH23好rp1' 結果:'ABH23好RP1'
# a==>97 A ==> 65 32
def my_upper(old_str):
new_str = ''
for s in old_str:
if 'a' <= s <= 'z':
upper_s = chr(ord(s) - 32)
new_str += upper_s
else:
new_str += s
return new_str
print(my_upper('hello')) # HELLO
print(my_upper('hel34lo')) # HEL34LO
12.寫一個自己的rjust函數,創建一個字符串的長度是指定長度,原字符串在新字符串中右對齊,剩下的部分用指定的字符填充
例如:原字符:'abc' 寬度:7 字符:'^' 結果:'^^^^abc'
原字符:'你好嗎' 寬度:5 字符:'0' 結果:'00你好嗎'
def my_rjust(s, sub_str, num):
return sub_str * (num - len(s)) + s
print(my_rjust('aaa', 'r', 4)) # raaa
13.寫一個自己的index函數,統計指定列表中指定元素的所有下標,如果列表中沒有指定元素返回-1
例如:列表:[1, 2, 45, 'abc', 1, '你好', 1, 0] 元素:1 結果:0,4,6
列表:['趙雲', '郭嘉', '諸葛亮', '曹操', '趙雲', '孫權'] 元素:'趙雲' 結果:0,4
列表:['趙雲', '郭嘉', '諸葛亮', '曹操', '趙雲', '孫權'] 元素:'關羽' 結果:-1
def index(string, s):
idxs=[]
for i, st in enumerate(string):
if st == s:
idxs.append(i)
return idxs if len(idxs) > 0 else -1
print(index('ststs', 's')) # [0,2,4]
print(index('ssss', 't')) # -1
14.寫一個自己的len函數,統計指定序列中元素的個數
例如:序列:[1, 3, 5, 6] 結果:4
序列:(1, 34, 'a', 45, 'bbb') 結果:5
序列:'hello w' 結果:7
def my_len(l):
c = 0
for a in l:
c += 1
return c
print(my_len([ 1, 2, 1, 1])) # 4
15.寫一個函數實現自己in操作,判斷指定序列中,指定的元素是否存在
例如:序列:(12, 90, 'abc') 元素:'90' 結果:False
序列:[12, 90, 'abc'] 元素:90 結果:True
def my_in(it, ele):
for i in it:
if i == ele:
return True
else:
return False
print(my_in(['zhangsan', 'lisi', 'wangwu'], 'lisi')) # True
print(my_in(['zhangsan', 'lisi', 'wangwu'], 'jack')) # False
print(my_in({'name': 'zhangsan', 'age': '18'}, 'name')) # True
16.寫一個自己的replace函數,將指定字符串中指定的舊字符串轉換成指定的新字符串
例如:原字符串:'how are you? and you?' 舊字符串:'you' 新字符串:'me' 結果:'how are me? and me?'
def my_replace(all_str,old_str,new_str):
return new_str.join(all_str.split(old_str))
print(my_replace('how you and you fine you ok','you','me')) # how me and me fine me ok
第二種解法:
def my_replace(all_str,old_str,new_str):
result = ''
i = 0
while i < len(all_str):
temp = all_str[i: i + len(old_str)]
if temp != old_str:
result += all_str[i]
i += 1
else:
result += new_str
i += len(old_str)
return result
print(my_replace('how you and you fine you ok','you','me')) # how me and me fine me ok