Task
For this project, we will try to create a simple project that will collect a user’s input and allow them to guess the value that the computer has generated (randomly). Essentially, a simple guessing game.
Source
Code:
import random
# we will keep track of values here
attempts_count = []
# we will define a score method
def score():
if len(attempts_count) <= 0:
print("There is currently no high score")
else:
print("The current high score is {} attempts".format(min(attempts_count)))
# adjust values, we will have it be between 1 - 10
def begin():
# generate value between 1 - 10
random_num = int(random.randint(1, 10))
print("Let's play a little guessing game!")
# collect user inputs
name = input("Input your name: ")
prompt = input("Hi, {}, want to play the game? (Enter Yes/No) ".format(name))
attempts = 0
score()
while prompt.lower() == "yes":
try:
# the guessing range is between 1 - 10
guess = input("Pick a number between 1-10 ")
if int(guess) < 1 or int(guess) > 10:
raise ValueError("Guess a value between 1-10")
if int(guess) == random_num:
print("Nice! You got it!")
attempts += 1
attempts_count.append(attempts)
print("It took you {} attempts".format(attempts))
play_again = input("Play again? (Enter Yes/No) ")
attempts = 0
score()
random_num = int(random.randint(1, 10))
if play_again.lower() == "no":
print("Bye, bye.")
break
elif int(guess) > random_num:
print("Lower")
attempts += 1
elif int(guess) < random_num:
print("Higher")
attempts += 1
except ValueError as err:
print("Invalid input")
print("({})".format(err))
else:
print("Bye, bye.")
if __name__ == '__main__':
begin()
Output:
Let's play a little guessing game!
Input your name: Michael
Hi, Michael, want to play the game? (Enter Yes/No) Yes
There is currently no high score
Pick a number between 1-10 5
Lower
Pick a number between 1-10 2
Nice! You got it!
It took you 2 attempts
Play again? (Enter Yes/No) Yes
The current high score is 2 attempts
Pick a number between 1-10 8
Lower
Pick a number between 1-10 4
Lower
Pick a number between 1-10 2
Higher
Pick a number between 1-10 3
Nice! You got it!
It took you 4 attempts
Play again? (Enter Yes/No)
For more information
If you seek to learn more about Python, please visit Python’s official documentation.
Michael is an Information Technology consultant, with a focus on cybersecurity. Every day, Michael strives to learn something new, with an aim to share it with you all!