-3

I am somewhat new to coding. I am making a quiz where I read in questions from a csv file. I don't understand why my code will not print "Correct. Well Done." when the user inputs a correct answer. Instead, it always prints "Incorrect." I have made sure userInput and answer is the same by printing them.

FILENAME = 'quiztest.csv'

def welcomeUser():
    name = input("Hello. Please enter your name: ")
    print("Welcome " + name + "!")
    
def readFile():
    with open(FILENAME, "r") as file:
        for line in file:
            line = line.split(",")
            question = line[0]
            options = line[1]
            answer = line[2]
            askQuestion(question, options, answer)
    
def askQuestion(question, options, answer):
    print(question)
    print(options)
    userInput = input("Please enter the answer: ")
    print(userInput)
    print(answer)
    if userInput == answer:
        print("Correct. Well Done.")
    else:
        print("Incorrect.")
            
    
    
readFile()

What is returned:

What is my name?
Tom Jeff Fred Sam
Please enter the answer: Sam
Sam
Sam

Incorrect.
  • 1
    @JonathonReinhart No, the newline is **not** included in the string returned by `input`. – Thierry Lathuille Feb 27 '21 at 20:24
  • 3
    But if the answer is the last part of the line, then it contains one. So, the change should be `answer = line[2].strip()`. – Thierry Lathuille Feb 27 '21 at 20:25
  • @CODER123456789, note the [mre] guidelines -- ideally a question should have _the shortest possible program that replicates a specific problem when run without changes_. We don't need your whole quiz program; just something that reads a line from a file and compares a string to it would do. (You could _try_ hardcoding the line from the file and see if that solves the bug, and then _try_ hardcoding the line from user input and see if _that_ solves the bug, and the process of trying those two things would either help you ask a narrow question or give you enough of a hint to solve it yourself). – Charles Duffy Feb 27 '21 at 20:38
  • @Thierry Err, oops. Thanks, deleted my comment. – Jonathon Reinhart Feb 27 '21 at 20:39

1 Answers1

0

Notice the blank line between the last "Sam" and the "Incorrect" in your output. The value in answer includes a newline since it was the last part of the line you read from the input file, and the way you are reading that file, you get a newline at the end of each line that you process.

Your problem is easy to fix. Just call strip() to strip the newline off of the end of the input line you read from the input file:

def readFile():
    with open(FILENAME, "r") as file:
        for line in file:
            line = line.strip().split(",")
            question = line[0]
            options = line[1]
            answer = line[2]
            askQuestion(question, options, answer)
CryptoFool
  • 21,719
  • 5
  • 26
  • 44