简体   繁体   中英

How do I check if a value is in a list and then have a variable storing the score increase by 10 each time

I have created the following code, but would like the score to increase each time that I is in Y, and then display the increased score, allowing the user to enter their guess 8 times.

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")

Two main issues with your current code:

  1. You don't set an initial value for score prior to entering the loop.
  2. You use =+ instead of += to try and increment the score.

This makes an unfortunate combination of mistakes, because score = +10 does not throw an error while score += 10 (the correct way) would have given NameError . See the changes below. Beyond that, you then get an infinite loop by not incrementing the count on each loop.

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

One thing that is needed to complete the logic is to increment the count by 1 at the end. The incremental operator is += and not =+ . Another thing is the variable score will need to be initialized at the start. So the final code with comments about the missing parts is shown below.

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

Your while loop is an infinite loop. Incrementing count by 1 will make it a definite loop. Also, initialize the score variable to zero. That should work things out.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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