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

Python石头剪刀布游戏While循环持续卡在输入环节求助

问题排查与代码优化

问题根源

你的代码卡在while循环的核心原因是字符串方法调用错误:
player = input("Please pick one\n rock, paper, or scissors?: ").lower
这里的.lower没有加括号,你赋值给player的是字符串的lower方法对象,而不是转换后的小写字符串。方法对象永远不会出现在choices列表里,所以player not in choices永远为True,循环无法终止。

只需要把.lower改成.lower(),就能让输入的字符串转为小写并正确判断是否在可选列表中。

修复后的基础代码

import random


choices = ["rock","paper","scissors"]

computer = random.choice(choices)
player = None

while player not in choices:
    # 修复点:添加()调用lower方法
    player = input("Please pick one\n rock, paper, or scissors?: ").lower()

if player == computer:
    print ("computer: ", computer)
    print ("player: ", player)
    print ("This match is a tie, can't even do something simple, dipshit!")

elif player == "rock":
    if computer == "paper":
        print ("paper wraps rock")
    else:
        print ("rock smashes scissors")

elif player == "paper":
    if computer == "scissors":
        print ("scissors eats up paper's ass lmaoooo")
    else :
        print ("rock gets wrapped by paper")

elif player == "scissors":
    if computer == "rock":
        print ("damn boi that computer rock eating up yo damn ass pfttt")
    else :
        print ("snip, snip, time to go paper boiiiii")

代码优化建议

  • 让电脑每次输入后重新选择:原来的代码电脑只在游戏开始选一次,玩家如果输入错误多次,电脑的选择不会变。把computer = random.choice(choices)放到while循环内部,确保每次有效输入时电脑都重新选。
  • 用字典简化胜负判断:嵌套的if-elif可以替换成字典映射,让代码更简洁易维护。
  • 添加重玩功能:让玩家可以选择多次游戏,不用重启程序。
  • 统一输出风格:可以选择更规范的表述,或者保留你的趣味风格,保持一致性即可。

优化后的示例代码

import random

choices = ["rock", "paper", "scissors"]
# 用字典定义胜负关系:key是玩家选择,value是(胜的情况, 败的情况)
outcome_map = {
    "rock": ("rock smashes scissors", "paper wraps rock"),
    "paper": ("paper wraps rock", "scissors cuts paper"),
    "scissors": ("scissors cuts paper", "rock smashes scissors")
}

while True:
    player = None
    while player not in choices:
        player = input("请选择 rock/paper/scissors(输入q退出):").lower()
        if player == 'q':
            print("游戏结束!")
            exit()
    
    computer = random.choice(choices)
    print(f"电脑选择:{computer}")
    print(f"你的选择:{player}")
    
    if player == computer:
        print("平局!再来一局?")
    else:
        win_msg, lose_msg = outcome_map[player]
        if (player == "rock" and computer == "scissors") or \
           (player == "paper" and computer == "rock") or \
           (player == "scissors" and computer == "paper"):
            print(win_msg)
        else:
            print(lose_msg)
    
    play_again = input("要不要再玩一局?(y/n):").lower()
    if play_again != 'y':
        print("游戏结束!")
        break

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 00:05:11