Finn Roblin Finn Roblin - 1 year ago 60
Python Question

Why is the user's input not recognized as correct?

my code has an issue. I'm relatively new to reading from files, and as such, I don't know what is wrong with my code.

# Flashcards

#Read from a file containing questions in the form question, answer

import random
import time

def __run__():
read_file = open('state_capitals.txt','r')
lines = read_file.readlines()
ran_lines = random.randrange(0,49)
string_lines = lines[ran_lines]
global string_lines_split # To make debugging easier
string_lines_split = string_lines.split(',')
print(string_lines_final[1]) # Print correct answer
usr_input = input(string_lines_split[0])
if usr_input == str(string_lines_split[1]):

When I execute run(), everything works fine until I enter my answer. I am prompted for an answer, and when I enter it, even if my answer is exactly the same as the answer in string_lines_split1, the program prints that my answer is wrong. Link to text document:



Thank you for reading about my issue, and guiding me toward a solution. I look forward to working with the stackoverflow community.

Answer Source

First your code has error: print(string_lines_final[1]) should be print(string_lines_split[1]).

Your problem is that there is a trailing '\n' in string_lines_split[1] which causes the comparison failed.

Try changing string_lines = lines[ran_lines] to string_lines = lines[ran_lines].rstrip().

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download