Coding a simple guessing game while learning Python basics. Game rules: The program repeatedly asks the user to input a guess, and increases the counter of guesses (guess_count) by 1. If the counter reaches a certain limit (guess_limit), the game says ("You loose"). If guessed correctly: ("You win")
I have two implementations and cannot understand, what design is conceptually more correct.
Variant 1: create a boolean variable out_of_guesses and set it initially to False
secret_word = "pythoniac"
guess = ""
guess_count = 0
guess_limit = 3
out_of_guesses = False
The program then executes a WHILE loop, the WHILE loop finishes either if the word was guessed or if the guess limit was reached and out_of_guesses == True.
while guess != secret_word and not out_of_guesses:
if guess_count < guess_limit:
guess = input("Enter a guess: ")
guess_count += 1
else:
out_of_guesses = True
After that, outside the WHILE loop, the programs checks, if out_of_guesses == True and prints ("You loose"). Else, it prints ("You win").
if out_of_guesses:
print("You Lose!")
else:
print("You Win!")
Variant 2: without additional boolean variable:
secret_word = "pythoniac"
guess = ""
guess_count = 0
guess_limit = 3
Within the WHILE loop, if the guess limit is reached, the program prints ("You lose") and breaks out of the loop with exit(). If the secret word was guessed, the program prints ("You win") outside the WHILE loop:
while guess != secret_word:
if guess_count < guess_limit:
guess = input("Enter a guess: ")
guess_count += 1
else:
print("You loose!")
exit()
print("You Win!")
The question: which variant is better as a general rule of thumb? To implement different outcomes within the WHILE loop and then break out of the WHILE loop with exit() / break? Or to introduce additional boolean variables to store different outcomes and implement these outcomes outside the WHILE loop?
many thanks in advance!
exit. Again, it may work fine in simple scenarios, but you'll likely need to refactor the code to remove it if you add any complexity to your program later. There may be some cases where exiting half-way through the program is easier that trying let the script end normally, but I wouldn't use it simply to remove a Boolean variable from a loop's logic. - Carcigenicate