将值从函数返回到全局变量

Returning a value from a function to a global variable

各位程序员大家好! 快速免责声明 我是编码领域的新手,目前正在学习 Python,很高兴获得所有信息和帮助!

所以我正在尝试编写 mastermind 游戏的代码,如果你不熟悉的话,这里是维基百科文章:Text

我正在尝试使用全局变量,但每次在函数中使用全局变量时,它都会 return 将其发送到全局变量中,变量只会设置回其原始值。

如果您需要我提供更多信息,请告诉我! 期待您的来信。

import random
colors = "YORPGB"
global secret  
global round
global hits
global close 

def gen_random_secret():
    secret = ""
    for i in range(4):
        n = random.randrange(6)
        secret += colors[n]
    return secret

def get_guess(force_valid_input):
    while True:
        guess = input(f"Available letters: {colors}\nPut in a 4-letter Word with the available letters, there can be duplicates! ").upper()
        
        if len(guess) ==4:
            return guess
        else:
            if not force_valid_input:
                return None
            print("Wrong Input try again!")

def check_guess(guess,secret):
    hits = 0
    close = 0
    for i in range(4):
        if guess[i] == secret[i]:
            hits += 1
    
    for color in colors:
        close += min(secret.count(color),guess.count(color))
    close = close - hits
    
    return hits, close

def start_game():
    print("Welcome to the Mastermind game!\nGenerating random code...")
    round = 1
    history = []
    hits = 0
    close = 0
    secret = gen_random_secret()
    while round<=12:
        guess = get_guess(True)
        check_guess(guess,secret)
        
        print(f"Hits: {hits} Close: {close}\n")
        if hits == 4:
            break
        round += 1
        history.append((guess,hits,close))
    print()
    for row in history:
        for color in row[0]:
            print(f" {color}", end="")
        print(f" | {row[1]} {row[2]}")
    print()
    if hits == 4:
        print(f"Congratz u guessed it the code was: {secret}")
    else:
        print(f"You ran out off attempts, you lose bitch!\n the secret Word was {secret}")

start_game()

您必须在函数内调用 global 让函数知道要使用全局变量。

例如:

def gen_random_secret():
    global secret
    secret = ""
    for i in range(4):
        n = random.randrange(6)
        secret += colors[n]
    return secret

而不是:

global secret
def gen_random_secret():
    secret = ""
    for i in range(4):
        n = random.randrange(6)
        secret += colors[n]
    return secret