r/learnpython • • Mar 30 '21

How are you ‘planning’ your code?

There’s a thousand videos on Youtube on how to code Python - but they seem to be more like function references - which you can look up in the documentation?

How you guys and girls think through what you’re about to write?

Should I write 90 lines of code then reorganise it into functions? Or start writing functions and then finally ‘use’ the functions at the bottom of your code/script?

Is there a best practice way of doing this? I’m trying to make it easier for myself so everything works like ‘lego’ - otherwise I find I get really confused

Should I write down the steps as comments and then fill in the code after?

‘’’ getjson() Function will accept json string and return TSV def getjson():

‘’’ getinputs() function will read argv[1:] and return the first parameter, or exit with error message if none specified def getinputs():

‘’’ writetosql() function will accept TSV and write it to final.db def writetosql():

‘’’ Run the functions inputs=getinputs() tsv=getjson(inputs) writetosql(tsv)

349 Upvotes

107 comments sorted by

View all comments

2

u/Hikaru2000 Mar 30 '21

Step 1: Any note taking software (or pen and paper, whichever you prefer) and write the problem asked and then refine it into a workable problem statement.

Step 2: List down the steps or processes required to achieve the goal.

Step 3: Write a rough pseudo-code (it can be as simple as just going into the details of the steps or as much as just noting the various functions you'd use at various steps)

Step 4: Start writing your code (this part depends on the programmer themselves). I usually just list down all the functions I need with initial parameters and outputs, then go to the main code. As I keep adding to the main code, my functions may change (I work with datasets for a Pattern Recognition course and this happens at times). So I wait before writing any function. At this stage, I also import any libraries etc that are required.

Step 5: I split the code into sections (separate them based on the steps in Step 2). As I finish writing one section and verify there's nothing more to be added there, I write the functions used in that part. Similarly for all sections. Then I run and debug the code section-wise (Jupyter Notebook makes this easy).

Step 6: (This is the most important step) Once it works properly, I stay away from it and don't touch it at all. (Just ensure it works properly, make it readable, add comments if necessary. Ensure that if you look at the code at a later time, you should understand what you are doing).