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()
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