Thursday, June 11, 2015

Project 2 of the 100 Projects: Higher or Lower (in Python)

I was inspired by a post on Liquidthink.net about what the author terms the 100 projects challenge, and I decided that I'll try to do as many as I can too, also in Python.

So without further ado, a quick and (hopefully) clean implementation of Higher or Lower in Python. It's only 29 lines, which is an amount I'm rather pleased with.



import random
toguess = 0
def getmax():
    return int(input("Enter the maximum number to guess: "))
def setnum():
    return random.randint(1, getmax())
def guessnum():
    try:
        guess = int(input("Enter a guess: "))
    except SyntaxError:
         print("That's not a number. Try again.")
          return guessnum()
    return guess
def mainloop():
     toguess = setnum()
     currguess = guessnum()
     count = 1
     while currguess != toguess:
          count += 1
          if currguess < toguess:
               print("Too low.")
          else:
               print("Too high.")
          currguess = guessnum()
     toprint = "You won in {0} turns! Try again? ".format(count)
     print(toprint)
     x = raw_input("")[0]
     if x == "y" or x == "Y":
          mainloop()
mainloop()
It's on Pastebin for easier reading here and I put it on a Gist a couple minutes ago.
I'm rather proud of the way in which I handled the main loop (aptly titled mainloop()) without being excessively verbose and making use of return statements in a pretty efficient manner.

No comments:

Post a Comment