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.

2

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.