I just created a small game and I want to repeat it if the user wants to. i created an input and after words tried to set the guess_count variable back to 0, so i thought it will trigger the while loop again.
secret_number = 8
guess_count = 0
guess_limit = 3
while guess_count < guess_limit:
guess = int(input("Guess the number: "))
guess_count = 1
if guess == secret_number:
print("You won!")
break
else:
print("Sorry, you failed!")
try_again = input("Try again? ")
if try_again == "yes":
guess_count = 0
CodePudding user response:
Setting the guess_count
back to 0
in the else
block will not trigger the loop again. This is because the else
block is executed after the loop has exited. You might want to move the logic to restart the loop into the loop itself. eg.
secret_number = 8
guess_count = 0
guess_limit = 3
while True:
if guess_count >= guess_limit:
print("Sorry, you failed!")
try_again = input("Try again? ")
if try_again == "yes":
guess_count = 0
continue
else:
break
else:
guess = int(input("Guess the number: "))
guess_count = 1
if guess == secret_number:
print("You won!")
break
CodePudding user response:
playing = True
secret_number = 8
while playing:
guess_count = 0
guess_limit = 3
while guess_count < guess_limit:
guess = int(input("Guess the number: "))
guess_count = 1
if guess == secret_number:
print("You won!")
break
else:
print("Sorry, you failed!")
try_again = input("Try again? (yes/no) ")
if try_again == "no":
playing = False