python闖關 python闖關 Day06

2021-10-13 02:47:33 字數 2375 閱讀 1335

函式式程式設計

python的函式式程式設計,需要關注以下幾個點。

1. 引數:有無引數、形參和實參的區別、引數可以是哪些型別,引數的讀取順序等。

2. 返回值:未指定的情況下,預設是有返回值的。

按照之前的程式經驗,呼叫函式前需要將環境引數壓棧,再壓入引數(push),再跳轉到函式,再由函式反向讀取壓入的引數(pop)。通過這節課的學習,python也是類似的執行邏輯。

函式返回時,需要將返回值壓棧,再退出函式,由父「程序」彈出並讀取壓入的返回值。python有區別的是返回值的型別不是寫在函式宣告的那一行,而是由函式的返回值來確定的。

對於沒有返回值的函式,可以理解為「方法」,呼叫函式的幾種方法

1 語句形式:foo()

2 表示式形式:3*len('hello')

3 當中另外乙個函式的引數:range(len('hello'))

在練習中,打算在函式內修改全域性的字典,沒有成功,作業後再試試。

練習:1、寫函式,,使用者傳入修改的檔名,與要修改的內容,執行函式,完成批了修改操作

def mywritefile (strfile,strcontext):

f = open(strfile, 'w',encoding='utf-8')

f.write(strcontext)

f.close()

strfile = input('請輸入檔名:')

strcontext = input('請輸入需要修改的內容:')

mywritefile(strfile,strcontext)

2、寫函式,計算傳入字串中【數字】、【字母】、【空格】以及 【其他】的個數

def count_str(str):

tmp = {}

len_str = len(str)

i = 0

isdig = isalpha = isspace = isother = 0

while i < len_str:

if str[i].isdigit(): isdig +=1

elif str[i].isalpha(): isalpha +=1

elif str[i].isspace(): isspace +=1

else : isother +=1

i += 1

print("字串:", str)

print("數字的數量:",isdig)

print("字母的數量:",isalpha)

print("空格的數量:",isspace)

print("其他的數量:",isspace)

str = "abcdef123 54 "

count_str(str)

3、寫函式,判斷使用者傳入的物件(字串、列表、元組)長度是否大於5。

def count(arg):

if len(arg) > 5:

print(arg, "的長度大於5")

count('abcdddd')

count([1,1,1,1])

count((1,2))

4、寫函式,檢查傳入列表的長度,如果大於2,那麼僅保留前兩個長度的內容,並將新內容返回給呼叫者。

def count1(arg):

newarg = arg

if len(arg) > 2:

newarg = arg[:2]

return(newarg)

print(count1('abcde'))

print(count1([1,2,2,3,4,5]))

5、寫函式,檢查獲取傳入列表或元組物件的所有奇數字索引對應的元素,並將其作為新列表返回給呼叫者。

def modilist(arg):

new_arg =

i = 0

while i < len(arg):

i += 2

return(new_arg)

print (modilist((1,2,3,4,5,6,7)))

6、寫函式,檢查字典的每乙個value的長度,如果大於2,那麼僅保留前兩個長度的內容,並將新內容返回給呼叫者。

dic =

ps:字典中的value只能是字串或列表

def cutdict(**arg):

for key in arg:

newvalue = arg[key]

if len(newvalue) > 2:

newvalue = newvalue[:2]

arg[key] = newvalue

return(arg)

arg =

arg = cutdict(**arg)

print (arg)

1、寫函式,,使用者傳入修改的檔名,與要修改的內容,執行函式,完成批了修改操作

python闖關 python闖關 Day05

乙個簡單的 選單 usr bin env python coding utf 8 mymenu 動物 貓 黃貓 花貓 狗 二哈 金毛 植物 樹 大樹 小樹 草 綠草 矮草 menu list list mymenu.keys while true print 編號 center 50,for i i...

python闖關 python闖關 Day02

q1 寫乙個使用者迴圈猜年齡的遊戲,猜對就退出,猜不對就繼續猜,猜三次,提示使用者是否繼續,使用者回答y或者y就繼續猜,三次之後再重複,回答n或n就結束遊戲。usr bin env python coding utf 8 猜年齡 import random age random.randint 1,...

python闖關 python闖關 Day009

第9章 合併表達 1 將names albert james kobe kd 中的名字全部變大寫 names albert james kobe kd names name.upper for name in names 應記住的表達方式,很python print names 2 將names a...