๐Ÿ“– Beginning Python Programming /
Module: Controlling logic flow

while ...:

๐Ÿ“– Beginning Python Programming / Controlling logic flow / while ...:

Code Example: While-Input-List v4

def ask_for_list_name():
    '''Ask the user for list name to save.'''
    list_name = input("Please enter a list name: ")
    return list_name

def get_list_items_input(list_name):
    '''Ask user to input a collection of list items until type 'q'.'''
    items = []
    while True:
        value = input(f"Please input an item for {list_name}, or 'q' to quit: ")
        if value == "q":
            break
        if len(value) > 0:
            items.append(value)
    return items

def save_list(list_name, items):
    '''Save the given items into list_name.txt.'''    
    with open(f"{list_name}.txt", "a") as file_obj:
        file_obj.write("\n".join(items))
        file_obj.write("\n")


list_name = ask_for_list_name()
items = get_list_items_input(list_name)
save_list(list_name, items)
print(f"List saved to {list_name}.txt.")
In this code example, we define functions to make the code modularize. We will learn more detail about functions in module 5.