Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/286.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 计算机组件琐事项目,奇怪的文本文件问题_Python_Python 3.x - Fatal编程技术网

Python 计算机组件琐事项目,奇怪的文本文件问题

Python 计算机组件琐事项目,奇怪的文本文件问题,python,python-3.x,Python,Python 3.x,我被卡住了;我的老师和同学不知道如何帮助,也不知道为什么会发生这种情况 total=0 questions=open('questions.txt','r') for x in range(20): print(questions.readline()) print(questions.readline()) P1=input('Which answer is correct? type the corresponding letter: ') righta

我被卡住了;我的老师和同学不知道如何帮助,也不知道为什么会发生这种情况

   total=0
questions=open('questions.txt','r')
for x in range(20):
    print(questions.readline())
    print(questions.readline())
    P1=input('Which answer is correct? type the corresponding letter: ')
    rightanswer=questions.readline()
    if P1==rightanswer:
            print('correct!')
            total=total+1
    if P1!=rightanswer:
            print('incorrect!')
所以所有这些都很好,问题在于正确的答案。我的文本文件布局如下:

What is hardware component in a computer that stores random information?
a: VrAM, b: GPU, c: CPU, d: RAM
d

他预计会有20个问题出现在文本文件中。它总是打印“不正确!”,直到最后一个问题,它实际检测到我的答案是正确的。我不知道如何解决这个问题,我的代码似乎还可以,因为它确实可以工作,但只有在文本文件的末尾,它告诉我我的答案实际上是正确的

我怀疑你的问题是@jornsharpe提到的。您可以通过使用string方法strip来纠正这个问题,strip方法删除前导/尾随空格。因此,应将两行更改为:

P1=input('Which answer is correct? type the corresponding letter: ').strip()
rightanswer=questions.readline().strip()

需要从我的行中删除\n,以便它实际上注册为正确答案。

printreprrightanswer-我猜除了最后一行之外,文件中的每一行都有一个新行。哪个答案正确?键入相应的字母:a不正确!什么东西可以容纳计算机中的所有组件?a:CPU,b:RAM,c:主板,d:硬盘哪个答案正确?键入相应的字母:c正确!||||||这是输出。欢迎使用堆栈溢出。这不是家庭作业完成服务。你的导师给了你作业,而不是我们,你需要做你自己的工作。如果你不能开始,向你的老师寻求帮助;他们被雇来教你。如果你的老师给你布置的作业他们自己无法完成,向学校管理部门投诉。祝你好运。好吧,我没想到你们会帮我做任何工作,我只是希望找到解决我问题的办法,因为我的老师建议我四处寻求解决办法。多亏了jonrsharpe的建议,我意识到它一直在打印错误,因为每个正确的答案旁边都有/n,所以实际上不仅仅是字母,而是带有/n的字母。我们可以从线路上删除/n,对吗?这很有效,非常感谢大家。对不起,如果我想让你们做我的“家庭作业”。