Skip to content Skip to sidebar Skip to footer

Python 3 Simon Says For Loop String Comparison

I'm new to python 3 and I feel like I am learning in the worst way possible. Everything is through an online text-book called zybooks. I've been trying to understand for loops, and

Solution 1:

You'd have a much easier time using an index :

user_score = 0
simon_pattern = 'RRGBRYYBGY'
user_pattern  = 'RRGBBRYBGY'
for i in range(len(simon_pattern)):
    if user_pattern[i] == simon_pattern[i]:
        user_score += 1

Solution 2:

The issue with your second attempt code (for s in simon_pattern ...) is that you were comparing every s in simon_pattern to every u in user_pattern). You need to correlate these (usually with an index) so that you only compare the first to the first, second to the second etc.


Solution 3:

Using index to iterate through each loop you need some number that increases as you go through each iteration. you can just use user_score since it is already assigned to 0, and going to increase after each iteration by 1. You will probably say "but it is going to be increased only if there is a match!" (this is right)! but if there is mismatch you are going to break out of the loop anyways, and end the game so this it's a perfect.

user_score = 0
simon_pattern = input()
user_pattern  = input()

for i in simon_pattern:
   if user_pattern[user_score] == simon_pattern[user_score]:
      user_score += 1
   else:
      break
            

print('User score:', user_score)

Solution 4:

user_score = 0
simon_pattern = input()
user_pattern  = input()

for i in range(len(simon_pattern)):    # loop for each letter in simon_pattern
    if user_pattern[i] == simon_pattern[i]:    # if user matches simon
        user_score += 1    # add 1 to the user_score
    else:    # otherwise exit the game
        break

print('User score:', user_score)    #output final score

Solution 5:

If you need to do it with continues and breaks like I had to, it would be something like this:

user_score = 0
simon_pattern = input()
user_pattern  = input()

for i in range(len(simon_pattern)):
    if user_pattern[i] == simon_pattern[i]:
        user_score += 1
        continue
    else:
        break
print('User score:', user_score)

Post a Comment for "Python 3 Simon Says For Loop String Comparison"