Created
August 1, 2012 06:45
-
-
Save ahk/3224336 to your computer and use it in GitHub Desktop.
my edit included
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import random | |
import sys | |
def main(): | |
# 1. generate a random number within the range | |
# determined by the user | |
guessUpperLimit = int(raw_input("Enter the upper limit for the target number: ")) | |
targetInt = random.randint(0, guessUpperLimit) | |
print "Okay, I've got my number!" | |
# 2. Allow the user to guess the target number, | |
# returning "Too small", "Perfect!" or "Too large", | |
# depending on their relationship | |
userGuess(targetInt, guessUpperLimit) | |
# 3. Ask the user if they would like to play again | |
userPlayAgainOrNot() | |
def userGuess(targetInt, guessUpperLimit): | |
guessInt = input("Enter a guess (an integer between 0 and %d): " %guessUpperLimit) | |
if guessInt == targetInt: | |
return "Perfect!" | |
else: | |
if guessInt > targetInt: | |
print "Too large! Try again!" | |
userGuess(targetInt, guessUpperLimit) | |
elif guessInt < targetInt: | |
print "Too small! Try again!" | |
userGuess(targetInt, guessUpperLimit) | |
def userPlayAgainOrNot(): | |
tryAgain = raw_input("Would you like to try again? (y/n) ") | |
if tryAgain == "y": | |
main() | |
elif tryAgain == "n": | |
print "Thanks for playing!" | |
sys.exit(0) | |
else: | |
print "I'm sorry. I didn't get that." | |
userPlayAgainOrNot() | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment