[英]How do I increase the value of a variable within a loop?
我正在建造这个石头,纸,剪刀的游戏,而且我已经走了很远。 但是,我无法获得最终分数以正确打印。 无论情况如何,我在总回合,总胜利和平局中总是得到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.
您将在每个循环的开始将变量设置为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
只需在循环之前声明它们:
win = 0
loses = 0
ties = 0
rounds = 0
while True:
...
您要做的是每次循环重新开始时,所有变量都再次设置为0。 通过在循环之前声明它们,代码将运行,并且仅在循环中稍后将它们增加1时才更改它们的值。
您应该在while而不是内部初始化变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.