【问题标题】:How do I increase the value of a variable within a loop?如何在循环中增加变量的值?
【发布时间】:2019-08-24 12:14:48
【问题描述】:

我正在制作这款石头、纸、剪刀游戏,而且我已经完成了很多工作。但是,我无法正确打印最终分数。无论情况如何,我的总回合数、总胜场数和平局数总是为 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.

【问题讨论】:

  • rounds = 0, wins = 0 and ties = 0,你在 while 循环中设置 0,所以无论你添加什么,它都设置为 0,从 while 循环中删除这些行并放在循环之前

标签: python python-3.x


【解决方案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

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

      【解决方案3】:

      你应该在 while 之外初始化你的变量,而不是在里面。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-01-26
        • 2014-01-07
        • 2018-02-01
        • 1970-01-01
        • 2011-02-24
        • 2014-09-02
        • 2020-05-26
        • 2013-01-16
        相关资源
        最近更新 更多