Python Function () - невозможно выйти из функции и вернуться в основную - PullRequest
0 голосов
/ 10 июля 2020

Я пытаюсь выполнить приведенный ниже код с условием, что если для элемента переменной введено нулевое значение, он должен выйти. Но он не завершается и возвращается к первой строке функции.

    def order():
        orderName = input('What would you like to call this order? :')
        print(""" Please place your order below.
        To stop Placing your order, leave the item name empty. """)

        item = input("Item: ")
        price = input("Price: ")
        quantity = input("Quantity: ")  # gets all the info they want to add
        print("-----------------------------------------------")

        with open("mypc.txt", "a") as a_file:
            a_file.writelines(quantity + "|" + price + "|" + item + "\n")

        while True:
            item = input("Item: ")
            if item == "":
                return
            price = input("Price: ")
            quantity = input("Quantity: ")  # gets all the info they want to add
                   
        with open('mypc.txt', 'r')as Task2:
            for row in Task2:
                row = row.strip()
                eachItem = row.split("|")

        a_file.close()
        print('Order saved to ' + orderName +
              '.txt. Exiting Application...')

    def menu():

        # Check if file exists
        if os.path.isfile('mypc.txt') == False:
            # Create it and promptly close it, so it is in the correct location
            task1 = open('mypc.txt', 'w')
            task1.close()

        # Open for read-write
        task2 = open('mypc.txt', 'r+')

        # splits for new line break, making an array
        info = task2.read().split("\n")


   def main():

       ans = ''

       while ans != '0':

            print(""" Welcome to the Crapple Order Management System. You can
              1. Place an Order
              2. Process an Order
            """)

            menu()
            option = input("What would you like to do? (Select 1 or 2) : ")

            if option == '1':
                order()
            elif option == '2':
                reciept()


    if __name__ == "__main__":
        main()

Присоединение ниже образца вывода, полученного при выполнении кода.

    Welcome to the Crapple Order Management System. You can
            1. Place an Order
            2. Process an Order

    What would you like to do? (Select 1 or 2) : 1
    What would you like to call this order? :mypc
     Please place your order below.
        To stop Placing your order, leave the item name empty. 
    
    Item: Asus PRIME X570-P ATX AM4 Motherboard
    Price: 149.99
    Quantity: 1
    -----------------------------------------------
    Item: AMD Ryzen 5 3600 3.6 GHz 6-Core Processor
    Price: 149.99
    Quantity: 1
    -----------------------------------------------
    Item: 
    
    Welcome to the Crapple Order Management System. You can
            1. Place an Order
            2. Process an Order

    What would you like to do? (Select 1 or 2) :

когда предоставляется второе входное значение для переменной Item, оно не добавляется к файлу, и в файл записывается только первое значение.

Любая помощь в решении этой проблемы будет значительной оценен.

Спасибо, Чандра.

...