Python Forum
Thread Rating:
  • 1 Vote(s) - 5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help with functions
#2
If you put your game logic in a function, then you can call that function repeatedly from a while loop.

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
Reply


Messages In This Thread
Help with functions - by joshneedshelp - Feb-06-2019, 12:24 PM
RE: Help with functions - by nilamo - Feb-06-2019, 09:30 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020