首页 > 解决方案 > 不确定为什么脚本会在 while 循环中跳过 elif 语句 - Python

问题描述

第一篇文章,如果不符合标准或有类似问题,请见谅。我在这里发布之前用谷歌搜索过,但找不到任何关于此的信息。我正在学习 python 并创建了一个非常基本的石头、纸、剪刀游戏。我希望脚本在最后询问用户是否想重玩游戏,我查找了如何做到这一点,因为我被难住了。

下面的脚本,更具体地说,while 循环完全跳过了 elif 语句,无论我输入 Y 还是 y,它都只会说“ciaox”并结束。如果它以相反的方式执行,它会跳过 elif 语句并重新启动游戏。

帮助将不胜感激。

import random

def game():

    sl = ["rock", "paper", "scissors"]
    us = input("Rock, paper, scissors?: ")
    sl.remove(us)
    pcs = random.choice(sl)

    if us == "rock" and pcs == "paper":
        print("You chose " + us + ". PC chose " + pcs + ". You lose.")
    elif us == "rock" and pcs == "scissors":
        print("You chose " + us + ". PC chose " + pcs + ". You win.")
    if us == "paper" and pcs == "rock":
       print("You chose " + us + ". PC chose " + pcs + ". You win.")
    elif us == "paper" and pcs == "scissors":
        print("You chose " + us + ". PC chose " + pcs + ". You lose.")
    if us == "scissors" and pcs == "rock":
        print("You chose " + us + ". PC chose " + pcs + ". You lose.")
    elif us == "scissors" and pcs == "paper":
        print("You chose " + us + ". PC chose " + pcs + ". You win.")

while True:
    game()
    replay = input("Would you like to play again? Y/N ")
    if replay == "N" or "n":
        print ("ciaox")
        break
    elif replay == "Y" or "y":
        game()

标签: python

解决方案


推荐阅读