Я пытаюсь упростить свой код, создав функцию вне цикла while, но условия, которые я хочу ввести в функцию, имеют операторы break

#python-3.x #function #while-loop

Вопрос:

Ниже приведен пример моего кода. Я пытаюсь создать функцию для своего 4-го условного оператора вне цикла while, но некоторые вложенные условные выражения имеют оператор break. Как я могу создать функцию вне цикла, но все равно выйти из цикла, когда мне это тоже нужно.

 current_room = 'security room'
directions = ['north', 'south', 'east', 'west']
all_items = ['Thermal Rifle', 'Blood Wine', 'Protein Bar', 'Bandages', 'Keys', 'Time Grenade', 'Note']    

while True:
    # Print current room
    print('-' * 60)
    print(f'You are in {current_room.title()}')
    print('Inventory:', inventory)

    prompt = 'What is your move:n$ '
    user_command = input(prompt).lower().strip()
    split_command = user_command.split(' ', 1)

    if user_command == 'quit':
        print()
        print('Exiting game....')
        break
    elif user_command == 'show items':
        print(all_items)
        time.sleep(1)
    elif user_command == 'help':
        menu()
        time.sleep(2)
    # if command direction is in rooms update current room to new room
    elif split_command[0] == 'go':
        # This is code I want to turn into a function outside of the loop
        # but my issue is the two break statements in the code
        if split_command[1] in directions:
            if split_command[1] in rooms[current_room]:
                current_room = rooms[current_room][split_command[1]]
                # if command direction is kahmeetes office congratulate and break out of loop
                if current_room == 'kahmeete's office' and len(inventory) == len(all_items):
                    print(f'nCongratulations! You have collected all items and reached {current_room}!')
                    print('You have successfully defeated Kahmeete and saved the Princess of Time!')
                    break
                elif current_room == 'kahmeete's office' and len(inventory) != len(all_items):
                    print(f'nYou are in {string.capwords(current_room)}')
                    print('nYou do not have enough items to defeat Kahmeete!')
                    print('Kahmeete used the T.T.A.D. "Time Traveling Alien Device on you!"')
                    print('You are lost in the past and you will never rescue the Princess of Time!')
                    break
            else:
                print('You cannot go that way!')
                time.sleep(1)
 

Вот основа функции:

 def moving_rooms(command, direction, room, current_loc, item, all_item_list):
    if command[1] in direction:
        if command[1] in room[current_loc]:
            current_loc = room[current_loc][command[1]]
            # if command direction is cellar congratulate and break out of loop
            if current_loc == 'kahmeete's office' and len(item) == len(all_item_list):
                print(f'nCongratulations! You have collected all items and reached {string.capwords(current_loc)}!')
                print('You have successfully defeated Kahmeete and saved the Princess of Time!')
                # This is where the break statement would be

            elif current_loc == 'kahmeete's office' and len(item) != len(all_item_list):
                print(f'nYou are in {string.capwords(current_loc)}')
                print('You do not have enough items to defeat Kahmeete!')
                print('Kahmeete used the T.T.A.D. "Time Traveling Alien Device on you!"')
                print('You are lost in the past and you will never rescue the Princess of Time!')
                # This would of been where the break statement was
        else:
            print('You cannot go that way!')
            time.sleep(1)
    else:
        print('Invalid input')
        time.sleep(1)
 

Ответ №1:

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

 elif split_command[-] == 'go':
    done = handle_go_command(args)
    if done:
        break
 

Теперь просто return True в вашей функции, когда вы этого хотели break , и return False там, где вы хотите, чтобы внешний цикл продолжался.