gpt4 book ai didi

python - IF 语句不比较从文件接收的值

转载 作者:行者123 更新时间:2023-12-01 03:17:19 28 4
gpt4 key购买 nike

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

Question Number 1 : Whats your name

input the Answer :abdo

Sorry, thats Wrong! The right answer is : abdo

Your score is : 0

Question Number 2 : whats my name

input the Answer :abdo1

Sorry, thats Wrong! The right answer is :abdo1

Your score is : 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)

最佳答案

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

在您的代码中:

if ans == line2.rstrip():

应该可以解决问题

关于python - IF 语句不比较从文件接收的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42352483/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com