Bool 被正确返回,但仍然无法正常工作

我想检查用户的输入并检查输入是否被接受。该方法称为“ check_input”,我在“ running”方法的第三行中称为此方法。我给它传递了一个字符串和布尔变量。


然后我想返回 inputAccepted 值,然后根据它的值对它做一些事情。


我已经使用了断点,并且bool本身已正确更改,但是当代码离开'check_input'方法时,bool'inputAccepted'被遗忘了。


我究竟做错了什么?


我的理论是 bool 在方法之外无法访问?


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")



一只斗牛犬
浏览 149回答 2
2回答

慕尼黑的夜晚无繁华

您需要查看的返回值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

莫回无

您在函数check_input中使用“ inputAccepted”作为全局变量和形式参数,在定义函数check_input时更改参数名称,这可能会解决您的问题。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python