Pretty clean looking code, but let's look at a few ways it could be better or more pythonic:
Use
elif
statements:if personInput == randnumb: # ... elif personInput > randnumb: # You already know they're != at this point # ... elif ...
Use snake case for your variable names. E.g., use
person_input
instead ofpersonInput
(which is camel case), andrand_num
instead ofrandnumb
. In that second case, it's also more common to shorten "number" to "num" instead of "numb".Use format strings instead of print's argument concatenation, e.g.:
print("Guess lower ({} guesses left)".format(max_guesses - guesses))
Check for and handle errors:
try: person_input = int(input("What is your guess? ")) except ValueError: print("Not sure what you meant by that, please input an integer") continue
I prefer to be more safe than sorry when handling my own incrementor, such as
guesses
, just in case I do something funky that lets it skip overmax_guesses
:# Since you "break" on correct answer, we don't need to check that again if guesses >= max_guesses: # ...
EDIT:
One more thing. In Python, to write a script (rather than a module), you should check if __name__ == '__main__':
as follows:
from random import randint
def main():
randnumb = randint(1,100)
guesses = 0
maxGuesses = 5
while guesses < maxGuesses:
# ...
if __name__ == '__main__':
main()
This allows for safe code re-use, and makes sure that the code doesn't get run if this file gets imported from another file. It's not technically necessary for a one-file script like you're writing here, but it's a good practice to get into anyway.