如何在循环中增加变量的值?

时间:2019-04-03 04:36:31

标签: python python-3.x

我正在建立这个石头,纸,剪刀的游戏,而且我已经走了很远。但是,我无法获得最终分数以正确打印。无论哪种情况,我在总回合,总胜利和平局中总得到0值。

我一直试图在循环中添加这些变量,但是,我似乎无法弄清楚。


import random

# a rock, paper, scissors game

loop = True

while loop is True:
    win = 0
    tie = 0
    lose = 0
    rounds = 0 

    usrchoice = input("Rock, Paper or Scissors? (Quit ends): ") # user makes a choice

    if usrchoice.title() == "Rock":
        pass

    ...

        if computer_choice == "Scissors":
            print("You WIN!")
            win = win + 1
            rounds = rounds + 1


        elif computer_choice == "Rock":
            print("It's a tie!")
            tie = tie + 1
            rounds = rounds + 1


        else:
            print("You LOSE!")
            lose = lose + 1
            rounds = rounds + 1




我希望输出是任何东西,这当然取决于用户,而不仅仅是0。像这样:

>>> You played 0, and won 0 rounds, playing tie in 0 rounds.

3 个答案:

答案 0 :(得分:1)

您将在每个循环的开始将变量设置为0。将变量移到循环上方即可解决此问题。

例如:


import random

# a rock, paper, scissors game
# foot beats cockroach, cockroach beats nuke and nuke beats foot

win = 0
tie = 0
lose = 0
rounds = 0 

loop = True

while loop is True:
    usrchoice = input("Foot, Nuke or Cockroach? (Quit ends): ") # user makes a choice

答案 1 :(得分:0)

只需在循环之前声明它们:

win = 0
loses = 0 
ties = 0
rounds = 0
while True:
    ...

您正在做的是每次循环重新开始时,所有变量都再次设置为0。通过在循环之前声明它们,代码将运行并仅在循环中稍后将它们增加1时更改它们的值。

答案 2 :(得分:0)

您应该在while而不是内部初始化变量。