python - access column in csv file using for loop -
there's nothing quite same on so, hence question:
i have file structure: (csv file called test.csv)
1.what line this? 1 2.what line this? 2 3.what line this? 3 4.what line this? 4 5.what line this? 5 i want program able print first line (1. line this?) , ask user input (answer=?) , if answer equal in corresponding column, output "right".
the code far:
it prints question , asks answer, not 1. output "correct" if it's right 2. move on next question, if right
import csv def main(): open('test.csv','r') f: reader=csv.reader(f) row in reader: questions=row print(questions) answer=input("answer:") answer_correct=false row in reader: field in row: in range(len(questions)): if field==questions[i]: currentindex=questions.index(field) if row[currentindex+1]==answer: answer_correct==true if answer_correct == false : print("wrong answer, sorry!") else: print("****you're right!*****") main() for answer, please:
- suggest fix code, pointing out errors , explaining solution
- suggest more elegant fix /snippet solve problem using csv reader , no other imported tools.
as mentioned code needs to: -present each question, ask user input (answer), if right or wrong (print right or wrong) , move next question, until end of file
so far output:
['1.what line this?', '1'] answer:1 wrong answer, sorry! >>> i've tried this:
import csv
def main(): open('test.csv','r') f: reader=csv.reader(f) row in reader: print(row[0]) answer=input("answer:") answer_correct=false row in reader: field in row: if answer==row[1]: answer_correct==true if answer_correct == false : print("wrong answer, sorry!") else: print("****you're right!*****") main()
i wrote little snippet, works.
import csv open('questions.csv', 'r') f: reader = csv.reader(f) row in reader: question, correct_answer = row print(question) answer = input() if answer == correct_answer: print("wow! su knowledge!") else: print("still trying") seems has wrong indents in code.
, block checking answer executed after whole cycle.
Comments
Post a Comment