Как мне выйти из a для l oop через некоторое время l oop и вернуться наверх? - PullRequest
0 голосов
/ 09 июля 2020
while True:
    new_move = input('Enter the coordinates: ')

    # check if cell is already occupied
    for i, el in enumerate(location):
        if new_move == el and cells[i] != '_':
            print('This cell is occupied! Choose another one!')
            break

    # check if new_move contains non-numerical values
    if not new_move.replace(' ', '').isdigit():
        print('You should enter numbers!')
        continue

    # check if new_move goes beyond 3
    if int(new_move[0]) > 3 or int(new_move[2]) > 3:
        print('Coordinates should be from 1 to 3!')
        continue

    # retrieve index of new_move that matches given coordinate
    for i, el in enumerate(location):
        if new_move == el and cells[i] == '_':
            # replace given index with 'X'
            new_cells = cells[:i] + 'X' + cells[i + 1:]
            # print new board state
            print('---------')
            print(f"| {' '.join(new_cells[0:3])} |")
            print(f"| {' '.join(new_cells[3:6])} |")
            print(f"| {' '.join(new_cells[6:9])} |")
            print('---------')
            

* отредактировано, потому что я пропустил важную информацию в своем предыдущем вопросе

Вопрос OG:

Как мне выйти из for l oop и вернуться к началу while l oop (т.е. снова запросить ввод new_move)? На данный момент код зацикливается, только если я удовлетворяю двум другим операторам if, но не оператору if внутри for l oop. Он просто прыгает прямо к остановке и не возвращается в исходное положение. Я не могу успешно разместить continue в любом месте для l oop.

Я решил это, реализовав решение user212514. Но теперь у меня проблема в том, что я не выхожу из while l oop, когда final for l oop завершено / выполнено. Я не могу разместить там оператор break, не испортив что-нибудь еще.

Ответы [ 2 ]

0 голосов
/ 09 июля 2020

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

def is_occupied(position, location):
    for i, el in enumerate(location):
        if position == el and cells[i] != '_':
            return true

    return false

while True:
    new_move = input('Enter the coordinates: ')

    # check if cell is already occupied
    if is_occupied(new_move, location):
        print('This cell is occupied! Choose another one!')
        continue

    # check if new_move contains non-numerical values
    if not new_move.replace(' ', '').isdigit():
        print('You should enter numbers!')
        continue

    # check if new_move goes beyond 3
    if int(new_move[0]) > 3 or int(new_move[2]) > 3:
        print('Coordinates should be from 1 to 3!')
        continue
0 голосов
/ 09 июля 2020

Вы можете использовать break в for:

while True:
    new_move = input('Enter the coordinates: ')

    # check if cell is already occupied
    for i, el in enumerate(location):
        if new_move == el and cells[i] != '_':
            print('This cell is occupied! Choose another one!')
            break

    # check if new_move contains non-numerical values
    if not new_move.replace(' ', '').isdigit():
        print('You should enter numbers!')
        continue

    # check if new_move goes beyond 3
    if int(new_move[0]) > 3 or int(new_move[2]) > 3:
        print('Coordinates should be from 1 to 3!')
        continue

Пересмотренный вопрос и ответ

Похоже, вы захотите использовать переменную для предотвращения оценки if s после for.

while True:
    new_move = input('Enter the coordinates: ')
    good_coordinates = True
    for i, el in enumerate(location):
        if new_move == el and cells[i] != '_':
            print('This cell is occupied! Choose another one!')
            good_coordinates = False
            break

    if not good_coordinates:
        continue

    # execute your other if statements
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...