Python programming method

Python programming ideas
1. Top down design
2. Bottom up execution
For example: sports competition code

1. Top down design

#Games.py

from random import random
def printIntro():
    print("Simulate two players A and B Some kind of competitive game")
    print("Required for program operation A and B Capability value of (0~1 Decimal representation between)")

def getInputs():
    a=eval(input("Please enter players A Capability value of:"))
    b=eval(input("Please enter players B Capability value of:"))
    n=eval(input("Number of simulated matches:"))
    return a,b,n

def simNGames(n,probA,probB):
    winsA,winsB=0,0
    for i in range(n):
        scoreA,scoreB=simoneGame(probA,probB)
        if scoreA>scoreB:
            winsA+=1
        else:
            winsB+=1
    return winsA,winsB

def gameover(a,b):
    return a==15 or b==15

def simoneGame(probA,probB):
    scoreA,scoreB=0,0
    serving="A"
    while not gameover(scoreA,scoreB):
        if serving=='A':
            if random()<probA:
                scoreA+=1
            else:
                serving="B"
        else:
            if random()<probB:
                scoreB+=1
            else:
                serving="A"
    return scoreA,scoreB

def printSummary(winA,winB):
    n=winA+winB
    print("Co simulation{}Match".format(n))
    print("A The number of games won is{},Proportion{:0.1%}".format(winA,winA/n))
    print("B The number of games won is{},Proportion{:0.1%}".format(winB,winB/n))

def main():
    printIntro()
    proA,proB,n=getInputs()
    winsA,winsB=simNGames(n,proA,proB)
    printSummary(winsA,winsB)

main()

2. Bottom up execution
The best way to execute a medium-sized program is to start at the bottom of the structure diagram and then go up gradually. Or run and test each basic function first, and then test the whole function composed of basic functions, which helps to locate errors.

The Python interpreter provides import reserved words to assist test unit development. The syntax format is as follows:
Import < source file name >

Note that the source file name cannot have a period (.)

For example, unit test the gameover() function of the above code. The code is as follows:

>>>import Games
>>>Games.gameover(15,10)
True

When using spyder, input gameover(15,10) directly in ipython, for example:

Tags: Python Programming IPython

Posted on Mon, 30 Mar 2020 23:12:39 -0700 by valoukh