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

如何在Python函数间复用输入值?以Higher or Lower游戏为例

《Higher or Lower》游戏函数协同问题解决方案

我正在开发《Higher or Lower》游戏,尝试用函数拆分逻辑。目前代码里有多个函数,其中winner和game需要配合才能正常运行(代码还没写完,后续还要加很多机制)。

现有代码:

def winner(opponent1, opponent2):

  opponent1_flwrs = opponent1['follower_count']
  opponent2_flwrs = opponent2['follower_count']
  score = 0

  if opponent1_flwrs > opponent2_flwrs:
    if higher_or_lower == "A" or higher_or_lower == "a":
      score += 1
      return "You're right! Current score: " + score
    else:
      clear()
      print(art.logo)
      return "Sorry, that's wrong. Final score: " + score
  elif opponent2_flwrs > opponent1_flwrs:
    if higher_or_lower == "B" or higher_or_lower == "b":
      score += 1
      return "You're right! Current score: " + score
    else:
      clear()
      print(art.logo)
      return "Sorry, that's wrong. Final score: " + score

def game(opponent1, opponent2):
  """
  Contains the code necessary for the game to begin and will continue to execute 
  as long as the user is the winner
  """
  print(art.logo)
  print(f"Compare A: {opponent1['name']}, a {opponent1['description']}, "
        f"from {opponent1['country']}")
  print(art.vs)
  print(f"Against B: {opponent2['name']}, a {opponent2['description']}, "
        f"from {opponent2['country']}")
  higher_or_lower = input("Who has more followers A or B? ")

我有个存储数据的文件,opponent1、opponent2、opponent1_flwrs、opponent2_flwrs的值都来自这个文件。现在需要让game函数里获取的higher_or_lower输入值能在winner函数里使用,保持值不变,之后还要加while循环,持续调用这些函数直到用户答错。


核心问题解决思路

  • 函数有独立作用域,winner不能直接获取game里的higher_or_lower,必须通过参数传递
  • 当前winner里的score每次调用都会重置,得把分数放在函数外维护才能实现累加
  • 用while循环控制游戏流程,直到用户答错退出

修改后的代码示例

# 假设已导入art模块和clear函数
def winner(opponent1, opponent2, user_choice, current_score):
    opponent1_flwrs = opponent1['follower_count']
    opponent2_flwrs = opponent2['follower_count']
    
    if opponent1_flwrs > opponent2_flwrs:
        if user_choice.lower() == "a":
            current_score += 1
            return True, f"You're right! Current score: {current_score}"
        else:
            clear()
            print(art.logo)
            return False, f"Sorry, that's wrong. Final score: {current_score}"
    elif opponent2_flwrs > opponent1_flwrs:
        if user_choice.lower() == "b":
            current_score += 1
            return True, f"You're right! Current score: {current_score}"
        else:
            clear()
            print(art.logo)
            return False, f"Sorry, that's wrong. Final score: {current_score}"
    # 可选:处理粉丝数相等的情况
    else:
        return True, f"It's a tie! Score remains: {current_score}"

def game_round(opponent1, opponent2):
    """单轮游戏:展示对手信息并获取用户选择"""
    print(art.logo)
    print(f"Compare A: {opponent1['name']}, a {opponent1['description']}, from {opponent1['country']}")
    print(art.vs)
    print(f"Against B: {opponent2['name']}, a {opponent2['description']}, from {opponent2['country']}")
    return input("Who has more followers? Type 'A' or 'B': ")

# 主游戏循环
def main():
    score = 0
    # 从数据文件加载初始对手示例(根据你的实际文件修改)
    # 比如:from your_data_file import get_random_opponent
    # opponent1 = get_random_opponent()
    # opponent2 = get_random_opponent()
    
    while True:
        user_choice = game_round(opponent1, opponent2)
        is_correct, result_msg = winner(opponent1, opponent2, user_choice, score)
        print(result_msg)
        
        if not is_correct:
            break
        
        # 答对后,把B作为下一轮的A,再选新的B
        opponent1 = opponent2
        # opponent2 = get_random_opponent()

if __name__ == "__main__":
    main()

关键修改说明

  1. 参数传递:给winner新增user_choice参数,直接接收game_round里的用户输入,解决跨函数变量访问问题
  2. 分数持久化:把score放在main函数里维护,每次调用winner时传入,实现连续游戏的分数累加
  3. 返回值优化:winner返回两个值——是否答对的布尔值和结果提示语,方便主循环判断是否继续游戏
  4. 职责拆分:把原game函数拆成game_round(负责单轮展示和输入)和main(负责全局循环和状态管理),逻辑更清晰

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 20:39:15