我想檢查用戶的輸入并檢查輸入是否被接受。該方法稱為“ check_input”,我在“ running”方法的第三行中稱為此方法。我給它傳遞了一個字符串和布爾變量。然后我想返回 inputAccepted 值,然后根據它的值對它做一些事情。我已經使用了斷點,并且bool本身已正確更改,但是當代碼離開'check_input'方法時,bool'inputAccepted'被遺忘了。我究竟做錯了什么?我的理論是 bool 在方法之外無法訪問?import randomimport collectionsimport recodeLength = 4guessesRemaining = 10inputAccepted = FalsewelcomeMessage = '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")
2 回答

慕尼黑的夜晚無繁華
TA貢獻1864條經驗 獲得超6個贊
您需要查看的返回值check_input,而不是輸入值。
inputAccepted = check_input(guess)
您也沒有理由返回最初的猜測,因此我建議重寫該函數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

莫回無
TA貢獻1865條經驗 獲得超7個贊
您在函數check_input中使用“ inputAccepted”作為全局變量和形式參數,在定義函數check_input時更改參數名稱,這可能會解決您的問題。
添加回答
舉報
0/150
提交
取消