我的名字是Seix_Seix,我对我正在构建的Python程序有疑问。Python将输入与文件中的行进行比较?
事情是,我正在做一个“谜题游戏”(愚蠢,对吧?),练习一些基本的Python技巧。程序的预期流程是你给它一个从1到5的数字,然后打开一个文件,其中存储了所有的谜语,并将它打印在你给出的数字的行中。 之后,它会要求你输入,在其中键入答案,然后(这是所有土崩瓦解下)它你的答案上比较相应线路的另一文件(这里所有的答案都)。
下面是代码,所以你可以给它一个看看*(这是在西班牙,因为它是我的母语,但它也有在注释的翻译和解释)
# -*- coding: cp1252 -*-
f = open ("C:\Users\Public\oo.txt", "r") #This is where all the riddles are stored, each one in a separate line
g = open ("C:\Users\Public\ee.txt", "r") #This is where the answers to the riddles are, each one in the same line as its riddle
ques=f.readlines()
ans=g.readlines()
print "¡Juguemos a las adivinanzas!" #"Lets play a riddle game!"
guess = int(raw_input("Escoge un número entre 1 y 5. O puedes tirar los dados(0) ")) #"Choose a number from 1 to 5, or you can roll the dice (0)" #This is the numerical input, in which you choose the riddle
if guess==0:
import random
raw_input(random.randrange(1, 5))
print (ques[guess-1]) #Here, it prints the line corresponding to the number you gave, minus 1 (because the first line is 0, the second one is 1 and so on)
a=input("¿Sabes qué es?") #"Do you know the answer?" #Here, you are supposed to type the answer to the riddle.
while True:
if a==(ans[guess-1]): #And here, it is supposed to compare the answer you gave with the corresponding line on the answer file (ee.txt).
print "ok" #If you are correct it congratulates you, and breaks the loop.
break
else:
print "no" #If you are wrong, it repeats its question over and over again
所以,我跑该程序。一切都很好,直到我不得不输入答案为止;在那里,不管我说,即使它是正确的还是错误的,它给了我一个错误:
Traceback (most recent call last):
File "C:\Users\[User]\Desktop\lol.py", line 16, in <module>
a=input("¿Sabes qué es?") #"Do you know the answer?" #Here, you are supposed to type the answer to the riddle.
File "<string>", line 1, in <module>
NameError: name 'aguacate' is not defined #It is the correct answer BTW
我知道当它开始比较回答了这个问题会产生,我也知道这可能是因为我写错了... Sooo,关于如何做到这一点的任何建议是正确的?
预先感谢
亲爱的母亲......它实际上工作!我真的觉得,**现在真的**哑......¬¬ 但是,虽然严重,但非常感谢** **非常**。 对于骰子的一部分,我很专注于解决比较问题,我完全忘了它... 哦!还有一件事...你可以给我一些关于代码的意见吗?我在这里是一个完整的n00b,所以我可以使用我可以得到的所有反馈... 再次感谢, Seix_Seix –
@Seix_Seix:好的,我编辑了我的答案。我希望你会像我一样享受StackOverflow。您可能还需要花一点时间阅读[FAQ](http://stackoverflow.com/faq),这将有助于您更好地开始工作(没有任何恼人的老态偶的风险):) –
+1,患者和完整答案。 – nneonneo