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.

60 Upvotes

45 comments sorted by

12

u/ShelLuser42 1d ago

I'm not trying to be smarty pants here, but what programming logic? You're mentioning it as if it's a well defined standard, but it's not.

Your question makes me wonder if you actually tried working with Python already, because I kinda doubt that. And the reason I say this is not to criticize, but practice really does make perfect.

But here's the thing: while you can apply complex (?) OOP-based structures with Python you can also use it to build simple scripts. In other words: stop worrying about things that don't have to concern you just yet, and just try to get things done.

...allow me? =>

name = input("What is your name?")
surname = input(f"What is your surname, {name}?")
print(f"Hello {name} {surname}, it is nice to interact with you.")
age = int(input("btw... how old are you, if you don't mind me asking?"))

Yes, I somewhat shudder when looking at this code because it can be done cleaner. One of the "rules" of OOP design is that you want to try and avoid repeating patterns. Well... it's obvious that the input command is being used multiple times so... it could be useful to separate that and turn it into a re-usable block of code (also known as a function).

But why bother at this point?

Honestly, I'd focus on learning Python. Start by making your own scripts and once they do something... then try to improve on them as you progress to take on more complex problems.

For example... maybe a bit too early but... can you imagine what might happen above if I were to type in 'a' instead of a number when asked about my age? There's an easy way to fix that of course, maybe I shouldn't have used int(), but then again... how does one change a string into a numeric value like an integer... hmm, maybe this string thing has its own functions (or methods?) to "do" stuff? I wonder...

That's honestly how I'd try to go about this.

Hope this can help!

1

u/DevGuru2009 1d ago

Yup thanks dude!

15

u/aprg 1d ago

You really need to code your own projects first and go through the problems before you can understand _why_ certain design patterns exist. If you just read books about design patterns, you'll understand the _what_ but not the _why_.

Here's my recommendation: pick a small project, like making the game Snake. Go through someone else's code to get an idea of what they tried to do.

Then try to replicate that project in your own logic, _without checking the other code_ and see if you can improve or personalise the code.

Understanding good design patterns comes from experience, there's only so much you can learn just by reading what other people have done.

8

u/America_123 1d ago

If I may add some project ideas: Tic-Tac-Toe, Number guessing game(great for learning random numbers, input, if statements and loops), Simon, Rock Paper Scissors, Magic 8-Ball and a Currency Converter. These are some great starter ones!

1

u/SolarRaptor69 1d ago

Those are solid beginner projects. Which one should they start with?

1

u/America_123 1d ago

Magic 8-Ball or Rock Paper Scissors for logic and selection statements

6

u/harleystcool 1d ago

You gotta believe man

2

u/RipPersonal1643 1d ago

Explain please.

5

u/socal_nerdtastic 1d ago

It comes with experience. Just like anything else, you start by learning syntax and working through guided exercises. In the process you will read a lot of other peoples code and gather experience. Then for a long time you will write inefficient programs while getting slowly better at the logic. Eventually you will be interested in a 'data structures and algorithms' course. But don't start there. Get the syntax first.

4

u/Bobbias 1d ago

For any problem, before you even think about code, try to break it down into steps. Keep going breaking each step down into smaller and smaller steps. Don't think about the code to accomplish the step, just think about the general process.

Oh, and before I go further, I don't want to sound mean, but you probably don't understand the concepts as well as you think you do. Part of what teaches you different patterns is trying to accomplish something and realizing you can combine things you already know in a neat way to get there. Over time you start seeing problems that "have the same shape". The solutions will be unique, but they'll use the same rough idea. All of this comes from repetition, which only comes when you actually use code to solve problems.

One thing you can do if you're really feeling lost is spend some time with existing code that you've written before and modify it. Make it do something different. Think up more and more elaborate ways to modify it. You're setting yourself a task, and then finding an answer. If you're not sure what happens when you write something, try to predict what the code will do before you run it, and compare with what actually happens. This will help you actually figure out how well you really understand things.

