【问题标题】:If x == y: print z - Why won't my code print? [duplicate]If x == y: print z - 为什么我的代码不打印? [复制]
【发布时间】:2021-02-27 20:18:41
【问题描述】:

我对编码有点陌生。我正在做一个测验,我从 csv 文件中读取问题。我不明白为什么我的代码不会打印“正确。做得好”。当用户输入正确答案时。相反,它总是打印“不正确”。我已经确定userInput 和打印出来的答案是一样的。

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 my name?
Tom Jeff Fred Sam
Please enter the answer: Sam
Sam
Sam

Incorrect.

【问题讨论】:

  • @JonathonReinhart 不,换行符包含在input返回的字符串中。
  • 但如果答案是该行的最后一部分,那么它包含一个。所以,变化应该是answer = line[2].strip()
  • @CODER123456789,请注意minimal reproducible example 指南——理想情况下,问题应该有在不更改运行时复制特定问题的最短程序。我们不需要您的整个测验程序;只是从文件中读取一行并将字符串与其进行比较的东西。 (您可以尝试对文件中的行进行硬编码,看看是否可以解决错误,然后尝试从用户输入中对行进行硬编码,看看是否那个 i> 解决了这个错误,尝试这两件事的过程可以帮助你提出一个狭窄的问题,或者给你足够的提示来自己解决它)。
  • @Thierry Err,哎呀。谢谢,删除了我的评论。

标签: python


【解决方案1】:

请注意输出中最后一个“Sam”和“Incorrect”之间的空白行。 answer 中的值包含一个换行符,因为它是您从输入文件中读取的行的最后一部分,并且您读取该文件的方式是在您处理的每一行的末尾都有一个换行符。

您的问题很容易解决。只需调用strip() 将换行符从您从输入文件中读取的输入行末尾剥离:

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)

【讨论】:

    猜你喜欢
    • 2015-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-07
    • 1970-01-01
    • 1970-01-01
    • 2012-01-09
    • 1970-01-01
    相关资源
    最近更新 更多