This is my first Python script, and I was hoping to get some feedback. I do have one specific question: is the use of global
variables considered a bad practice? When I used them below, my programmer's instincts immediately went off as though I was creating a code-smell, mostly because it seems much less elegant than just having a private String myVariable
at the top of a Java class. The use of global myVariable
to force the scope seemed a bit hacky. But I don't know a single thing about Python except what I wrote below, so I could be way off.
I also realize that the below code is more complex than it needs to be. I know that it could be written in much fewer lines of code by removing function definitions and such (in fact, my first version was only like 15 lines). But I wrote this more complicated version in order to get a handle on some of the basic concepts like sharing variables, returning from functions, etc.
Any tips or glaring style/best-practices issues are appreciated! (I'm a style-Nazi with Java, so please, don't hold back so that I can learn!)
#!/usr/bin/python
from random import randint
# GLOBALS
guesses = 0
the_number = 0
def checkGuess(guess):
global the_number
if guess <= 0:
return False
elif guess == the_number:
return True
elif guess < the_number:
print "The number is HIGHER."
elif guess > the_number:
print "The number is LOWER."
return False
def isValid(guess):
return len(guess) > 0 and guess.isdigit()
def getInput():
global guesses
input = ""
while not isValid(input):
input = raw_input("(#" + str(guesses) + ") Guess a number: ")
if not isValid(input):
print "Please guess an integer!"
return int(input)
def runGame(min, max):
global guesses
global the_number
the_number = randint(min, max)
guess = 0
print "I'm thinking of a number between " + str(min) + " and " + str(max) + " ..."
while not checkGuess(guess):
guesses = guesses + 1
guess = getInput()
print "YOU WON!"
def printTitle():
print "----------------------"
print "----- MASTERMIND -----"
print "----------------------"
print ""
def main():
printTitle()
runGame(1, 100)
main()