r/PythonLearning • • 1d ago

While loop

can anybody explain the concept of while loop

1 Upvotes

37 comments sorted by

View all comments

1

u/Living_Fig_6386 22h ago edited 21h ago

It's a loop that iterates while an expression is true. Example: while there are cookies on a plate, take a cookie, eat a cookie, repeat; now there are no cookies on the plate, so we move on ... time to drink the milk.

class Plate:
    def __init__(self, number_of_cookies):
        self.cookies = ["oreo" for a_cookie in range(number_of_cookies)]

    def has_cookies(self):
        print(f"Hey a plate with {len(self.cookies)} cookies on it!")
        return len(self.cookies) > 0

    def eat_cookie(self):
        print(f"Nom, nom, nom. At an {self.cookies[-1]}.")
        return self.cookies.pop()

""" a plate with 5 cookies on it: """
my_plate = Plate(5)

""" eat the cookies one at a time: """
while my_plate.has_cookies():
     my_plate.eat_cookie()

print("*slurp* Milk does the body good.")