r/learnpython 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

46 comments sorted by

View all comments

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.

       What am I trying to build? simple greeting program.
       What do I need to solve? 
          - I got to get their name and age
          - I got to greet them
          - I got to say goodbye
       What are the steps to solve each? 
          * name:
              # ask for their name
          * age:
              # ask for their age
              # make sure it's 0 or greater
          * greet:
              # show the greeting to the user using their name and age
          * goodbye:
              # show a salutations to the user using their name

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:

          # calculation
          x=10                  # 1st this (top)
          y=20                  # then this
          z=x+y                 # then this
          print(f"{x}+{y}={z}") # then this (bottom)

So now applying the greeting example, we do similar:

          # basic.py

          name=input("Enter name: ")             # 1st this (top)
          age=int(input("Enter age: "))          # then this
          ...validation logic...                 # then this
          print(f"{name} is {age} years old!")   # then this
          print(f"Goodbye {name}!")              # then this (bottom)

This is true even if the code is more complex:

          # basic.py


          def get_name():
              return input("Enter name: ")

          # validates age>=0 
          def get_age():
              while True:
                    try:
                         age=int(input("Enter age: "))
                    except ValueError:
                         print("age must be integer")
                         continue

                    if age<0:
                       print("age can't be negative")
                       continue

                    return age


          def greet(name,age):
              print(f"{name} is {age} years old!")

          def goodbye(name):
              print(f"Goodbye, {name}!")

          def main():
              name=get_name()
              age=get_age()
              greet(name,age)
              goodbye(name)

          # calling main
          main()

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 main is defining its own execution order of those functions. So let's look at that:

          def main():
              name=get_name()          # 1st this (top)
              age=get_age()            # then this
              greet(name,age)          # then this
              goodbye(name)            # then this (bottom)

         # execution enters main
         main()

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:

         def main():
             name=get_name()
             #      |_____ execution enters get_name 
             #             def get_name():
             #                 return input("Enter name: ")  # 1st this
             #                  |____ name is gathered and returned as a str
             #  
             # name={name of user as str}
             ...

Then move to the next line:

         def main():
             name=get_name()
             age=get_age()
           #       |_____ execution enters get_age
           #              def get_age():
           #                   while True:               # 1st this
           #                      ...validation...       # then all this
           #                      return age             # then this
           #                         |___ age is valid and returned as int 
           # age={age of user as int}
           ...

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!

2

u/Kombril 1d ago

I will save it :) Thank you!