I am trying to create a spelling test function where the definitions of 10 words are already in a csv (txt) file as one record (eg. definition_1,definition_2,etc.). I am trying to print each one separately and retrieve an input as a variable, which could be stored in another csv file afterwards. This is as far as I have gotten, but I don't seem to be having any luck with the code working. Please take into consideration that I have just started learning to code.
def sit_a_test():
print "Test"
## Reads and prints each row of the csv file to display the definition of the allocated word.
cr = csv.reader(open('Test.txt','rb'))
for row in reader:
print "Defintion 1: ",row[0]
# Allows the user to input their answer in response to the definition. Saves the input as a variable. Repeats for each row.
answer = raw_input("Answer: ")
print "Defintion 2: ",row[1]
answer_2 = raw_input("Answer: ")
print "Defintion 3: ",row[2]
answer_3 = raw_input("Answer: ")
print "Defintion 4: ",row[3]
answer_4 = raw_input("Answer: ")
print "Defintion 5: ",row[4]
answer_5 = raw_input("Answer: ")
print "Defintion 6: ",row[5]
answer_6 = raw_input("Answer: ")
print "Defintion 7: ",row[6]
answer_7 = raw_input("Answer: ")
print "Defintion 8: ",row[7]
answer_8 = raw_input("Answer: ")
print "Defintion 9: ",row[8]
answer_9 = raw_input("Answer: ")
print "Defintion 10: ",row[9]
answer_10 = raw_input("Answer: ")
## Writes answer inputs to the csv file in preperation to be calculated as a score.
with open('Score.txt','w',newline='') as fp:
a = csv.writer(fp,delimeter=',')
data = [answer,answer_2,asnwer_3,answer_4,answer_5,answer_6,answer_7,answer_8,answer_9,answer_10]
I would break this up a little:
def ask_question(number, definition):
""" Asks a question for definition number """
print "Definition {}: {}".format(number, definition)
return raw_input("Answer: ")
def sit_a_test():
results = []
with open("Test.txt", "rb") as f:
for row in csv.reader(f):
results.append(list(ask_question(no, def) for no, def in enumerate(row))))
with open("Score.txt", "wb") as f:
writer = csv.writer(f)
writerow.writerows(results)
The ask_question()
function asks a question with a definition number and the definition and returns the answer from the user. The answers are gathered in a list. Each list contains the answers from a single row for the definition from the Test.txt
. I assume that your csv-file contains rows like this
definition_1, definition_2, definition_3..
definition_1, definition_2, definition_3..
definition_1, definition_2, definition_3..
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.