Python Forum

Full Version: The count variable is giving me a hard time in this code
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
from random import randrange

def toohigh():
	# displays too high sequence
	count += 1
	return('Too high! Try again. ')
	guess = input('Guess my number between 1 and 1000. ')
	play()
	
def toolow():
	# displays too low sequence
	count += 1
	return('Too low! Try again. ')
	guess = input('Guess my number between 1 and 1000. ')
	play()

def correct():
	# displays correct sequence
	count += 1
	return('Congrats! That was the correct number!')
	if count <= 10:
		return('It took you ', str(count), 'guesses.' 'You either know the secret or got lucky.')
	if count > 10:
		return('It took you ', str(count), 'guesses.' 'I think you can do better than that.')
	playagain()

def playagain():
	playagain = input('Would you like to play again? y/n ')
	if playagain == 'y':
		play()
		count = 0
	if playagain == 'n':
		return('Bye!')
		count = 0
	else:
		return('Please answer y or n')
		playagain()

def play():
	# plays game
	count = 0
	x = randrange(1000)
	guess = int(input('Guess my number between 1 and 1000. '))
	while guess != x:
		if int(guess) > x:
			toohigh()
		if guess < x:
			toolow()
		if guess == x:
			correct()

play()
# I am 100% a noob, thank you for helping.
Quote:The count variable is giving me a hard time in this code
please be a bit more specific
By default, variables that are assigned inside a function are local to the function. To get data into a function you usually pass the information in as an argument. To get the data out you return() it.

There are other ways, but starting off, this is one of the best.

So for toohigh(), when it gets to line 5, it wants to make count bigger, but it has never been assigned in the function, so it doesn't know what to do.

You should decide whether the functions even need to know the count at all. Maybe you could keep the guess count outside. For instance, your toohigh() and toolow() functions do exactly the same thing except for the text in one line. Probably you could do all the similar stuff elsewhere.