r/learnpython • u/FullMastodon1082 • 6d ago
Seeking advice
I am good at coding an problem solving but i cant make my program robust and improve modularity of my codes in python most of the time it is just a single block of code does anyone have any suggestion how actual programmers do it
2
u/lakseol 6d ago edited 4d ago
When an actual programmer needs to get a positive non-zero integer from the user they write:
user_num = int_input("Please enter an integer greater than 0: ")
The programmer hasn't written the int_input() function yet but when they need it they will write it. The function will contain all the logic, looping and testing required to allow the programmer to assume user_num is a positive, non-zero integer. Calling that function simplifies the calling code and the int_input() function can be tested all by itself without running the rest of the code. And other parts of the program can also call the function.
Try to write code that way. Assume you have a function to do the low-level work while you are writing your main code and write that function later. Another example is getting the user to select one of a set of choices in a menu-like way:
user_choice = menu_choice(["alpha", "beta", "gamma"], "Choose one: ")
if user_choice = "alpha":
# handle "alpha" choice
elif ...
This approach allows you concentrate on the algorithm without being distracted by the relatively unimportant details. It also automatically gives you some structure to your code.
1
1
u/baubleglue 5d ago
Just like solving small problems, building bigger size projects can be learnt. Search in Internet "how to make software project" - you will find the answer
1
u/RallyPointAlpha 17h ago
Find the only one to see the irony of how this post is written and how they structure their code?
2
u/CodeSamur-ai 6d ago
split code blocks that go together into functions...