2

I would like to write two variable in a file. I mean this is my code :

file.write("a = %g\n" %(params[0]))
file.write("b = %g\n" %(params[1]))

and what I want to write in my file is :

f(x) = ax + b 

where a is params[0] and b is params[1] but I don't know how to do this ?

Thank you for your help !

Barmar
  • 741,623
  • 53
  • 500
  • 612

4 Answers4

1

If all you want to write to your file is f(x) = ax + b where a and b are params[0] and params[1], respectively, just do this:

file.write('f(x) = %gx + %g\n' % (params[0], params[1]))

'f(x) = %gx + %g' % (params[0], params[1]) is simply string formatting, where you're putting a and b in their correct spaces.

Edit: If you're using Python 3.6, you can use f-strings:

a, b = params[0], params[1]
file.write(f'f(x) = {a}x + {b}\n')
blacksite
  • 12,086
  • 10
  • 64
  • 109
0
"f(x) = {a}x + {b}".format(a=params[0], b=params[1]) 

Is a clean solution

PdevG
  • 3,427
  • 15
  • 30
0

sorry I don't know Python, but I guess this

f = open('file', 'w')
x = 0;
a = 0;
b = 0;
result = a*x+b
a = str(a)
b = str(b)
x = str(x)
result = str(result)
f.write("f("+x+")="+result) #this is if you want result to be shown
print("f("+x+")="+result)

#or

f.write("f("+x+")="+a+""+x+"+"+b) #this is if you want actually show f(x)= ax+b
print("f("+x+")="+a+""+x+"+"+b)

again I don't know Python, but this is what I come up with by using : https://repl.it/HARP/1

I hope this helps

Cem Sultan
  • 79
  • 1
  • 13
0

You target is to achieve is to write the equation below to be written inside the file.

f(x) = ax + b where a is params[0] and b is params[1]

What you should do is

file.write('f(x) = %gx + %g' % (param[0], param[1]))

which will write

"f(x) = 2x + 3" # if params[0] and params[1] are 2 and 3 resp

What you are doing is

file.write("a = %g\n" %(params[0]))
file.write("b = %g\n" %(params[1]))

This will write in the file as:

a = 2
b = 3

if params[0] and params[1] are 2 and 3 respectively

Jaysheel Utekar
  • 1,171
  • 1
  • 19
  • 37