为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

一只斗牛犬 2021-04-25 02:25:13
我想检查用户的输入并检查输入是否被接受。该方法称为“ 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


查看完整回答
反对 回复 2021-06-01
?
莫回无

TA贡献1865条经验 获得超7个赞

您在函数check_input中使用“ inputAccepted”作为全局变量和形式参数,在定义函数check_input时更改参数名称,这可能会解决您的问题。


查看完整回答
反对 回复 2021-06-01
  • 2 回答
  • 0 关注
  • 148 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号