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

Python函数间变量传递:如何让hangman()获取hang()中的gameinput变量?

解决方案

核心问题分析

你遇到的是Python变量作用域问题:gameinput是hang()函数的局部变量,其他函数(比如hangman())无法直接访问;另外嵌套定义函数(two_player_word/one_player_word在hang()的条件分支里)会导致作用域混乱,且重复定义无意义。

修改后的完整代码

import time

def get_game_mode():
    while True:
        gameinput = input("Please select a gamemode, Type [1] for one player or Type [2] for two player: ")
        if gameinput in ("1", "2"):
            return gameinput
        print("Invalid option, please try again.")

def two_player_word():
    # 双人模式:让第二个玩家输入要猜的单词
    word = input("Player 2, please enter the word to guess: ").strip().lower()
    return word

def one_player_word():
    # 单人模式:从预设列表随机选单词
    import random
    word_list = ["apple", "banana", "cherry", "date", "elderberry"]
    return random.choice(word_list)

def hangman(game_mode):
    if game_mode == "2":
        word = two_player_word()
    elif game_mode == "1":
        word = one_player_word()
    print(f"The word to guess is: {'*' * len(word)}")
    # 这里可以继续添加猜单词的核心逻辑

def main():
    while True:
        print("\nWould you like to play?")
        start_input = input("Press [1] to start, Press [2] to exit program. ")
        if start_input == "2":
            print("Thank you for playing, goodbye....")
            time.sleep(2)
            break
        elif start_input != "1":
            print("Invalid option.")
            continue
        
        # 获取游戏模式
        game_mode = get_game_mode()
        # 启动游戏
        hangman(game_mode)
        
        # 游戏结束后询问重玩
        while True:
            print("\nWould you like to play again?")
            restart_input = input("Press [1] to play again, Press [2] to exit program. ")
            if restart_input == "1":
                print("\n" * 25)
                break
            elif restart_input == "2":
                print("Thank you for playing, goodbye....")
                time.sleep(2)
                return
            else:
                print("Invalid option.")

if __name__ == "__main__":
    main()

关键修改点

  • 变量作用域修复:将模式选择逻辑改为get_game_mode()函数,通过返回值把用户选择的模式传递给hangman(),避免跨函数访问局部变量。
  • 函数结构优化:把two_player_word和one_player_word改为顶层独立函数,消除嵌套定义的作用域问题,同时让它们返回实际的单词(而非仅打印),符合函数的职责。
  • 流程调整:在main()中,每次启动/重玩游戏时都会重新调用get_game_mode(),支持玩家切换游戏模式;同时修复了原代码中未导入time模块、拼写错误Invaild等问题。
  • 循环简化:将原代码中p == 1的循环改为while True,逻辑更清晰,直到用户输入合法选项才退出循环。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 09:09:18