I have two variables that I know are equal but my if statement does not recognise this?

Viewed 54

This is my code:

bookings = ['blue,red', 'green,orange', 'yellow, purple']
number = 0
b = 0
c = 1

file_test = open('test_1.txt' , 'wt')

results_song = []

for item in bookings:
   words = bookings[number].split(',')
   results_song.append(words[0])
   results_song.append(words[1])

   number = number + 1

results_song_str = '\n'.join(results_song)
print(results_song_str)

file_test.write(results_song_str)

file_test.close()

file_test = open('test_1.txt' , 'r')

line = file_test.readlines()


for item in bookings:

    line_1 = line[b]
    line_2 = line[c]
    answer = input('If first word is then what is the second word')

    if answer == line_2:
       print('correct')
    else:
       print('wrong')

    b = b + 2
    c = c + 2

However the code will not recognise that answer is equal to line_2. I cannot figure out why this is happening. I have checked that c is the correct number and that line_2 is the same as answer. But I did notice that when I ran the code while printing answer and line_2 that this would return:

red

red

but I never put a new line feature in here.

Any help would be much appreciated as I need to use this code for a school assignment.

1 Answers

Debugging by printing

# ...

for item in bookings:
    line_1 = line[b]
    line_2 = line[c]

    print("Your Answer:", repr(answer))
    print("Actual Answer:", repr(line_2))

    # ...

gives

Your Answer: 'red'
Actual Answer: 'red\n'

Aha! A sneaky newline character! Seems like when the program was reading text from the file and splitting the lines, it saved the newline character for you. How sweetly annoying. : |

To remove it, you can use the str.replace() method

# ...

for _ in range(len(bookings)):   # I took the freedom to modify the loop conditions

    line_1 = line[b].replace('\n','')
    line_2 = line[c].replace('\n','')

    # ...

or change the way lines are read from the file, manually splitting the lines using the str.split() method

# ...

with open('test_1.txt' , 'r') as file_test:
    line = file_test.read().split('\n')

for _ in range(len(bookings)):
    line_1 = line[b]
    line_2 = line[c]

    # ...

Credit goes to @juanpa.arrivillaga for suggesting the use of repr() to check values.

Related