Reputation: 49
I am new to Python.
I am wanting to check the input of the user and check if the input is accepted. The method is called 'check_input' and i call this method in the 'running' methods 3rd line. I pass it a string and bool variable.
I then want to return the inputAccepted value and then do something with it depending on its value.
I have used breakpoints and the bool itself is changed correctly but when the code leaves the 'check_input' method the bool 'inputAccepted' is forgotten.
What am i doing wrong?
My theory is that the bool isn't accessible outside the method?
import random
import collections
import re
codeLength = 4
guessesRemaining = 10
inputAccepted = False
welcomeMessage = 'Welcome to Mastermind. Try and guess the code by using the following letters:\n\nA B C D E F \n\nThe code will NOT contain more than 1 instance of a letter.\n\nAfter you have entered your guess press the "ENTER" key.\nYou have a total of'
print(welcomeMessage, guessesRemaining, 'guesses.\n')
def gen_code(codeLength):
symbols = ('ABCDEF')
code = random.sample(symbols, k=codeLength)
return str(code)
code = gen_code(codeLength)
print(code)
counted = collections.Counter(code)
def check_input(guess, inputAccepted):
if not re.match("[A-F]", guess): #Only accepts the letters from A-F
print("Please only use the letters 'ABCDEF.'")
inputAccepted = False
return (guess, inputAccepted)
else:
inputAccepted = True
return (guess, inputAccepted)
def running():
guess = input() #Sets the guess variable to what the user has inputted
guess = guess.upper() #Converts the guess to uppercase
check_input(guess, inputAccepted) #Checks if the letter the user put in is valid
print(guess)
print(inputAccepted)
if inputAccepted == True:
guessCount = collections.Counter(trueGuess)
close = sum(min(counted[k], guessCount[k]) for k in counted)
exact = sum(a == b for a,b in zip(code, guess))
close -= exact
print('\n','Exact: {}. Close: {}. '.format(exact,close))
return exact != codeLength
else:
print("Input wasnt accepted")
for attempt in range(guessesRemaining):
if not running():
print('Done')
break
else:
print('Guesses remaining:', guessesRemaining - 1 - attempt, '\n')
else:
print('Game over. The code was {}'.format(''.join(code)))
Thank you very much
Upvotes: 1
Views: 73
Reputation: 1
You are using "inputAccepted" as global variable and formal argument in function check_input , change the argument name while defining function check_input, it may resolve your issue.
Upvotes: 0
Reputation: 2431
You need to look at the return values of check_input
, not look at the input values.
inputAccepted = check_input(guess)
There's also no reason for you to return your initial guess, so I would recommend rewriting the function check_input
:
def check_input(guess):
if not re.match("[A-F]", guess): #Only accepts the letters from A-F
print("Please only use the letters 'ABCDEF.'")
return False
else:
return True
Upvotes: 2