You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python函数避免全局变量:猜数字游戏问题求助

猜数字游戏的全局变量替代方案求助

我正在通过多种资源(如LPTHW书籍及在线资料)学习Python3,习惯将所学知识融合到实践任务中。但由于我仅有有限的C/嵌入式开发背景,深知可写全局变量是不被推荐的,因此尽可能避免使用全局变量。

然而在编写以下猜数字游戏代码时,我因不知如何处理num_guesses变量而陷入困境,当前代码因该变量出现问题:

import random

min_num = 1
max_num = 100

def generate_number(min_num, max_num):
    """This function generates a random number within a specified range"""
    return random.randint(min_num, max_num)

def get_guess():
    """This function asks the player to guess a number"""
    guess = input("Guess a number between 1 and 100: ")
    return int(guess)

def check_guess(guess, target):
    """This function checks if the player's guess matches the target number"""
    if guess == target:
        print("Congratulations! You guessed the number!")
        return True
    elif guess < min_num or guess > max_num:
        print("Your guess is out of bounds. Try again.")
        return False
    elif num_guesses[-2]:
        if abs(target-guess) < abs(target-num_guesses[-2]):
            print("Warmer!")
            return False
        else:
            print("Colder!")
            return False
    else:
        if abs(target-guess) <= 10:
            print("Warm!")
            return False
        else:
            print("Cold!")
            return False

def play_game():
    """This function runs the game"""
    #min_num = 1
    #max_num = 100
    target = generate_number(min_num, max_num)
    guesses = []
    num_guesses = 0

    while True:
        guess = get_guess()
        num_guesses += 1

        if guess in guesses:
            print("You already guessed that number. Try again.")
        else:
            guesses.append(guess)
            if check_guess(guess, target):
                print("You guessed the number in", num_guesses, "guesses!")
                break

    play_again = input("Do you want to play again? (yes or no)")
    if play_again == "yes":
        play_game()
    else:
        print("Thanks for playing!")

play_game()

我尚未接触面向对象编程,希望用已学知识简化解决问题,之后再进阶学习面向对象内容。

这款游戏是简单的猜数字类型,需检查输入是否在有效范围内,并根据与前一次猜测的距离给出冷热提示。

恳请提供修复思路,帮助我学习最佳实践 :)


编辑更新

感谢下方解答,我也学会了如何将min_num和max_num整数作为参数传递给各个函数,无需使用全局变量。

我还添加了一些文本并整理了其他部分,提升用户友好度 :)

import random

def show_instructions(min_num, max_num):
    """This function displays the rules/instructions for playing the game"""
    print("\n")
    print("*" * 61)
    print("*** Welcome to the Random Number Guess GeneRatoR [RNG GRR]***")
    print("*" * 61)
    print("\nTo play:\n")
    print("Enter a value between the range shown at the start of the game")
    print("After each guess you will be told 'Warmer' if getting closer to the value")
    print("If further away, then it will show 'Colder'.")
    print("If within 10 of the value it will say 'Very Warm!'")
    print(f"To begin: enter a number between the {min_num} and {max_num}")

def generate_number(min_num, max_num):
    """This function generates a random number within a specified range"""
    return random.randint(min_num, max_num)

def get_guess(min_num, max_num):
    """This function asks the player to guess a number"""
    guess = input("> ")
    return int(guess)

def check_guess(guess, target, guesses, min_num, max_num):
    """This function checks if the player's guess matches the target number"""
    if guess == target:
        print("Congratulations! You guessed the number!")
        return True
    elif guess < min_num or guess > max_num:
        print("Your guess is out of bounds. Try again.")
        print(f"The number is between {min_num} and {max_num}.")
        return False
    elif abs(target - guess) <= 10:
            print("Very warm!")
            return False
    elif len(guesses) > 1:
        if abs(target-guess) < abs(target-guesses[-2]):
            print("Warmer!")
            return False
        else:
            print("Colder!")
            return False
    else:
        print("Quite far out, try again")
        return False

def play_game():
    """This function runs the game"""
    min_num = 1
    max_num = 100
    target = generate_number(min_num, max_num)
    guesses = []
    num_guesses = 0

    show_instructions(min_num, max_num)

    while True:
        guess = get_guess(min_num, max_num)
        num_guesses += 1

        if guess in guesses:
            print("You already guessed that number. Try again.")
        else:
            guesses.append(guess)
            if check_guess(guess, target, guesses, min_num, max_num):
                print("You guessed the number in", num_guesses, "guesses!")
                break

    play_again = input("Do you want to play again? (yes or no)")
    if play_again == "yes":
        play_game()
    else:
        print("\n***Thanks for playing!\n")

play_game()

内容的提问来源于stack exchange,提问作者Dan Lewis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 23:57:00