To write break or continue within Python function (continue not professionally in loop error)

Asked 2 weeks ago, Updated 2 weeks ago, 2 views

def inputUser(table, cnt):
    x = int (input ("Enter the following number of x coordinates: ")))
    y = int (input ("Enter the following number of y coordinates: ")))

    #Check the coordinates entered by the user
    if board[x][y] != '':
        print("Invalid Location".")
        continue
    else:
        board[x][y] = 'X'
        cnt += 1

def main():
    cnt = 0
    flag = True
    drawBoard(board)
    while flag:
        inputUser(board, cnt)
        flag = computer(board, cnt)
        drawBoard(board)


main()

Like the above code, there is a while statement in the main function, inputUser function in the main function, and there is a while statement outside the inputUser function. In the process of defining the inputUser function here, the 'continue not successfully in loop' error appears when writing continue because there is no repeat statement within the inputUser function. How can we solve this?

python

2022-09-20 16:27

1 Answers

It would be impossible to use break or continue within the inputUser function for the reason you mentioned. And we can return the value we want when the function ends with a return. So this is possible.

//inputUser
if condition:
    //~~~
    return True

//in the main's while
while flag:
     if inputUser():
        continue
    else:
        break


2022-09-20 16:27

If you have any answers or tips


© 2022 pinfo. All rights reserved.