Guess the number game is really simple to implement in Python using just a few lines of code. The article talks about one such program where a player can guess a random number between 0 and 1000.
Environment
The code is built and executed using the following tools,
- Operating System - Windows 10
- Interpreter - Python 3.10
- Editor - Visual Studio Code
The number to be guessed is chosen first and the player is given a set of chances to guess the number. On each turn, the player guesses a number and the code will indicate whether to guess higher or lower or the player had won.
import random random.seed() chosenNum = random.randint(0, 999) guessLeft = 10 while guessLeft > 0: print(f"Guesses Left : {guessLeft}") playerNum = input("Guess [0-999]: ") if not playerNum.isnumeric(): print("error: invalid input, guess again!") continue playerNum = int(playerNum) if (playerNum == chosenNum): print("Yay! you guessed the number.") exit(0) elif (playerNum < chosenNum): print("Guess higher!") else: print("Guess lower!") guessLeft -= 1 print(f"Oh no! The number was {chosenNum}!")
The chosenNum variable holds the number that the player needs to guess. The guessLeft variable holds the maximum number of guesses available to the player, for each guess the variable is decremented, when guess reaches zero, the player had run of guesses. Under such cases, the code will output the chosen number with a message. The logic of checking the number match is achieved by using comparison operators. The output is as follows
> python.exe num_guess.py Guesses Left : 10 Guess [0-999]: 100 Guess higher! Guesses Left : 9 Guess [0-999]: 200 Guess higher! Guesses Left : 8 Guess [0-999]: 300 Guess higher! Guesses Left : 7 Guess [0-999]: 400 Guess lower! Guesses Left : 6 Guess [0-999]: 350 Guess lower! Guesses Left : 5 Guess [0-999]: 325 Guess higher! Guesses Left : 4 Guess [0-999]: 337 Guess higher! Guess [0-999]: 345 Guess higher! Guesses Left : 2 Guess [0-999]: 348 Guess higher! Guesses Left : 1 Guess [0-999]: 349 Yay! you guessed the number. > python.exe num_guess.py Guesses Left : 10 Guess [0-999]: 1 Guess higher! Guesses Left : 9 Guess [0-999]: 2 Guess higher! Guesses Left : 8 Guess [0-999]: 3 Guess higher! Guesses Left : 7 Guess [0-999]: 4 Guess higher! Guesses Left : 6 Guess [0-999]: 5 Guess higher! Guesses Left : 5 Guess [0-999]: 6 Guess higher! Guesses Left : 4 Guess [0-999]: 7 Guess higher! Guesses Left : 3 Guess higher! Guesses Left : 2 Guess [0-999]: 9 Guess higher! Guesses Left : 1 Guess [0-999]: 10 Guess higher! Oh no! The number was 961!
Thanks for reading. Please leave comments or suggestions (if any).
Comments
Post a Comment