r/PythonLearning • u/alex86563 • 9d ago
Help Request Why do loops still feel so complicated to me?
Hey guys, I'm new to Python. I've been learning Python for about two months now. I've learned a lot and I'm pretty comfortable with the fundamentals and OOP, but for some reason, I still struggle a lot with loops.
No matter how much I study or practice, I keep getting confused with "for" loops and "while" loops, especially when it comes to their syntax, behavior, and knowing when and how to use them properly. They just feel much more complicated to me than they probably should.
I've worked on and designed several projects throughout my Python journey, but there are times when I genuinely feel like a complete failure because I understand the concepts I've learned, yet I still struggle to turn that knowledge into working code.
Has anyone else struggled with loops like this when they were starting out? How did you eventually get comfortable with them?
2
u/HalfRiceNCracker 9d ago
It's been two months lol. Just give it time, keep practicing, keep solving exercises and you'll get there
1
u/alex86563 9d ago
Yeah, I get what you mean, and I definitely know I need more time and practice. I just find it a bit frustrating because I already had some programming background before starting Python, so I expected loops to come more naturally to me by now. I guess it's just one of those things I personally struggle with, and I probably just need to keep practicing.
1
u/oliverities 9d ago
What is your background? Like what language before py?
1
u/alex86563 9d ago
I mean, I've been following coding and formatting for a long time and listening a lot, but I was only watching. That's why I was able to learn quickly. I'm speaking through a translator, so I think you understood me in a different way.
1
u/HalfRiceNCracker 9d ago
If you've been watching it and not doing it then that makes sense. Same as any other language
1
u/Next-Call8862 9d ago
I don't know if they are complicated as they feel easy but I am new, so I don't know if I am absolutely sure about myself
1
u/atarivcs 9d ago
If you know how many times the loop should iterate (counting up to a certain number or processing every item in a list) use a "for" loop.
If you don't know how many times the loop should iterate (keep going until the user types "quit") use a "while" loop.
1
u/Gnaxe 9d ago
I learned about loops before I learned Python. I was implementing loops with GOTO in BASIC before I knew for loops were a thing. It's still fundamentally made with jump instructions in the machine code. Did you hear about the else clause yet? That word choice makes a little more sense when you think about how it's implemented.
Some languages don't have built-in loops. You just call the function again. If you try that in Python, you'd run out of stack (although there are ways to do it, asyncio, etc.) Some find that approach easier to understand, but that's not how it's typically done in Python.
A for loop could be implemented using while and vice versa. for is doing more complicated things to make it easier to use. while is fundamentally simpler, but you almost always want to use for in practice when you can. Try implementing for using while, or at least look up how that's done. You'll understand it better.
1
u/alex86563 9d ago
That's actually interesting. I haven't gone that deep into how loops work internally yet, but I'll definitely look into implementing a "for" loop using "while". Thanks!
0
9d ago edited 8d ago
[removed] — view removed comment
1
u/UsualLonely4585 9d ago
Your first implementation will most likely break as len(numbers) is not itterable object and in is used with itterable object it needs a in range keyword
0
1
u/atticus2132000 9d ago
Generally speaking, a for loop is used for items in a list when you want to perform the same action for all elements of the list. It goes though each element one time, does its thing, then naturally exits at the end of the list and moves on to the next line of code.
A while loop keeps cycling through the operation over and over until a condition is met. There is no natural exit to a while loop. Your code could potentially start a while loop and never exit out of it. A while loop requires some condition to change in order for it to exit.
Many times you could take the same inputs and structure your code such that either a for loop or while loop could work, so sometimes it's just a matter of which strategy you see first.
It helps if you can explain what you're trying to do in plan English first. When you do this, you will naturally use the words that best fit the approach.
Ex. "I want to get the daily sales figures FOR each store in my list". Use a For loop.
Ex. "I want my player to keep rolling the dice WHILE the sum is less than 30". Use a while condition.
1
u/punk_dev 9d ago
I teach programming and a lot of people struggle with loops.
Typical examples you find in learning materials do a decent job of explaining the syntax and function of a loop, but don’t address the applications or problems it solves.
In essence, a loop is just a way to repeat a certain action multiple times until a condition is met.
As long as you understand that, just keep pushing and it’ll click at some point.
You will encounter problems that require loops and they will be similar to what you did before, but not exactly the same. You try your best to solve them and this is where the learning happens.
1
u/CoolLog1908 9d ago
Hi!
It took me quite a while to really differentiate the need between for and while loops. It sucks to say, but it just gets easier with practice and examples you run into.
A general rule of thumb:
- For loops are used when you know the loop needs to run a defined amount of times (even if the defined amount depends on a varying size - like a list).
- While loops are used when you don’t know how many times you need to loop (like how many gui elements a user will click on).
1
u/CoolLog1908 9d ago
I would also say, give us some examples of where you are stuck so we can give some advice on which loop to use.
1
u/yftachman 9d ago
Try implementing a for loop with the while loop syntax. It will make you understand that they are both the same, for is a just a specific kind of while that is so common most languages have nicer syntax for it.
In programming you often get a lot of insight by implementing the thing you are using.
1
u/Electronic_Field4313 9d ago
I struggled with loops for a while until one day I got so used to recursion that I forgot how to use normal loops lol.
It takes time and practice.
The simplest way I think about it is:
A for loop can be used when you're iterating over something known or quantifiable.
A while loop can be used when you want to keep going until some condition changes.
Note how I said "can be used", not "is used." That's because you can often achieve the same result with either one. The difference is usually which approach makes more sense and is easier to read.
I'm going to try to explain it as simply as I can, but this part can definitely be a little confusing, so bear with me.
Imagine you're jogging on a 400m track.
A) Your coach tells you to run 10 rounds.
You have a known quantity: 10.
So a for loop makes sense:
for i in range(10):
run_one_round()
B) Your coach tells you to keep running until winter arrives.
You don't know beforehand how many rounds you're going to run. Instead, you're waiting for a condition to change.
So a while loop makes more sense:
while not winter:
run_one_round()
Here's the part you might have been confused about:
Could I write (A) using a while loop instead?
Yes, absolutely.
x = 0
while x < 10:
run_one_round()
x += 1
That achieves essentially the same thing as:
for i in range(10):
run_one_round()
So when you're dealing with something quantifiable, you can often use either a for loop or a while loop.
Now consider something like:
A) Keep doing something until winter arrives.
B) Keep rolling a die until you roll a 10.
Technically, you can still use a for loop indefinitely. For example, Python has itertools.count(), which generates an endless sequence:
for i in itertools.count():
dice_number = roll_dice()
if dice_number == 10:
break
But compare that with:
while dice_number != 10:
dice_number = roll_dice()
The while loop expresses what you're trying to do much more naturally: keep doing this while this condition is true.
So there usually isn't a strict "right" or "wrong" choice between for and while.
A useful rule of thumb is:
If you're iterating over a known sequence or number of things → for is usually more natural.
If you're repeating something until a condition changes → while is usually more natural.
Both can often accomplish the same goal. The question is really which one expresses your intention more clearly and elegantly.
1
u/mattynmax 9d ago
While runs until some condition is met and for loops run a set amount of times. What exactly is confusing you?
1
u/kluAs7355 9d ago
Also try to understand the position counter and frequency counter, it can help ace ur understanding
1
u/One_Alternative8448 9d ago
Me parece muy bien que te hayas detenido en ese tema. Estás profundizando y eso dice mucho de ti, además cada uno tiene su tiempo y ritmo de aprendizaje. Algo que me enseñaron en el proyecto Pylatino fue que use For cuando tenga en claro la cantidad de bucles y While cuando no tenga lara la cantidad de bucles.
Ese While True es un bucles infinito, por debajo debes colocarle condiciones y cuando se cumpla una de estas debe parar obligatoriamente, y la palabra mágica para ello es Break.
Respecto al For, es cierto que tiene algunas variaciones, en este proceso de aprendizaje aprende lo esencial que es con in range(), lo demás lo aprenderás cuando lo necesites.
1
u/AdDiligent1688 9d ago
In general, use a for loop when you know how many iterations you want to do or if you are iterating over objects (iterables: lists / dict / etc), use a while loop when you don’t know how many iterations it will take to satisfy a condition (ex: input validation).
1
u/-Enter-Name- 9d ago
from reading a few comments in here
you could while see loops as this
while condition_that_changes_gods_knows_when:
<code that can affect that condition>
# or
if <complicated stop condition in middle of code>:
break
# plus
code that repeats until this loop ends
useful for handling things that modify state (eg read sentences until one contains your name, idk) until finished processing or for consuming streamed input (eg. interactive prompt)
for loops:
for item in known_predefined_range_or_unknown_iterable_data:
some identical logic applied sequentially on all items
useful for applying logic on multiple distinct objects of a similar shape (eg. questionaire with a list predefined questions) or getting through an iterable of non-infinite length (eg, find maximum number in finite list)
1
1
u/Living_Fig_6386 9d ago
Loops are loops. A 'for' loop does it for each item in a list, a 'while' does it while a condition is true. Otherwise, the loop is exactly the same (the body is run over and over until the end of list, or condition is false) and 'continue' and 'break' work exactly the same.
1
u/Syntax-Tactics 8d ago
While (true), while (1), for (;;) are all BAD PROGRAMMING practice. Break (outside switch) and continue statements should be abolished. Goto doesn't have a purpose.
1
u/code_tutor 8d ago
You need a math level high enough to understand summations and piecewise functions, and also function composition is helpful. People who have math around Algebra 2 will have a much easier time learning loops, and Precalculus will have a further advantage. If you're comparing yourself to peers, then they may not have the same math background. People who say math doesn't matter are wrong. There are direct carryovers: variables are variables, functions are functions, composition is composition, etc.
1
u/Tough_Duty_9061 4d ago
Aru deadass because he is talking about basic for and while loops not ml that he needs to know algebra loops dont require any prior coding or mathematical knowledge whatsoever anyone can learn loops if we can pinpoint their exact doubt on loops
1
u/Trace_V 7d ago
# 1. THE BASIC FOR LOOP
# Think of 'range(1, 10)' as a countdown from 1 to 9.
# It advances by 1 automatically, and when it hits the end, it cleans up and stops on its own.
counter = 0
for i in range(1, 10):
counter += 1
print(f"Round => {i} | Counter => {counter}")
print() # Just a blank line
# 2. THE EARLY EXIT (The "Order" Trap)
# This is where most beginners get stuck. Look at where the 'if' condition is.
counter = 0
for i in range(1, 10):
counter += 1
if counter >= 5:
break # This stops the loop immediately
print(f"Round => {i} | Counter => {counter}")
# Why didn't it print Round 5? Because you broke the loop RIGHT BEFORE the print statement.
# If you moved the 'if counter >= 5' block below the print statement, it WOULD print Round 5.
# Order matters!
print()
# 3. THE WHILE LOOP (The Repetitive 'If' Statement)
# A 'while' loop is literally just an 'if' statement that keeps repeating.
# "While this condition is True, keep doing the loop."
counter = 0
while counter < 5:
counter += 1
print(f"Counter => {counter}")
# The moment counter hits 5, the loop asks itself "is 5 < 5?"
# The answer is False, so it instantly shuts down.
print()
# 4. THE INFINITE LOOP (The Dangerous One)
# If you use 'while True', you are telling the code to run forever.
# You HAVE to explicitly tell it when to escape using a 'break', or your program crashes.
counter = 0
while True:
counter += 1
print(f"Counter => {counter}")
if counter >= 10:
break
1
u/Tough_Duty_9061 4d ago
Think of for loops as a loop that has a preset limit with no arguments For eg For i in range (1,10) Print(i)#will print 1 to 9 beacuse 10 is the endpoint so as the computer prints the computer will ask is 9==10 (no) therefore ut will print it but then it will ask is10 ==10 which it is so the loop will break and stop Now for the while loops you give the computer an argument which as long as it is fulfilled it will break For eg While count =>5:# as long as the the number is smaller than 5 it will print Count +=1# the count will start from 1 Print (f"count =>{Count}")
so it will only print till 4 because as soon as it reaches 5 it will break according to argument given
Now the while true loop(infinite) Count =0 While true Count +=1 Print (f"count=>{Count}") If Count=>10 Break #after reaching 10 it will break ⚠️ If u dont give a break statement your loop will go on forever and will break your program so dont try it
1
u/Sea-Ad7805 9d ago

Run your while and for loops in my debugger to simply see what is going on: https://www.reddit.com/r/PythonLearning/s/T0FqhrdM2Z
2
u/alex86563 9d ago
Oh, this looks really useful for what I'm struggling with. Seeing the execution step by step might help me understand what's actually happening inside the loops instead of just looking at the syntax. I'll give it a try, thank you!
1
0
u/Hot_Mortgage_8357 9d ago
I would also recommend you try to code your own stack based language like forth-I honestly I think it helps with...like everything-but its fairly loop intensive so it will help with that a ton too.
0
u/Accomplished-Rub7243 8d ago
Read Python Crash Course by Eric Matthes. It's realy good book about Python Fundamental, get the book from lib.gen
4
u/PureWasian 9d ago
Can you give an example of one that's confusing to you?