Skip to content

Instantly share code, notes, and snippets.

@SzetoLok
Last active June 28, 2025 05:30
Show Gist options
  • Save SzetoLok/a84025ba6a70a61a1ba6b7286a23f132 to your computer and use it in GitHub Desktop.
Save SzetoLok/a84025ba6a70a61a1ba6b7286a23f132 to your computer and use it in GitHub Desktop.
Programming Task #2 Number guessing game
import random
def get_valid_guess(low: int, high: int) -> int:
"""
Prompt the user until a valid integer guess within [low, high] is entered.
Args:
low (int): The lower bound of the valid range (inclusive).
high (int): The upper bound of the valid range (inclusive).
Returns:
int: A valid integer guess from the user within the specified range.
"""
while True:
# Prompt the user for input
guess = input(f"Enter a number between {low} and {high}: ")
try:
guess_int = int(guess)
# Check if the guess is within the valid range
if guess_int < low or guess_int > high:
print(f'Invalid input. Please enter a number between {low} and {high}.\n')
continue
return guess_int
except ValueError:
# Handle non-integer input
print('Invalid input. Please enter an integer.\n')
def check_input(guess: str, answer: int, low: int, high: int) -> list:
"""
Evaluate the user's guess against the answer, print feedback, and update range.
Args:
guess (str): The user's guess as a string (will be converted to int).
answer (int): The target number to guess.
low (int): The current lower bound of the guessing range.
high (int): The current upper bound of the guessing range.
Returns:
list: [guess_is_correct (bool), new_low (int), new_high (int)]
"""
result = []
guess_is_correct = False
guess = int(guess)
if guess == answer:
print(f'Congratulations! You guessed the correct number: {answer}')
guess_is_correct = True
elif guess > answer:
print("Too high\n")
high = guess - 1 # Narrow the upper bound
elif guess < answer:
print('Too Low\n')
low = guess + 1 # Raise the lower bound
return [guess_is_correct, low, high]
def main():
"""
Main game loop for the number guessing game.
Generates a random answer and repeatedly prompts the user to guess,
providing feedback and updating the valid range until the correct number is guessed.
"""
guess_is_correct = False
answer = random.randint(1, 100) # Generate random target number
low = 1
high = 100
while not guess_is_correct:
# Get a valid guess from the user
guess = get_valid_guess(low, high)
# Check the guess and update game state
guess_is_correct, new_low, new_high = check_input(guess, answer, low, high)
low = new_low
high = new_high
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment