为什么我的python代码没有完全运行

时间:2017-08-14 13:47:20

标签: python exit break

任何人都可以帮助我理解为什么我的非常简单的岩石剪刀代码会卡在第18行的末尾并退出吗? 我已经单独测试了每个部件并且它可以工作,它可能不是最漂亮的代码,但它似乎可以完成这项工作,但是在最新的itteration它只是退出第18行,退出代码0,所以没有错误,没有说什么是错的,它只是没有执行下一行,就像那条线上有休息或退出,但不是:

 import random

def startgame():
    print("Please choose rock - r, paper - p or scissors - s:")
    pchoice = input(str())
    if(pchoice.lower in ["r","rock"]):
        pchoice = "0"
    elif(pchoice.lower in ["s","scissors"]):
        pchoice = "1"
    elif(pchoice.lower in ["p","paper"]):
        pchoice = "2"
    cchoice = (str(random.randint(0,2)))
    if(cchoice == "0"):
        print("Computer has chosen: Rock \n")
    elif(cchoice == "1"):
        print("Computer has chosen: Scissors \n")
    elif(cchoice == "2"):
        print("Computer has chosen: Paper \n")
#runs perfect up to here, then stops without continuing
    battle = str(pchoice + cchoice)
    if(battle == "00" and "11" and "22"):
        print("Draw! \n")
        playagain()
    elif(battle == "02" and "10" and "21"):
        if(battle == "02"):
            print("You Lose! \nRock is wrapped by paper! \n")
        elif(battle == "10"):
            print("You Lose! \nScissors are blunted by rock! \n")
        elif(battle == "21"):
            print("You Lose! \nPaper is cut by scissors! \n")
            playagain()
    elif(battle == "01" and "12" and "20"):
        if(battle == "01"):
            print("You Win! \nRock blunts scissors! \n")
        elif(battle == "12"):
            print("You Win! \nScissors cut paper! \n")
        elif(battle == "20"):
            print("You Win! \nPaper wraps rock! \n")
            playagain()

def main():
    print("\nWelcome to Simon´s Rock, Paper, Scissors! \n \n")
    startgame()

def playagain():
        again = input("Would you like to play again? y/n \n \n")
        if(again == "y"):
            startgame()
        elif(again == "n"):
            print("Thank you for playing")
            exit()
        else:
            print("Please choose a valid option...")
        playagain()

main()

2 个答案:

答案 0 :(得分:0)

错误在于:

if(battle == "00" and "11" and "22"):

除了False之外,所有情况下评估为00,您需要将其更改为:

if battle == "00" or battle == "11" or battle == "22":

以及使用and

的其他两个陈述

您的陈述被解释如下:

True/False 1- if battle == "00" 
True       2- and "11" #<-- here it checks if the string is True which means string is not empty
True       3- and "22" is True #<-- here too

因此,只有当所有语句都为True时,您的语句才有效,因为您使用的and要求语句的所有部分都为True。第二和第三部分始终为True,因此检查选项是否为"00"

你需要的是:

1- if battle == "00" True/False
2- or battle == "11" True/False
3- or battle == "22" True/False

由于True

,您只需要一个部分or来运行该语句

答案 1 :(得分:0)

在像这样的行中     if(battle == "00" and "11" and "22"): 使用in运算符     if(battle in ["00", "11", "22"]):

playagain()没有被调用,因为没有条件成立。