Curly.Q
Curly.Q

Reputation: 11

Python - Basic Explanation for Someone Trying to Understand (CSV, Excel)

I have go through this code line by line and explain each step. However, as I am extremely new to python (like this is my first work with it) I am very confused as to what this function is doing/why I am getting an error message. Any help would be appreciated!

print("Exercise 2 begins")
import csv  
c = 0       
t = 0      

with open('adele.csv','r') as csvfile:
    csvdata = csv.reader(csvfile, delimiter='\t')  
for line in csvdata:  
    t = t + 1         
    try:
        if 'grammy' in line[5]:  
            c = c + 1            
            print(c + ": " + t + ": " + str(line[5]))   # (7) Describe the purpose of this line
    except IndexError:           
        pass                    

csvfile.close()
print("Exercise 2 ends\n")

Upvotes: 1

Views: 57

Answers (1)

Eric Duminil
Eric Duminil

Reputation: 54223

The error message is that the code should be indented after for line in csvdata:.

print("Exercise 2 begins")

import csv  # Include csv package to allow processing of csv files
c = 0       # Initialize a variable "c" with value "0"
t = 0       # Initialize a variable "t" with value "0"

# (1)  You will run into an error when running this code. 
#      What is the error message? 
#      What does the message mean and how do you fix it?

with open('adele.csv','rb') as csvfile:
    csvdata = csv.reader(csvfile, delimiter='\t') # (2) What does this line mean
    for line in csvdata:                          # (3) What does this line mean
        t = t + 1         # (4) Describe the purpose of this line
        try:
            if 'grammy' in line[5]:  # (5) What does this line mean and 
                                     # what is in line[5]
                c = c + 1            # (6) What does this line mean
                print(c + ": " + t + ": " + str(line[5])) # (7) What does this line mean
        except IndexError:           
            pass

Depending on adele.csv, this code may or may not work. Try it, and try to understand what it does and how. Without error message, it will be easier to understand.

This code might check the number of grammy awards won by Adele, but it's hard to say without seeing adele.csv.

Upvotes: 1

Related Questions