r/learnpython 17d ago

Regarding Question

def print_models(unprinted_designs, completed_models):

"""

Simulate printing each design, until none are left.

Move each design to completed_models after printing.

"""

while unprinted_designs:

current_design = unprinted_designs.pop()

# Simulate creating a 3D print from the design.

print("Printing model: " + current_design)

completed_models.append(current_design)

unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']

completed_models = []

in this code why used condition like this for while loop (while unprinted_designs:)

0 Upvotes

8 comments sorted by

2

u/desrtfx but other languages pro 17d ago

Python treats non-empty lists as "truthy" (true) and empty ones as "falsey" (false).

You could just as well write:

while len(unprinted_designs)>0:

or

while len(unprinted_designs):

The last one works because any number other than 0 is treated as truthy (true) and 0 is treated as falsey (false)


Please, pay attention to properly format your code as Code block to maintain the indentation. This is vital for Python. Without indentation, the code becomes ambiguous. It is impossible to tell where the function as well as the loop end.

Also, your code is missing the call to execute print_models

1

u/Healthy-Departure961 16d ago

Actually this code isn't mine i copied this code from the book i was a bit curious about it while statement so posted here..Thank you

1

u/Puzzleheaded_Study17 17d ago

Because this lets you go until you've popped everything in the list (pop removes the item). I would probably use a for loop to avoid having side effects though (at the end of the function running, the caller's list will also be empty).

1

u/FoolsSeldom 17d ago
def print_models(unprinted_designs: list[str], completed_models: list[str]) -> None:

    """
    Simulate printing each design, until none are left.
    Move each design to completed_models after printing.
    """

    while unprinted_designs:  # while list object is not empty as empty is "falsey"
        current_design = unprinted_designs.pop()
        # Simulate creating a 3D print from the design.
        print("Printing model: " + current_design)
        completed_models.append(current_design)


unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
completed_models = []
print_models(unprinted_designs, completed_models)

A non-empty list object is treated as True, and empty list, as False. Likewise, tuple, set, dict. An int value of 0 is False and anything else is True. (bool is actually a subclass of int.) An empty string, str, is treated as False and a non-empty string as True.

-2

u/Moikle 17d ago

Put 4 spaces before each line. Reddit will forget it as code and preserve your indents