Skip to content
Advertisement

How to loop through a column in csv using python

I’m currently making a questionnaire on csv and programming using python. I’m trying to make my code loop through the first column in my spreadsheet and to only print the questions which have the key corresponding to what the user has chosen in this case either 1 for earth or 2 for animals…

enter image description here

The following is the code i have so far but when i loop through this code it doesn’t break if the number is not equal to 1. Also i have tried creating a variable which asks the user for the input on which subject they would like to pick. But when i run the program only the last question prints 5 times regardless if the user inputs 1 or 2, only the question at the bottom of the csv file is printed 5 times.

Here is my code!!

with open('questionnaire.csv') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    for row in csv_reader:
        key = row[0]
        subject = row[1]
        question = row[2]
        option1 = row[3]
        option2 = row[4]
        option3 = row[5]
        option4 = row[6]
        prompt = "Which option do you pick? "
        answer = row[7]
        
        user_prompt = (f"" + question + "n" + option1 + "n" + option2 + "n" +
                       option3 + "n" + option4 + "n" + prompt)

        for key in row[0]:
            if key == '1':
                print(key)
            else:
                break

        questionnaire = input(user_prompt)

Advertisement

Answer

your first for loop is fine, it is iterating over each row. At each iteration you are making key=row[0] which is fine. But then you make another for loop that make no sense for key in row[0] row[0] is either 1 or 2 there is no goal in making a for loop here. I think what you want is start with an input to the user enter the option 1 or 2 (before the for loop) and then, inside the for loop, if key is equal to the user choice you print user_prompt. Is it clear?

[edited] Try this and then create another if/else statement to verify if the user answer is equal to the right answer

selection = input("1 for earth 2 for animals")

with open('questionnaire.csv') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    for row in csv_reader:
        key = row[0]
        subject = row[1]
        question = row[2]
        option1 = row[3]
        option2 = row[4]
        option3 = row[5]
        option4 = row[6]
        prompt = "Which option do you pick? "
        answer = row[7]
        
        user_prompt = (f"" + question + "n" + option1 + "n" + option2 + "n" +
                       option3 + "n" + option4 + "n" + prompt)

        if key == selection:
            user_answer = input(user_prompt)
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement