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

如何在Python中正确整合函数实现石头剪刀布游戏?

石头剪刀布游戏整合问题修复

核心问题定位

你的代码中play函数存在两个关键错误:

  • 调用get_computer_choice()和get_user_choice()时,未将返回的选择结果保存到变量中,导致后续无法复用这些值。
  • 调用get_winner时,传入的是函数本身(get_computer_choice、get_user_choice),而非函数执行后得到的具体选择值,这会让胜负判断逻辑完全失效。

修正后的完整代码

import random

def get_computer_choice():
    rps = ["Rock", "Paper", "Scissors"]
    computer_choice = random.choice(rps)
    return computer_choice

def get_user_choice():
    # 处理输入大小写、空格,增加无效输入验证
    user_choice = input("Choose Rock, Paper, or Scissors: ").strip().capitalize()
    while user_choice not in ["Rock", "Paper", "Scissors"]:
        print("Invalid choice! Please try again.")
        user_choice = input("Choose Rock, Paper, or Scissors: ").strip().capitalize()
    return user_choice

def get_winner(computer_choice, user_choice):
    if computer_choice == user_choice:
        print("It is a tie!")
    elif computer_choice == 'Rock':
        print("You lost") if user_choice == 'Scissors' else print("You won!")
    elif computer_choice == 'Paper':
        print("You won!") if user_choice == 'Scissors' else print("You lost")
    elif computer_choice == 'Scissors':
        print("You won!") if user_choice == 'Rock' else print("You lost")

def play():
    # 保存函数返回的选择值
    computer_pick = get_computer_choice()
    user_pick = get_user_choice()
    # 将实际选择值传入胜负判断函数
    get_winner(computer_pick, user_pick)

play()

额外优化说明

  • 给get_user_choice增加了输入处理逻辑:自动修正大小写、去除多余空格,同时验证输入有效性,避免因用户输入错误内容导致游戏逻辑出错。
  • 简化了get_winner的条件判断写法,保持逻辑不变的同时让代码更简洁。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 17:35:32