Instantly share code, notes, and snippets.

Embed
What would you like to do?
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