'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 Truewhich will continue to execute until abreakstatement is reached (within its scope). - A single 'Play again?' prompt, nested into an inner
whileloop, 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
whilestatement mixes a bitwise AND and a logical difference operators. Given the variables involved, this will not work. - Additionally, the first
whileloop is evaluated aswhile ((guessp1 & guessp2) != answer)which is not only not the desired evaluation as this will always evaluate toFalse, unless the value ofanswerisTrueorFalse, but will also throw anunsupported operanderror 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 |
