Introduction

In my journey as a Software Engineering student at Ensign College, I believe that even the simplest projects are opportunities to implement best practices. This Python-based number-guessing game might look straightforward, but it incorporates essential programming concepts such as input validation, loop control, and data privacy.


The Code

import getpass  # Importing the library to handle sensitive input

# Securely setting the target number
correct_number = int(getpass.getpass('Enter your number (it will be hidden): '))
guess_count = 0
guess_limit = 3

while guess_count < guess_limit:
	guess_count += 1
	attempts_left = guess_limit - guess_count
	guess = int(input('What is your guess? '))
	
	if guess == correct_number:
	    print('You guessed it!')
	    break
	else:
	    if guess_count < guess_limit:
	        print(f'You have {attempts_left} attempt(s) left! Please try again!')
	        
else:
# This block executes if the while loop completes without a 'break'
print(f'You failed! The correct answer is number {correct_number}.')
                                                **

Please run this code on your PC

guessing game python.png

The game is running on the terminal


Key Technical Insights

1. Prioritizing Security with getpass

Most basic guessing games hardcode the "correct number" or leave it visible in the terminal. By using the getpass library, I ensured that the person setting the challenge can enter the secret number without it being displayed on the screen. This mimics real-world security scenarios, such as password entry.

2. Efficient Loop Management

The game uses a while loop combined with a break statement. This ensures that the program terminates immediately upon a correct guess, saving computational resources and providing instant feedback to the user.

3. The while-else Construct

One of Python's unique features is the else block associated with a while loop. In this project, I used it to handle the "Game Over" state. The else block only triggers if the loop finishes naturally (after 3 failed attempts) and not if it's interrupted by a break. This makes the code cleaner and more Pythonic.

4. Dynamic User Feedback

Using f-strings, the program provides real-time updates on the number of attempts remaining. This enhances the User Experience (UX) by keeping the player informed and engaged throughout the process.