Sitemap
Lynchable Things

Lynchable Things

Some Writings About AI and Alives

Number Guessing Game in Python

2 min readJan 24, 2023

This code is an implementation of a number guessing game as described in your prompt. The play_game() function is where the main logic of the game is implemented. It first generates a random number between 1 and 100 using the random.randint() function, and then enters a loop where it repeatedly prompts the player to guess the number. The player's guess is stored in the guess variable and is checked against the randomly generated number. If the guess is correct, the player is congratulated and the loop is broken. If the guess is too high or too low, the player is prompted to try again.

The signal_handler function is used to catch the "ctrl+c" signal and display a message before exiting the program, and the outer while loop in the __name__ == "__main__" block allows the game to continue until the player presses the "ctrl+c" combination.

Get Lynchable Things’s stories in your inbox

Join Medium for free to get updates from this writer.

This program will run continuously until the player press ctrl+c combination. player have to enter a number between 1 to 100 and program will check the number if it is correct or not and accordingly prompt the player

import random
import signal
import sys

def signal_handler(sig, frame):
print("\nThanks for playing!")
sys.exit(0)

def play_game():
# Generate a random number between 1 and 100
answer = random.randint(1, 100)

while True:
try:
# Get player's guess
guess = int(input("Guess a number between 1 and 100: "))

# Check if guess is correct
if guess == answer:
print("Congratulations, you guessed the correct number!")
break
elif guess < answer:
print("Too low, try again.")
else:
print("Too high, try again.")
except ValueError:
print("Invalid input, please enter a number.")

if __name__ == "__main__":
signal.signal(signal.SIGINT, signal_handler)
print("Welcome to the number guessing game! Press ctrl+c to quit.")
while True:
play_game()

By the way, you don’t really need to use “signal” module because when use push ctrl+c together while terminal is running, it will break cycle of game and exitting the game.

Thanks for reading.

To promote author please buy an item from his ebay store. Here is the link to ebay store:

Author’s Ebay Store

--

--

Lynchable Things
Lynchable Things

Written by Lynchable Things

Some Writings About AI and Alives