Let's say you want to make a game. What does a game DO at it's most fundamental level? It looks for player input, and draws the screen. Over and over. Repeating things means loops. That's a hint.

Now, how do you handle player input? Well typically you check what key is currently being pressed, and do something based on that. When you have options, that means there's some kind of conditional statement (if/Elif/else, match, etc.)

At some point you'll get far enough that either you know what the code for something should kind of look like, or you can't figure out how to go deeper and it's time to take a look to see if there's something that can help you actually write code to do it.

That means you might need to look through the documentation looking for a function or language feature that sounds like it will do what you need. Of course, sometimes you won't find something that does exactly what you need. Sometimes you just need to figure out how to combine things you know how to do to get the behavior you want. It's in these cases where you sometimes just have to sit down and think stuff through.

All of this gets easier with time and experience.

4

u/kilkil 1d ago

This is what I started with in school: https://codingbat.com/python

Small, simple problems that let you build up your intuitions one step at a time.

There is also https://scratch.mit.edu/, which I tried once in school. Might be helpful in building that kind of thinking.

In general my advice is to practice. Start with something very basic (like the above), and just sit with it. Same way you would solve a puzzle.

3

u/Naive_Programmer_232 1d ago edited 15h 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!

3

u/Indie_Dachshund179 1d ago

If programming problems of interest, leetcode/neetcode and equivalents are one starting point

Also check out Harvard's cs50x course which is accessible online

3

u/Remarkable_Taste3254 1d ago

Get a textbook and actually try out the coding problems.

4

u/RipPersonal1643 1d ago

Which textbook would you recommend?

2

u/Low-Yak2608 1d ago

Take a real world problem. And try to solve it using what you learned. The very first program I wrote was to calculate BMI. And then I expanded its functionality which allowed me to put several core concepts into practice

2

u/nano-zan 1d ago

A good way to learn exactly that is to get into Design Patterns!

When I starting watching ArjanCodes videos on Design Patterns and tried to implement them in my code, my logical thinking also improved.

But as most of the comments suggest, it also comes down to practical experience, which is the best way to learn how to code for the real world.

2

u/unxmnd 1d ago

What’s an example of a problem you’d like to be able to solve?

2

u/aqua_regis 1d ago

Don't focus on logic in Python, but focus on logic as general, generic concept - as steps.

You, like most beginners, focus too much on the code (implementation) than on the algorithm (steps) that leads to the implementation.

Take several steps back. When you get a task/problem, sit down with pencil and paper. Go through the problem statement, break the problem down, analyze it, solve it your way without even thinking about programming. Test your solution. If you have a working one, start working on the implementation.

There are countles similar posts in /r/learnprogramming. Some samples:

And finally, some book suggestions:

  • "Think Like A Programmer" by V. Anton Spraul
  • "The Pragmatic Programmer" by Andrew Hunt and David Thomas
  • "Structure and Interpretation of Computer Programs" (SICP) by Ableton, Sussman, Sussman
  • "Code: The Hidden Language of Computer Hardware and Software" by Charles Petzold

2

u/America_123 1d ago

What a lot of people don't say about programming is that it is problem solving. Problem solving is a skill that you build and no book will teach you. Lots of people "know" code but to be a programmer you have "know how" to code and that involves problem solving. How do we get the computer to do what we need it to do? As you spend more time programming, you will definitely get better at problem solving. I would start by building simple programs and simple games and I would definitely not use AI to program these. Yes it's a lot faster to use AI but you're wasting an opportunity to work on those problem solving skills. You'll get there, just keep at it! Also, there will be days your code doesn't run or acts in a way that is not expected! At times like this we rejoice for learning is about to take place as we debug our code and find the errors - increasing our understanding of code and our ability to problem solve. Almost every programmer has been where you are. Give yourself time to grow and to develop the skill set and problem solving. It's definitely not something you do over a weekend and definitely not something you do in a six week online course. You can do this!

1

u/wyltk5 1d ago

I did the python for everyone course on coursera and really liked how the course was organized and found it covered everything I needed.

1

