IF语句不会比较从文件

时间:2017-02-20 19:08:55

标签: python file

我几天前刚开始编程。我制作了这个程序,用户可以在其中创建一个测验(所有的Q&#39和s被写入文件)当我来阅读答案文件时,我创建一个with语句来独立提取每一行,然后将它与Qs文件的每个独立行进行比较。这很好用,我想要比较的价值确实如此。但是当答案实际上匹配文件中的那个时,if语句仍然返回else命令!这太不可思议了!这是输出的澄清。

  

问题1:您的名字是什么

     

输入答案:abdo

     

对不起,那是错的!正确的答案是:abdo

     

你的分数是:0

     

问题2:我的名字是什么

     

输入答案:abdo1

     

对不起,那是错的!正确的答案是:abdo1

     

你的分数是:0

这是我的代码:

import sys
questions = []
answers = []
score = 0
print("+++++++++++++++Welcome to SS Quiz Maker++++++++++++++++")
save = input("Would you like to create a new quiz or load your saved one :")
if save == "y":
    for i in range(0,2):
        print( "Question number",i + 1)
        questions.append(input("Enter a Question :"))
        answers.append(input("Enter an Answer :"))

    f = open("SS_QUIZ_QUESTIONS.txt", "w")
    f.truncate()
    for i in questions:
        f.write(i)
        f.write("\n")
    f.close()
    f = open("SS_QUIZ_ANSWERS.txt", "w")
    for i in answers:
        f.write(i)
        f.write("\n")
    f.close()
else:   
    for i in range(0,2):
        with open('SS_QUIZ_QUESTIONS.txt') as f:
            u = 1
            for line in f:
                if u == i + 1:
                    break
        with open('SS_QUIZ_ANSWERS.txt') as f:
            u = 1
            for line2 in f:
                if u == i + 1:
                    break
        print("Question Number ",i + 1," :",line)
        ans = str(input("input the Answer :" ))

        if  ans == line2:
            print("Correct")
            score = score +1
            print("Your score is :",score)

        else:
            print("Sorry, thats Wrong!")
            print("The right answer is :", line2)
            print("Your score is :",score)

1 个答案:

答案 0 :(得分:2)

问题在于,当您编写文件的答案时,您还会编写换行符"\n"。现在,当您比较字符串时,实际上是将abdo1abdo1\n进行比较,这是错误的。在比较之前,使用.rstrip()字符串上的line2方法。

在您的代码中:

if ans == line2.rstrip():

应该做的伎俩