關於簡單的python函數的一些小練習題


①:寫函數,接收n個數字,求這些參數數字的和
1 def sum_func(*args):
2     sm = 0
3     for i in args:
4         sm += i
5     return sm
6 
7 print(sum_func(1,2,3,7,4,5,6))
#結果:28
 
        

②:找出傳入的列表或元組的奇數位對應的元素,並返回一個新的列表

 1 l1 = [1,2,3,4,5,6,7]
 2 def jishu_list(l,li = []):
 3     n = 1
 4     for i in l:
 5         if n%2 == 1:
 6             li.append(i)
 7         n += 1
 8     return li
 9 print(jishu_list(l1))

#結果:[1, 3, 5, 7]

 ③:寫一個函數,判斷用戶傳入的對象(不可哈希)長度是否大於5

1 def func(l):
2     # return True if len(l) > 5 else False
3     return len(l) > 5 #比較運算本身返回bool值
4 print(func('546646'))

#結果:True

④:寫一個函數,判斷用戶傳入的列表長度是否大於2,如果大於2,只保留前兩個,並將新內容返回給調用者

 
        
 1 def func(l):
 2     if len(l)>2:
 3         l = l[0:2]
 4         return l
 5     else:
 6         return l
 7 print(func([1,2,3,4]))
 8 print(func([1,2]))

#結果:[1, 2] # [1, 2]
 
        

⑤:寫函數,統計字符串中有幾個字母,幾個數字,幾個空格,幾個其他字符,並返回結果

 
        
 1 s = ' das1 32 a2da'
 2 def lei(l):
 3     num = 0
 4     isah = 0
 5     kong = 0
 6     other = 0
 7     for i in l :
 8         if i.isdigit():
 9             num +=1
10         elif i.isalpha():
11             isah +=1
12         elif i.isspace():
13             kong +=1
14         else:
15             other +=1
16     return num,isah,kong,other
17 print(lei(s)) 

#結果:(4, 6, 3, 0)
⑥:寫一個函數,判斷用戶傳入的對象(字符串、列表、元組)的元素是否為空
 1 def func(l):
 2     if len(l) == 0:
 3         return '該對象為空'
 4     else:
 5         return '該對象不為空'
 6 
 7 print(func((1,2,3)))
 8 print(func([]))
 
#結果:該對象不為空
# 該對象為空
⑦:寫函數,檢查傳入字典的每一個value長度,如果大於2,那么僅保留前兩個長度的內容,並將新內容返回給調用者
 1 dic = {"k1":"v1v1","k2":[11,22,33,44]}
 2 
 3 def length_func(l):
 4     for k,v in l.items():
 5         if len(v) > 2:
 6             i = v[0:2]
 7             l[k]= i
 8         else:
 9             print('值長度小於2')
10     return l
11 print(length_func(dic))
 
 #結果:{'k1': 'v1', 'k2': [11, 22]}
 
        

⑧:寫函數,接收兩個數字參數,返回比較大的數字

1 def my_max(a,b):
2     return max(a,b)
3 
4 print(my_max(5,8))

#結果:8

⑨:寫函數,用戶傳入修改的文件名與要修改的內容,執行函數,完成整個文件的批量修改

方法一:直接寫入文件

 
        
 1 import os
 2 
 3 def func(file ,old ='',new = ''):#修改文件內容
 4     file1 = open('swap','w',encoding='utf8')
 5     file1.close()
 6     with open(file,mode='r',encoding='utf-8') as f1, \
 7             open('swap', 'a', encoding='utf8')as f2:
 8                     for i in f1: #輸出每行內容
 9                         if old in i:
10                             f2.seek(2)
11                             f2.write('{}\n'.format(new.strip()))
12                         else:
13                             f2.seek(2)
14                             f2.write('{}\n'.format(i.strip()))
15 
16     os.remove(file)
17     os.rename('swap',file)
18 func('sss',old='老李',new='老郭')
 
 #結果:修改前的文件內容:老王
 #                   老李
 #                   老陳
 #     修改后的文件內容:老王
 #                   老郭
 #                   老陳
 
        

方法二:先轉存列表再寫入文件

 1 import os
 2 
 3 def func(file ,old ='',new = ''):#修改文件內容
 4     lis = []
 5     file1 = open('swap','w',encoding='utf8')
 6     file1.close()
 7     with open(file,mode='r',encoding='utf-8') as f1, \
 8             open('swap', 'a', encoding='utf8')as f2:
 9                     for i in f1: #輸出每行內容
10                         if old in i:
11                             lis.append(new.strip())
12                         else:
13                             lis.append(i.strip())
14                     print(lis)
15                     for i in lis:
16                         print(i.strip())
17                         f2.write('{}\n'.format(i))
18     os.remove(file)
19     os.rename('swap',file)
20 func('sss',old='老李',new='老郭')
 
 #結果同方法一

⑩:寫一個函數完成三次登陸功能,再寫一個函數完成注冊

 
        
 1 def zc_func():#賬號注冊
 2     username = input('請輸入您注冊的用戶名:').strip()
 3     password = input('請輸入您注冊的密碼:').strip()
 4     with open('user_pwd_note','w',encoding='utf-8') as f:
 5         f.write('{}\n{}'.format(username,password))
 6     return '恭喜您注冊成功!'
 7 
 8 def logo_func():#賬號登錄
 9     i = 0
10     lis = []
11     while i < 3:
12         uname = input('請輸入您的用戶名:').strip()
13         passwd = input('請輸入密碼:').strip()
14         with open('user_pwd_note','r',encoding='utf-8') as f:
15             for j in f:
16                 lis.append(j.strip())
17         if uname == lis[0] and passwd == lis[1]:
18             print('登陸成功!')
19             break
20         else:
21             print('您輸入的賬號或密碼錯誤,請重新輸入!')
22         i += 1
23 
24 zc_func()
25 logo_func()


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM