本文實(shí)例講述了Python通用循環(huán)的構(gòu)造方法。分享給大家供大家參考,具體如下:
1.交互循環(huán)
是無限循環(huán)的一種,允許用戶通過交互的方式程序的特定部分;
def main(): sum =0.0 count =0 moredata ='yes' #字符串 while moredata[0] =='y': #獲取字符串第一個(gè)字符,true執(zhí)行下面的 x =eval(input('enter a number>>')) sum =sum+x count = count +1 moredata =input("你有更多的number(yes or no)") print("pingjunshushi:/n",sum/count)main()enter a number >>3你有更多的number(yesor no)yenter a number >>4你有更多的number(yesor no)npingjunshushi: 3.52.哨兵循環(huán):
執(zhí)行循環(huán)要遇到設(shè)定的特殊數(shù)據(jù),循環(huán)語句才會(huì)終止。
哨兵循環(huán)求平均數(shù)的方法:
1)設(shè)定一個(gè)哨兵值作為循環(huán)終止的標(biāo)識(shí);
2)任何值都可以看做哨兵,但是要與實(shí)際數(shù)有所區(qū)別;
python中空字符串以雙引號(hào)""表示,注意引號(hào)中間沒有空格!!!
def main(): sum =0 count =0 xStr = input("enter a number") while xStr != "": #空字符串 x = eval(xStr) #轉(zhuǎn)換字符串為數(shù)字的過成 sum = sum + x count =count +1 xStr = input("enter a number :") print("average is",sum/count)main()enter a number6enter a number :6enter a number :6enter a number : 這里確認(rèn)輸入不是哨兵空字符才將輸入字符串轉(zhuǎn)換為數(shù)字average is 6.0 eval() 函數(shù)參數(shù)是字符串可以當(dāng)成有效python表達(dá)式來求值,并返回計(jì)算結(jié)果
3.文件循環(huán)
def main(): fileName = input("file denumber:") #這個(gè)相當(dāng)于一個(gè)文件 infile = open(fileName,'r') #open(文件名,方式'r'/'w')函數(shù)用來打開這個(gè)文件的一行保存在infile列表(相當(dāng)一個(gè)數(shù)組)中 sum =0 count = 0 for line ininfile: #循環(huán)變量line遍歷文件的每一行(文件每一行已經(jīng)保存在infile列表中),將每一行執(zhí)行下面的代碼 sum = sum+eval(line) count = count +1 print("aveage is:",sum/count)main()循環(huán)遍歷文件,通常的方法是用哨兵方法一次讀取文件的一行
這個(gè)可以用來讀取excel中的測(cè)試用例;
python中采用readline()方法的end-of-file循環(huán)模式:
readline()將文件的一行讀取到字符串中,在文件尾部readline()返回一個(gè)空字符串可以作為哨兵值;
line=infile.readline()while line != "":#處理每一行l(wèi)ine =infile.readline()
這段代碼會(huì)讓人誤以為遇到一個(gè)空行時(shí)就會(huì)退出,其實(shí)不然文本文件的空行包括一個(gè)換行符/n 這樣readline()函數(shù)返回值是換行符,而不是哨兵值空字符串,循環(huán)繼續(xù)
open() 打開文件讀取保存到list中
readline()讀取文件,每次讀取一行
4.死循環(huán)
python中可以用python完成特定的功能:
while True: try: x = int(input("輸入一個(gè)數(shù)字:")) break except ValueError: print("重新輸入:") copy()函數(shù):
返回字典的淺拷貝;
dict1={"name":"liyue"}dict2=dict1.copy()print("dict2 is:",str(dict2))運(yùn)行結(jié)果:
dict2 is: {'name': 'liyue'}
python讀取excel:
注意讀取時(shí)候加上表頭,沒表頭不行,所以測(cè)試用例要有表頭。
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選