Repeat while loop if input is a specific string

Question:

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
Asked By: Indubio

||

Answers:

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
Answered By: BaxJimmy

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
Answered By: theundeadmonk
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.