0

I need to import the values of the variables sum and diff into my test.csv file, how can I do that? I leave my code below:

x=3
y=5
z=2
sum=x + y + 5
diff= x-y-5

with open('test.csv', 'w', newline='') as f:
    thewriter.writerow(['sum', 'diff'])

2 Answers 2

2

Don't use sum as a variable name in Python as it is the name for a builtin function. Also quotes define a string and don't refer to a variable.

dif = 10
print('dif')
print(dif)

outputs:

dif
10

your code would look like

import csv

x=3
y=5
z=2
sum_x_y=x + y + 5
diff= x-y-5

with open('test.csv', 'w', newline='') as f:
    thewriter = csv.writer(f)
    thewriter.writerow(["sum_x_y", "diff"])
    thewriter.writerow([sum_x_y, diff])
Sign up to request clarification or add additional context in comments.

4 Comments

It is possible that the OP wanted the csv file to have a header row of sum, diff with the actual data as the second row and that's why the OP was writing out literal strings. This is based on my assumption that the OP knows the difference between diff and 'diff'.
ah yes might be possible, i updated my answer according to this
Of course. there is no reason why the header row column cannot be named sum -- there is no naming conflict in that context.
yes, but i think it's better practice just not to use it
0

Delete quotation marks in the list eg. ‘sum’ to sum. sum is the name of variable and ‘sum’ is a string object. By adding the quotation marks you are saying that you want to write string ‘sum’ and ‘diff’.

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.