繁体   English   中英

如何检查一个值是否在列表中,然后让一个变量存储每次得分增加10

[英]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")

当前代码有两个主要问题:

  1. 在进入循环之前,您无需为score设置初始值。
  2. 您使用=+而不是+=来尝试增加分数。

这会造成错误的错误组合,因为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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM