国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術文章
文章詳情頁

基于Python測試程序是否有錯誤

瀏覽:4日期:2022-07-25 13:10:44

1、首先介紹簡單的try......except嘗試運行的放例如下面的圖和代碼來簡單介紹下:

def test(x,y): print(x+y)try: test()except: print(’Error’)test(2,4)

test測試的函數,沒傳參數的x,y,函數結果是要答應x加y的和

try:試著執行test()函數,正常就執行函數并打印x加y的和

except:否則 打印’Error’ 因為我這test沒有給x,y定義傳參數,所以會走到except

結果:

基于Python測試程序是否有錯誤

2、我們以上次排球比賽程序為例子做測試:

from random import randomdef printIntro(): #打印程序介紹信息 print('10號張穎慧進行比賽分析結果:') print('這個程序模擬兩個選手A和B的某種競技比賽') print('程序運行需要A和B的能力值(以0到1之間的小數表示)')def getInputs(): #獲得程序運行參數 a = eval(input('請輸入選手A的能力值(0-1): ')) b = eval(input('請輸入選手B的能力值(0-1): ')) n = eval(input('模擬比賽的場次: ')) return a, b, ndef simNGames(n, probA, probB): # 進行N場比賽 winsA, winsB = 0, 0 for i in range(n): for j in range(7): #進行7局4勝的比賽 scoreA, scoreB = simOneGame(probA, probB) if scoreA > scoreB:winsA += 1 else:winsB += 1 return winsA, winsBtry: simNGames(0.55)except: print('simNGames Error') def gameOver(a,b):#正常比賽結束 return a==24 or b==24def gameOver2(a,b): #進行搶12比賽結束 if abs((a-b))>=2: return a,bdef simOneGame(probA, probB): #進行一場比賽 scoreA, scoreB = 0, 0 #初始化AB的得分 serving = 'A' while not gameOver(scoreA, scoreB): #用while循環來執行比賽 if scoreA==10 and scoreB==10: return(simtwoGame2(probA,probB)) if serving == 'A': if random() < probA: ##用隨機數生成勝負scoreA += 1 else:serving='B' else: if random() < probB:scoreB += 1 else:serving='A' return scoreA, scoreBtry: simOneGame(0.54)except: print('simNGame Error') def simtwoGame2(probA,probB): scoreA,scoreB=23,23 serving = 'A' while not gameOver2(scoreA, scoreB): if serving == 'A': if random() < probA:scoreA += 1 else:serving='B' else: if random() < probB:scoreB += 1 else:serving='A' return scoreA, scoreBtry: simtwoGame2(0.44,0.66)except: print('simNGame2 Error') def printSummary(winsA, winsB): n = winsA + winsB print('競技分析開始,共模擬{}場比賽'.format(n)) print('選手A獲勝{}場比賽,占比{:0.1%}'.format(winsA, winsA/n)) print('選手B獲勝{}場比賽,占比{:0.1%}'.format(winsB, winsB/n))def main(): printIntro() probA, probB, n = getInputs() winsA, winsB = simNGames(n, probA, probB) printSummary(winsA, winsB)main()

這個代碼中,在一些函數后用try.....except測試了一遍,如果有錯誤會分別對某個函數進行報錯。

因為小編在參數中故意寫錯,故會出現錯誤

運行結果如下:

基于Python測試程序是否有錯誤

當然還可以執行多個函數及條件的測試都可以,這樣可以實現自動化測試業務代碼,還可以穿插在程序中你需要的地方

做檢測等,這樣你的程序會按流程走,這塊又可以得到你要的測試效果。來看看代碼如下:

x = 0lis_y = [i for i in range(80,85)]def test(x,y): print(x+y,' ')def test1(x,y): print(x*y)try: while x < 20: for y in lis_y: test(x,y) test1(x,chr(y)) x+=1except: print(’Error’)

運行結果如下:

基于Python測試程序是否有錯誤

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。

標簽: Python 編程
相關文章:
主站蜘蛛池模板: 浑源县| 伊吾县| 怀远县| 高密市| 建宁县| 新巴尔虎右旗| 贡嘎县| 淄博市| 岳阳县| 怀宁县| 三穗县| 博客| 福鼎市| 丰原市| 福清市| 武城县| 西平县| 泰兴市| 新干县| 磐石市| 平利县| 德昌县| 叶城县| 巨鹿县| 西青区| 合江县| 横峰县| 大石桥市| 榆树市| 奇台县| 广昌县| 垫江县| 永城市| 福清市| 茂名市| 大兴区| 东阳市| 墨玉县| 龙胜| 古丈县| 新化县|