George Baker George Baker - 7 months ago 74
Python Question

4 Digit Guessing Game Python

Im trying to make a 4 digit numbers guessing game in Python 3. It should work by generating a random number between 1000 and 10000 (random.range(1000,10000)) and then by the user guessing and it should return after each guess how many numbers you have got right. My code doesn't exactly work and, I can't think why it doesn't so help is appreciated.

import random as r

guessing = True
real_ans = r.randrange(1000, 10000, 2)
real_ans_str = str(real_ans)

correct = 0

class Player():
def __init__(self):
self.player_guess = input("Enter a guess")
self.evaluate(correct)
def evaluate(self, correct):
for n in range(3):
if self.player_guess[n] == real_ans_str[n]:
correct += 1
if not correct == 4:
print(str(correct)," was correct")
correct = 0
else:
print("You guessed it! ")
guessing = False

while guessing:
Player()

Answer

There are several issues in your code:

  1. You're creating a new instance of Player class inside the main loop. It works, but it's not the best approach IMHO.

  2. You're using guessing to stop the main loop. In Python, all variables are local by default. In order to reference a global variable, you must identify it as global:

def evaluate(self, correct):
    **global guessing**
    for n in range(3):
        if self.player_guess[n] == real_ans_str[n]:
            correct += 1
    if not correct == 4:
        print(str(correct)," was correct")
        correct = 0
    else:
        print("You guessed it! ")
        guessing = False

However using global variables could lead to a messy code.

  1. range provides values from the minimum (0 by default) inclusive and the maximum exclusive. That range(3) will provide the numbers 0, 1 and 2 (3 numbers total), which is not what you want.

Since you're using a class, I'd try the following:

  1. Create a single instance of Player

  2. Create a new method called guess

  3. Change the evaluate method to return how many digits the player guessed right

  4. Create a new method called run, that will call guess and evaluate

import random as r

class Player():
    def __init__(self):
        self.real_ans = str(r.randrange(1000,100000,2))

    def guess(self):
        self.player_guess = raw_input("Enter a guess")

    def evaluate(self):
        correct = 0
        for n in range(4):
            if self.player_guess[n] == self.real_ans[n]:
                correct += 1
        return correct 

    def run(self):
        while True:
            self.guess()
            correct = self.evaluate()
            if not correct == 4:
                print(str(correct)," was correct")
            else:
                print("You guessed it! ")
                break

Player().run()