Skip to content

Instantly share code, notes, and snippets.

@marcusholmgren
Created April 5, 2020 15:23
Show Gist options
  • Save marcusholmgren/997d27898602bde5ee26e2490bc72aa7 to your computer and use it in GitHub Desktop.
Save marcusholmgren/997d27898602bde5ee26e2490bc72aa7 to your computer and use it in GitHub Desktop.
Simple game where you guess a random number between 1 - 25
#!/usr/bin/env python3
# Guess the Number
# 1. Ask the user how many times they would like to play
# 2. For every game, ask the player to select a random number between 1 - 25
# 3. Inform the player if the number is higher or lower
# 4. Build a loop statement that will iterate number of games and numbers picked
# 5. When user guess correct, tell them how many guesses it took
import random
def welcome():
print("Welcome to the game - Guess the Number")
print("Your objective is to guess a random number between 1 - 25")
print("")
def start():
games = None
while games is None:
games = get_numeric_input("How many time would you like to play? ")
for game in range(games):
print(f"\n-=== Game {1+game} ===-")
guesses, target, play = play_game()
if not play:
return
print(f"Yay it was {target}! You guessed correctly in {guesses} attempts.")
def play_game():
target = random.randint(1, 26)
correct = False
guesses = 0
while not correct:
answer = None
while not answer:
answer = get_numeric_input("Guess a number between 1 - 25? ")
if answer == 0:
return guesses, target, False
if answer < target:
print("Please provide a higher number.")
elif answer > target:
print("Please provide a lower number.")
guesses += 1
correct = answer == target
return guesses, target, True
def get_numeric_input(prompt):
try:
user_input = input(prompt)
if user_input.lower() == 'q':
return 0
return int(user_input)
except ValueError:
print("Please provide a number.")
if __name__ == '__main__':
welcome()
start()
print("\nGoodbye and thanks for playing!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment