While Loops, how do they work?

I’m not new to python as a whole but I’m very bad at it however, I want to learn. I’ve tried to do some coding but I want to know what everything is actually doing rather than just reciting things online so if some of you could explain it to me as if I was like a baby that would make me really happy.

I would say an LLM tool may be more helpful in this case, just for the reactivity of the response and for an experience more tailored to your needs.

That said, a while loop is concept related to control flow, they’re not a python exclusive feature and basically any programming language uses it in some form. I would say start with the wikipedia article about it to get some familiarity.

While Loops, how do they work?

while condition:
    code

Run the code again and again while the condition is True.

For example:

cookies = 5

while cookies > 0:  # condition is cookies > 0
    print("Eating a cookie")
    cookies -= 1

You also have the notion of infinite loop:

while True:
    print("ok")

You would need to have a condition in the body of the loop for it to brake out of it.

Or use a break statement.

while True:
    print("ok")
    break

This prints “ok” just once. Usually, break follows an ‘if’ condition.

I think stepping through some loops with a good debugger can do wonders for a software developer’s intuition of what loops are for.

Both for this code:

i = 0

while i < 10:
    i = i + 1

Note that Memory Graph is discussed here: Request for Feedback: Memory Graph – A Python Visualization Tool for Education

Just to add something that is not present in all languages: the condition can be also an object. In that case, bool() or len() are called implicitly if the type supports them. Usually len is supported by iterables:

>>> a = [1, 2]
>>> while a:
...     a.pop()
...     
2
1
>>> a
[]

This will work because in the first operation, len(a) is applied, and it returns 2. And the integers supports bool(): bool(n) == True, apart bool(0) == False. To be precise, 1 == True and 0 == False, since True and False are of the type bool, that is a subtype of the int type.

The condition can also contain a combination of boolean operators and objects:

>>> a = []
>>> while not a:
...     a.append(1)
...     
>>> a
[1]

With some exceptions, if the object doesn’t support bool() or len(), it will be evaluated to True.

This is not something that is applied strictly to while: it’s applied every time you test for the “truthiness” of the object:

>>> a = []
>>> x = not a
>>> x
True

I use while with the walrus operator := when I read binary data in set sizes:

with open('video.ts','rb') as video:
    while packet := video.read(188):
        parse_packet(packet)

It’s surprisingly fast and keeps your code readable.

You can even go double walrus to read bigger chunks and then split them.

import io

packetsize =188
chunksize = packetsize * 10000
with open('video.ts','rb') as video:
  # first walrus
  while chunk := io.BufferedReader(video, buffer_size=chunksize):
    # second walrus
    while packet := chunk.read(packetsize):
      parse_packet(packet)
i = 0
while True:
    print(i)
    if i >= 3: break
    i += 1
/home/me/PycharmProjects/WelcomeScreen/.venv/bin/python Bb.py 

0
1
2
3

Process finished with exit code 0

So, while is kind of a if statement,
where while execute if condition is True.

See, while has i <= 3, but if condition had i >= 3.

i = 0
while i <= 3:
    print(i)
    # if i >= 3: break
    i += 1
/home/me/PycharmProjects/WelcomeScreen/.venv/bin/python Bb.py 
0
1
2
3

Process finished with exit code 0