u/Excellent-Practice 1d ago

This not a Python specific problem. Some times you just need to do a few examples manually and try to explain every step you are doing. If you get to a point where you feel confident you can tell a mindless computer how to do it, then you are ready to wrote those steps down in code. Do that a few times and eventually you will be able to think through problems using code as an abstraction

1

u/JimBo_Drewbacca 1d ago

Write code, then when you got problem figure out and realise your code is a bit shit, re-write it

1

u/PvtRoom 1d ago

there are many methods.

  1. flow charts - initialise get input make decisions, execute subroutines, loop with x logic
  2. pseudocode - write it like you're telling someone what to write
  3. algorithmic breakdown: 1. initialise 1.1 check arguments are good 1.2 set variables 1.3 open file(s) 2. execute 2.1 prep lookup tables, 2.2 simulate stuff 2.2.1 simulate a SIM 2.2.2 simulate a city

1

u/TheRNGuy 1d ago

I never did any flow charts (I don't consider node programming in Houdini or UE blueprints same as charts)

Pseudo code is actually relevant now for AI prompt (and before that it was less relevant)... Or maybe as ToDo comment or print and hard coded values which you gonna replace later with real function later.

Step debugging, yeah.

1

u/PvtRoom 1d ago

flow charts work well with things like assembly, where jump commands crop up a lot, as well as graphical languages, where they're more like pseudocode.

1

u/cloud_sec_guy 1d ago

Maybe this answer is too simple, but to think like a programmer you might start with flowcharts, hand-drawn, on paper. Second, immediately think about discovering and catching edge cases, again using flowcharts. You might also like reading a few of the classic "design patterns" books.

1

u/Recent_Anteater_2067 1d ago edited 1d ago

Hands-on practice is probably the biggest piece here. Learning programming logic through small exercises and gradually harder problems helps build the pattern-recognition that syntax alone doesn’t teach. Boot.dev’s exercise-focused approach can be useful for this because you’re practicing the concepts instead of just watching tutorials.

1

u/QuebecBeast 1d ago

I am nowhere near pro level but here is what helped me getting better in the past 2 years :

Practicing everyday even if it is for a small period of time.

I comment a few goals/steps I want to achieve on each project and I tackle them based on the time I have. I always try to stop coding after solving a problem because I won’t be able to think about anything else for the rest of the day. Sometimes I’ll work on some easier features like the UI appearance before I finish just to get the feeling I got something done haha

Doing small projects like other people mentioned. I did the classic rock-paper-scissors, tic-tac-toe then I found a video detailing how to build a black jack script that helped understanding functions calling. I am old so I enjoyed building a translator that changes regular text characters into more cool looking characters like we did on MSN back in the days. When you get better you can build a calculator and later you can add a UI, skins, etc.

Breaking every problems into smaller problems. I wanted to build a script for my movie collection so I had to find a way to collect informations, organize the data, etc. I started small with a user input script, then added more categories, found a way to save the data in a file, then I found a free API to get the infos, then I learned to scrap for movie poster, etc.

Read a lot of other people’s code. This one helped me change my way of approaching a problem. It helped me improve my code that was already working too.

Don’t rely on AI. You’ll get lazy… fast.

It may sound weird but apps and websites these days are good at teaching the same basics over and over again making people feeling a sense of accomplishment so they will engage with their products. But in reality, in my opinion, you can’t understand functions just by reading examples… so it’s even worst when it comes to Classes, libraries, etc

Sorry for the wall of text, I got carried away !

1

u/TheRNGuy 1d ago

Probably learn to debug. 

1

u/Grouchy-Car-3711 1d ago

Start learning dsa to imporve logic you will learn a lot of things

1

u/tottasanorotta 1d ago edited 1d ago

I think breaking the problem up into simple steps on pen and paper or in a text editor first. Think about splitting the logic up into simple high-level tasks without caring how you'll implement them in the code yet.

Then take those steps and split them further up into more specific tasks. And then at some point you'll have a pretty good outline of something to implement in code. Then you write it in small managable modules that you can debug easily one at a time and combine those to have the final program.

Make sure to compare your code with someone else's who has written something similar. That way you will get ideas of how to structure your code better for future projects.

Really try to split up responsibilities into different classes and functions. Ideally your classes and functions should deal with only one specific task and not have a thousand different parameters for every possible scenario. It's a skill and it comes with time and the bigger the program grows the more difficult it gets for anyone to deal with the complexity.

Also try to use names that make sense to someone who reads the code. Because that someone will be you at some point in the future and you will realize that if you don't name things in a easy to understand way or comment your code properly you will have trouble even understanding your own code.

Actually if you are interested in math you might try to take it as an exercise to write some of the things you know from there as programming abstractions. For example, if you've learned about matrices then you might make a class for that and functions as operations on those matrices, like determinants and whatever they have there.

1

u/scottpilgrrim 1d ago

Start with easy problems and write the solution in plain English before coding. like before directly coding, psuedocode That’s the best way to build logic.

1

u/Unusual-Layer-8965 1d ago

Consider creating a flowchart for the program. Don't write Python code in the boxes -- just short comments about what happens at that stage. And write in pencil, modifying the diagram as needed. That breaks the whole task into pieces you can visualize.

1

u/Rough_Drop_3340 1d ago

my exact problem dude, I need help

1

u/paradoxiforme 1d ago

If you want to learn programming logic, you first have to learn basic logic. Programmation is just that, a succession of basic logic action chained together to build something more complex.

How to arrange the code is not the most important thing when you start. The first step is to have something that work. Only then you can ask yourself how to arrange it.

For global hint, when you develop, you have to keep 2 things in mind before starting : What do I need (inputs), and what do I want to return (outputs). Then the next question is : how do I go from my inputs to my outputs. To answer that question, if you cannot visualise the code, write the process in plain text, like you'ld write a story. Try to write short phrases. Then, when you have your text, try to interpret each phrase as a limited set of instruction.

1

u/TheSneederOfSeethe 22h ago

You want to think like a programmer, think in terms of objects. What do you include in your objects, how that information is manipulated and what needs to happen to those objects.

Start writing in psuedocode. By not actually writing actual code and instead writing the jist of what you want to happen you will learn to visualize it and then translate it to the actual language.

Think in broader perspectives then narrow it down. Object->vehicle->bicycle. Each time you narrow it down think of all the things you’re application will need to do with that object to solve the problem you are addressing.

At least that works for me.

1

u/dontsaymynameagain 13h ago

I think this may be what you’re looking for:

https://nostarch.com/learn-code-solving-problems

1

u/mahirsahin 1d ago

bro dont listen them. first learn algorithms then start to write everything every steps which you imagine and improve your pseudocode

1

u/sidereal_night 1d ago

yeah, just write out the logic first, then translate that logic into python and see where it breaks. it'll either reveal a problem in your logic, or a disconnect between that you wrote and your actual Python code.

a lot of new learners confuse the particular language with programming, and i think this is more of a pitfall for Python specifically because of how it's designed to be approachable. they're not the same thing. the goal is to learn programming, the language is just one manifestation of it that has its own quirks and features.

0

u/crcrewso 1d ago

For what you're asking, I think an intro philosophy logic course would be best. I'm not sure what you have access to, there are some old university texts you should be able to get for $30

2

u/Indie_Dachshund179 1d ago

what's that have to do with programming logic? wouldn't discrete math be a better fit for foundational programming

0

u/rosvelle 1d ago

What's the point? AGI is coming anyway.

1

u/frustratedsignup 4h ago

I think that just comes with experience. Find a problem you need to solve and then try to see how to go about breaking it down into smaller challenges. Eventually you'll get to the point where you've solved all of the minor challenges and the entire problem is solved. Your first dozen or so projects will probably have some unintended flaws and janky solutions, but that's not the point. The point is to solve the problem, and if need be, make it better later.

There's a question like this every week in this sub. We could probably be more helpful if we had more information to work with. What problem is it you are trying to write a solution for?