Python Bool被正确返回,但仍然获胜';行不通
我是Python新手 我想检查用户的输入,并检查输入是否被接受。该方法称为“check_input”,我在“running”方法第3行中调用了该方法。我给它传递一个字符串和bool变量 然后我想返回inputAccepted值,然后根据其值对其进行处理 我使用了断点,bool本身被正确地更改,但是当代码离开“check_input”方法时,bool“inputAccepted”被忘记了 我做错了什么 我的理论是,bool在方法之外是不可访问的Python Bool被正确返回,但仍然获胜';行不通,python,python-3.x,Python,Python 3.x,我是Python新手 我想检查用户的输入,并检查输入是否被接受。该方法称为“check_input”,我在“running”方法第3行中调用了该方法。我给它传递一个字符串和bool变量 然后我想返回inputAccepted值,然后根据其值对其进行处理 我使用了断点,bool本身被正确地更改,但是当代码离开“check_input”方法时,bool“inputAccepted”被忘记了 我做错了什么 我的理论是,bool在方法之外是不可访问的 import random import colle
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)))
非常感谢您需要查看
检查输入的返回值
,而不是查看输入值
inputAccepted = check_input(guess)
您也没有理由返回最初的猜测,因此我建议重写函数check\u 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
如果在函数检查输入中使用“inputAccepted”作为全局变量和形式参数,请在定义函数检查输入时更改参数名称,这可能会解决您的问题。check\u输入有一个返回值,您不使用该值。您可能打算执行类似于guess,inputAccepted=check\u input(guess,inputAccepted)的操作。我认为您需要
inputAccepted=check\u input(guess,inputAccepted)
。另外,只返回InputAcceptedPossible duplicate的bool值,或者将函数重命名为inputAccepted(guess)并在if@KennyOstrom现在我得到了错误“UnboundLocalError….inputAccepted referenced before assignment”非常感谢!我知道我现在的问题是打印副作用不是很好的做法。一种更具python风格的方法会涉及一个异常,因此您可以稍后打印消息。但是对于一个新的程序员来说,这可能太多了。