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

2024-09-25 08:36:46 发布

您现在位置:Python中文网/ 问答频道 /正文

所以,我做了一个石头布剪刀程序,它就像一个魅力。我对它唯一的抱怨是输出中的分数没有在以后继续下去。这是用Python编写的-请原谅,如果下面框中的代码格式错误,我是新来的堆栈溢出。你知道吗

例如,ties=ties+1将正确打印,但是当程序再次运行时,如果我得到另一个tie,它不会说ties=2,而是会一直说ties: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))

主()


Tags: youinputplaycpupaperprinthumanscissors
1条回答
网友
1楼 · 发布于 2024-09-25 08:36:46

在编写代码时,每次运行while循环时,都会将tieswinslosses重置为零。将这些表达式移到while循环之外,值不会随着每个新游戏而重置。你知道吗

相关问题 更多 >