Skip to content

Instantly share code, notes, and snippets.

@tmitzka
Created May 21, 2018 10:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tmitzka/f0c53d7a220e263e387e4ed4c78a5ae8 to your computer and use it in GitHub Desktop.
Save tmitzka/f0c53d7a220e263e387e4ed4c78a5ae8 to your computer and use it in GitHub Desktop.
Guess my number: try to guess a random number as fast as possible.
"""A game in which the player tries to guess a random number."""
import random
def guess_number():
"""Create variables and run the game loop."""
number = random.randint(1, 100)
print("I'm thinking of a number between 1 and 100.")
print("Can you guess it?")
guesses = 0
wrong_numbers = []
while True:
guess = ""
while (
not guess.isdigit() or
int(guess) not in range(1, 101) or
guess in wrong_numbers
):
guess = input("\nYour guess: ").strip()
if not guess.isdigit() or int(guess) not in range(1, 101):
print("You have to enter a number between 1 and 100.")
elif guess in wrong_numbers:
print(f"You already tried {guess}.")
guesses += 1
if guesses == 10:
print("Let's end this game, you took too long.")
print(f"My number was {number}.")
break
wrong_numbers.append(guess)
guess = int(guess)
if guess < number:
print("That's too low. Try a higher number.")
elif guess > number:
print("That's too high. Try a lower number.")
else:
print(f"Correct! My number is {number}.")
print("That took you", end=" ")
if guesses == 1:
print("just one guess. VERY impressive!")
elif guesses <= 5:
print(f"{guesses} guesses. Well done!")
else:
print(f"{guesses} guesses. Not bad.")
break
def main():
"""The main function of the game."""
while True:
guess_number()
answer = ""
while answer not in ("y", "n"):
answer = input("\nPlay again? (y/n) ").strip().lower()
if answer == "n":
break
else:
print()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment