1

I'm using the following code:

import csv
f = csv.writer(open("pe_ratio.csv","w"))

def factorial(n):
    results = 1
    # results are one because that is the minimum number 
    while n >= 1:
        results =  results * n
        # results * nth number of n
        n = n - 1   
        # n - 1     
        # two variables are affected in this program results and n
    return f.writerow([results])

print factorial(4)

file.close()

And I get this error:

Traceback (most recent call last):
  File "pe_ratio.py", line 23, in <module>
    print factorial(4)
  File "pe_ratio.py", line 21, in factorial
    return f.writerows([results])
_csv.Error: sequence expected

I suspect I will need to read the CSV documentation and do it in-depth to figure out this problem. What I am trying to accomplish is to get the csv file to write in a row factorial(4)'s result. I have tried taking out the print function for factorial(4) and the program stalled. Thanks for the help in advance.

Robert Birch
  • 231
  • 2
  • 4
  • 16

1 Answers1

1
import csv
with open("pe_ratio.csv", "w") as out_file:
    f = csv.writer(out_file)

    def factorial(n):
        results = 1
        # results are one because that is the minimum number 
        while n >= 1:
            results =  results * n
            # results * nth number of n
            n = n - 1   
            # n - 1     
            # two variables are affected in this program results and n
        return f.writerow([results])  # <---note writerows vs writerow

    print factorial(4)
tacaswell
  • 73,661
  • 15
  • 189
  • 183