亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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 關注
  • 166 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號