![](/img/trans.png)
[英]How do I add a score text list that adds 1 each time I click my cookie sprite? (python)
[英]How do I check if a value is in a list and then have a variable storing the score increase by 10 each time
我创建了以下代码,但是我希望每次在Y中都增加分数,然后显示增加的分数,从而允许用户输入他们的猜测8次。
Y = ["Treasure", "Hi", "Hey", "whoops", "OK", "Hello"]
count=0
while count<9:
I = str(input("Enter your guess"))
if I in Y:
score=+10
print('Your score is:',score)
else:
print("I don't understand")
当前代码有两个主要问题:
score
设置初始值。 =+
而不是+=
来尝试增加分数。 这会造成错误的错误组合,因为score = +10
不会引发错误,而score += 10
(正确的方法)会给出NameError
。 请参阅下面的更改。 除此之外,您还可以通过不增加每个循环的count
来获得无限循环。
Y = ["Treasure", "Hi", "Hey", "whoops", "OK", "Hello"]
count=0
score = 0 # Set an initial score of 0, before the loop
while count<9:
I = str(input("Enter your guess"))
if I in Y:
score =+ 10 # Change to += to increment the score, otherwise it's always 10
print('Your score is:',score)
else:
print("I don't understand")
count += 1
完成逻辑所需要做的一件事是最后将计数加1。 增量运算符是+=
而不是=+
。 另一件事是变量分数将需要在开始时进行初始化。 因此,下面的代码显示了有关缺失部分的注释。
Y = ["Treasure", "Hi", "Hey", "whoops", "OK", "Hello"]
count = 0
score = 0 # initialize the score
while count<9:
I = str(input("Enter your guess: "))
if I in Y:
score+=10 # increment the score
print('Your score is: %s' % score)
else:
print("I don't understand")
count += 1 # increment the count
您的while循环是一个无限循环。 将count递增1将使其成为一个确定的循环。 另外,将score变量初始化为零。 那应该可以解决问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.