# Creating a random generator function in a number guessing game

Hello there!

I’m trying to create a random number generator within GuessNumber such that it relies on self.mn and self.mx to reduce human error when changing the limits of the random generator function. I’m not quite sure how to integrate it into the class…

``````class GuessNumber:

def __init__ (self, number, mn=0, mx=100):
self.number = number
self.min = mn
self.max = mx
self.guesses = 0

def get_guess(self):
guess = input(f"Please guess a number between {self.min} and {self.max}: ")

if self.valid_number(guess):
# if True, then this will execute
return int(guess)
else:
# if False, then this will execute
return self.get_guess()

def valid_number(self, str_number):
try:
number = int(str_number)
except:
return False

return self.min <= number <= self.max
# if value entered is not in the min max range, the above line will return False

# both False entries in "valid_number" is to prompt the 'else' statement in get_guess

def play(self):
while True:
self.guesses += 1

guess = self.get_guess()

if guess < self.number:
elif guess > self.number:
else: #they guessed it
break
print(f"You guessed it in {self.guesses} guesses.")

from random import randint
a = randint(0,100)
game = GuessNumber(a)
game.play()``````

You can just initialize `self.number` using `randint()` with the limits given to `__init__()`, instead of passing `number`. You’ll have to move the import to the top of the file to do that (which is good practice anyway, with a few exceptions).

1 Like

@airtower-luna

Solved it

Thanks!

``````from random import randint

class GuessNumber:

def __init__ (self, mn=0, mx=100):
self.min = mn
self.max = mx
self.number = randint(self.min, self.max)
self.guesses = 0

def get_guess(self):
guess = input(f"Please guess a number between {self.min} and {self.max}: ")

if self.valid_number(guess):
# if True, then this will execute
return int(guess)
else:
# if False, then this will execute
return self.get_guess()

def valid_number(self, str_number):
try:
number = int(str_number)
except:
return False

return self.min <= number <= self.max
# if value entered is not in the min max range, the above line will return False

# both False entries in "valid_number" is to prompt the 'else' statement in get_guess

def play(self):
while True:
self.guesses += 1

guess = self.get_guess()

if guess < self.number: