r/learnpython • u/brushygiraffe • 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)
2
u/RcNorth Mar 30 '21
Write down in simple steps what the program needs to do i.e.
Open CSV file
read through file and process each row
for each row insert record into SQLite database
etc.
Once you know what the program needs to do You can determine what needs to happen at each step i.e. how do I get the name of the file to process? (start with it hard coded then move to command line parameter or something else later)
Opening the file doesn’t need it’s own function as it is a single line. If processing each row is going to be complex move It to a function, if it is simple maybe a For loop is enough.
Start with displaying the results of each step print commands or looking at variable values in the editor. Only move to the next step when you are good with the process so far.
I’ve started with things in a for loop then had to move them to a function later to make the code easier to read or to provide better error handling than I thought I was going to need at the start.