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)
1
u/_G0D_M0DE_ Mar 31 '21
How I start depends on the paradigm I have chosen (or one that has been chosen for me), whether its procedural (imperative), object-oriented, functional, or even combination of paradigms. At work, I'm mainly operating under OOP requirements. So my code is compartmentalized into classes and instantiated into objects. This can get rather complicated because it involves design patterns.
For beginning programmers, most simple programs are mostly going to involve procedural programming. And in that case, I would think about the logically separable components of the program and abstract those out to be functions. The most abstract and simple way to consider procedural programs are in terms of IPO (Input, Processing, and Output). You will have a portion of your code gather input from a client/user. That data is then processed into information based on some business rule or algorithm, and then the results are presented to the client/user. Client or "user" could be an actual person entering in data through a console or GUI interface, from a file, or even from another program (see UNIX philosophy).
Python makes it really simple to produce function stubs thus allowing you to fill in the details of those implementations later. And this is very helpful when employing an incremental and iterative development process. I would definitely make use of that feature. For example:
And at the top-level you simple put in a function call when necessary. And the name of the function should reflect the isolated logic you want peformed.
Good luck!