Skip to content

Instantly share code, notes, and snippets.

@ahk
Created Aug 1, 2012
Embed
What would you like to do?
my edit included
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