[Python] Queues in Python loop does not give me a choice to put input?

Discussão em 'Python' iniciado por Stack, Maio 11, 2025.

  1. Stack

    Stack Membro Participativo

    I ran this code and had two problems:

    1. when I ran it it displays 'Invalid choice please enter a number between 1 and 4' even right after the main menu print
    2. when I input the choice 1 it doesn't prompt me to input an item the code just stops

    import queue

    q1 = queue.Queue()

    def enqueue(item):
    q1.put(item)
    print(f"Enqueued: {item}")

    def dequeue():
    if not q1.empty():
    item = q1.get()
    print(f"Dequeued: {item}")
    else:
    print("Queue is empty.")

    def display():
    if not q1.empty():
    print("Queue:", list(q1.queue))
    else:
    print("Queue is empty.")

    def main():
    print("\nQueue Operations:")
    print("1. Enqueue")
    print("2. Dequeue")
    print("3. Display Queue")
    print("4. Exit")

    choice = input("Enter your choice (1-4): ")

    if choice == '1':
    item = input("Enter item to enqueue: ")
    enqueue(item)
    elif choice == '2':
    dequeue()
    elif choice == '3':
    display()
    elif choice == '4':
    print("Exiting program.")
    else:
    print("Invalid choice. Please enter a number between 1 and 4.")
    main()


    my expecting outcome was:

    • the menu prints
    • I input 1
    • input option pops up for me to input an item
    • item gets enqueue into q1

    my actual outcome:

    • main menu prints
    • "Invalid choice. Please enter a number between 1 and 4" prints
    • prompt to input choice prints
    • I input one
    • code doesn't prompt for an item for me to input

    Continue reading...

Compartilhe esta Página