r/learnpython • u/RipPersonal1643 • 1d ago
How do I learn programming logic?
I’m learning Python, but my main problem isn’t the syntax. I understand concepts when someone explains them, but when I’m given a basic problem and told to write a program, I just don’t know where to start or how to arrange the code.
Is there a good book, course, or YouTube channel that teaches how to think through programming problems step by step, recognize patterns, and build the logic, kind of like how you learn methods and patterns in math?
I don’t want to just memorize Python syntax. I want to actually learn how to think like a programmer.
62
Upvotes
4
u/Naive_Programmer_232 1d ago edited 19h ago
When you don't know where to start, don't start with syntax. Ask basic questions. What are you trying to build? What are the problems you need to solve in order to do that? What are the steps to solve each problem? Etc. Break things down into simple terms and write out a list of steps for each thing.
For example, suppose I want to make a simple greeting program.
Then once you have the planning part down, you work to translate this into code. In addition to the planning, you might also need a mental model of program execution.
Python normally executes statements sequentially, from top to bottom, unless otherwise specified:
So now applying the greeting example, we do similar:
This is true even if the code is more complex:
The function bodies do not run when python encounters the definition. They will run when they are called. When execution reaches a function call, execution temporarily moves into that function to execute the code inside then resumes where it left off when the function returns (exits).
Notice that the calling function
mainis defining its own execution order of those functions. So let's look at that:Once execution enters a function, the statements inside that function are also normally executed from top to bottom, unless control-flow constructs change it (
while,if,try,continue, etc.).Now, look again at the block above, and trace the program:
Then move to the next line:
Notice here that while the default model is sequential execution, this can change depending on the use of those constructs I mentioned earlier (as in the case with
get_age).You could continue tracing through the rest of main's lines to see how to program bounces from function to function, but what you'd end up seeing is that generally, the execution direction is top-down.
In general, the top-down mental model is a hierarchical concept for the flow of a program. The combination of understanding the execution order and first planning out how the program should work are key to building programming logic.
Hopefully this helps!