如何使变量值在if语句之外进行

时间:2017-11-17 13:10:36

标签: python loops variables if-statement

所以,我做了一个石头剪刀程序,它就像一个魅力。我对它的唯一抱怨是输出中的分数不会随之结转。这是用Python编写的 - 如果下面框中的代码格式错误,请原谅我,我是堆栈溢出的新手。

ties = ties + 1,例如,将正确打印,但是当程序再次运行时,如果我得到另一个领带,它将不会说tie = 2,它将继续说领带:1。或者如果我得到一个平局和一个损失,它会说领带:1输了:0然后它将打印领带:0输了:1

import random
def main():


    playRPS = str.lower(input("Play a game or rock paper scissors?  Yes or no.  "))
    if(playRPS == "no"):
        print("Well, why did you run the program them?")
    while(playRPS == "yes"):
        human = int(input("Welcome to rock paper scissors!  Type 1 for rock, 2 for paper, or 3 for scissors"))
        cpu = random.randint(1,3)
        ties = 0
        wins = 0
        loses = 0
        if(human == cpu):
            print("It's a tie!")
            ties = ties + 1
            playRPS = input("Play again?")
        elif(human == 1 and cpu == 2):
            print("The computer picked paper, you picked rock, CPU wins!")
            loses = loses + 1
            playRPS = input("Play again?")
        elif(human == 1 and cpu == 3):
            print("The computer picked scissors, you picked rock, You win!")
            wins = wins + 1
            playRPS = input("Play again?")
        elif(human == 2 and cpu == 1):
            print("You picked paper, the computer picked rock, You win!")
            wins = wins + 1
            playRPS = input("Play again?")
        elif(human == 2 and cpu == 3):
            print("You picked paper, the computer picked scissors, CPU wins!")
            loses = loses + 1
            playRPS = input("Play again?")
        elif(human == 3 and cpu == 1):
            print("You picked scissors, the computer picked rock, CPU wins!")
            loses = loses + 1
            playRPS = input("Play again?")
        elif(human == 3 and cpu == 2):
            print("You picked scissors, the computer picked paper, You win!")
            wins = wins + 1
            playRPS = input("Play again?")
        else:
            print("An error occured, maybe you typed 4, or 5, or maybe you made a typo.")
        playRPS = str.lower(input("Another game?  Yes or no."))
        print("Wins:  " + str(wins))
        print("Ties:  " + str(ties))
        print("Loses  " + str(loses))

main()的

1 个答案:

答案 0 :(得分:2)

在编写代码时,每次while循环运行时,它都会将tieswinslosses重置为零。将这些表达式移到while循环之外,并且每次新游戏都不会重置这些值。