Feb-06-2019, 09:30 PM
If you put your game logic in a function, then you can call that function repeatedly from a while loop.
For example:
For example:
>>> import random >>> def play_game(): ... secret_number = random.randint(1, 10) ... print("I'm thinking of a number from 1 to 9. You have three guesses to get it.") ... for guess in range(3): ... attempt = input(f"Guess #{guess+1}: ") ... try: ... if int(attempt) == secret_number: ... return True ... except ValueError: ... print("That's not a number :(") ... else: ... print("Incorrect") ... return False ... >>> running = True >>> while running: ... winner = play_game() ... if winner: ... print("You got it!") ... else: ... print("Sorry, you ran out of guesses.") ... try_again = input("Play again? [yes/no] ") ... running = try_again[0].lower() == "y" ... I'm thinking of a number from 1 to 9. You have three guesses to get it. Guess #1: 2 Incorrect Guess #2: 4 Incorrect Guess #3: 9 Incorrect Sorry, you ran out of guesses. Play again? [yes/no] YES I'm thinking of a number from 1 to 9. You have three guesses to get it. Guess #1: 1 Incorrect Guess #2: 2 Incorrect Guess #3: 3 Incorrect Sorry, you ran out of guesses. Play again? [yes/no] no