Fix Errors in Python Guessing Game Explained

I made a guessing game in Python where the goal is to guess a secret word. The player has three attempts to input the correct word. If the player uses up all their tries and fails to guess it correctly, the game prints “OUT OF GUESSES.” If the player succeeds, it prints “you win.”

However, I’m running into some errors in the code that I can’t seem to resolve. Below is the code I wrote:

Here the code I wrote:

codeTotal_Guesses = 3
Guess = ""
G = 1
Seceret_Word = "Lofi"
Out_of_Guesses = False

while guess != Seceret_Word and not(Out_of_Guesses):

if G < Number_of_Guesses:
guess = input("Enter your guess: ")
G += 1
else:
Out_of_Guesses = True

if Out_of_Guesses:
print("OUT OF GUESSES")
else:
print("you win")

Issues I’ve Noticed in the Code:

  1. Variable Name Typos:
    • In the while loop, I mistakenly used guess instead of Guess (variable names are case-sensitive).
    • Seceret_Word is also misspelled (should be Secret_Word).
  2. Incorrect Variable Name Reference:
    • The if G < Number_of_Guesses line references Number_of_Guesses, which doesn’t exist. It should be Total_Guesses.
  3. Syntax Error:
    • There’s no colon (:) at the end of the if G < Number_of_Guesses line, which causes a syntax error.
  4. Initialization Problem:
    • The Guess variable needs to be referenced consistently throughout the code, but it is not used correctly in the while loop due to the typo.

Below is the corrected version of your guessing game:

Corrected Code:

codeTotal_Guesses = 3
Guess = ""
G = 1
Secret_Word = "Lofi"
Out_of_Guesses = False

while Guess != Secret_Word and not Out_of_Guesses:
if G < Total_Guesses:
Guess = input("Enter your guess: ")
G += 1
else:
Out_of_Guesses = True

if Out_of_Guesses:
print("OUT OF GUESSES")
else:
print("you win")

Explanation of the Fixes:

  1. Corrected Typos:
    • Changed Seceret_Word to Secret_Word and guess to Guess to maintain consistency.
  2. Fixed Variable Reference:
    • Changed Number_of_Guesses to Total_Guesses to use the correct variable name.
  3. Added Colon:
    • Added the missing colon at the end of the if G < Total_Guesses: line.
  4. Consistent Variable Usage:
    • Ensured that the same variable names (Guess and Secret_Word) are used throughout the code.

This corrected version should now run without errors. When the user guesses the word correctly, it prints “you win,” and if they exhaust all their guesses, it prints “OUT OF GUESSES.”

Final Thought:

By following naming conventions and structuring logical conditions effectively, you ensure that your code is not only functional but also easy to read and maintain. Debugging becomes much easier when your variables are named consistently, and your conditions are logically ordered. Always keep refining your code these small improvements will make a big difference in writing bug-free programs!

Related blog posts