1

the script runs fine, but only records the last result in the .txt file. What am i doing wrong?

a= float(input('Insert a: ')) b= float(input('Insert b: ')) for c in range(10,300): d= float(46+(9*a)-(7*c)) e= float(-6+(463*b)+(-1*c)+(0.8*a)+(0.89*d)) print(d) print(e) import sys sys.stdout=open("loop.txt","w") print(d) print(e) sys.stdout.close() 
2
  • 3
    Maybe you should open the file BEFORE the loop. Commented Jul 21, 2017 at 14:01
  • 1
    this is because you will write after your loop, so d and e have the last computed values. Commented Jul 21, 2017 at 14:02

2 Answers 2

3

You can write these values inside the loop itself

a= float(input('Insert a: ')) b= float(input('Insert b: ')) with open("loop.txt","w") as f_out: for c in range(10,300): d= float(46+(9*a)-(7*c)) e= float(-6+(463*b)+(-1*c)+(0.8*a)+(0.89*d)) f_out.write('{} {}\n'.format(d, e)) 
Sign up to request clarification or add additional context in comments.

2 Comments

works wonderful, can you send me a link with options to format the output?
This page is a good reference for string formatting, including precision, padding, sig figs, etc.
0

You have to open the stream before doing anything :

import sys sys.stdout = open("loop.txt", "w") a= float(input('Insert a: ')) b= float(input('Insert b: ')) for c in range(10,300): d= float(46+(9*a)-(7*c)) e= float(-6+(463*b)+(-1*c)+(0.8*a)+(0.89*d)) print(d) print(e) sys.stdout.close() 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.