'Python continue function wont start the code all over again

I am trying to start the whole code again but it restarts the current loop can someone help?

while guessp1 & guessp2 != answer:
        if guessp1 == answer:
            print(player1, " won!")
            while True:
                answers = str(input("Play again? (y/n): "))
                if answers in ("y","n"):
                    break
                print('invalid input.')
            if answers == "y":
                continue
                
            else:
                quit()```


Solution 1:[1]

There are a number of issues with the posted code, which are addressed later in this answer. For a start, a working example (which can be modified to your liking) is posted below.

Key elements:

  • An outer loop as a simple While True which will continue to execute until a break statement is reached (within its scope).
  • A single 'Play again?' prompt, nested into an inner while loop, courtesy of the new (Python 3.8+) walrus operator.

Example:

p1 = 'Terry' 
answer = 'spam'

while True:
    guess = input('\nWhat goes with eggs? ')
    if guess == answer:
        print(f'{p1} won!')
        while (resp := input('Play again? [y|n] ').lower()) not in ('y', 'n'):
            print('Invalid input.')
        if resp != 'y':
            break
    else:
        print('Sorry, try again.')

Code issues:

  • The first while statement mixes a bitwise AND and a logical difference operators. Given the variables involved, this will not work.
  • Additionally, the first while loop is evaluated as while ((guessp1 & guessp2) != answer) which is not only not the desired evaluation as this will always evaluate to False, unless the value of answer is True or False, but will also throw an unsupported operand error due to the attempted bitwise operation on strings.
  • Once this is fixed (as while True), the loop runs infinitely as we aren't provided with all of the variable definitions from the code proceeding this block. Therefore, debugging stopped here.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 S3DEV