Reputation: 71
I am trying to print out and write to a file a nested loop, but I fail the second part. It won't write to a file like a nested loop, but writes in a straight line. How can I solwe the problem?
def valjastaarv():
rida = 12
koht = 12
iste_rida = 3
iste_koht = 2
f = open('tulemus.txt', 'w')
for i in range (1,int(koht)+1):
for j in range (1,int(rida)+1):
print(j, end = " ")
f.write(str(i))
print()
f.close()
valjastaarv()
Upvotes: 1
Views: 1012
Reputation: 1528
You need a newline \n
each time you want to start a new line. Here's the code that works properly:
def valjastaarv():
rida = 12
koht = 12
iste_rida = 3
iste_koht = 2
f = open('tulemus.txt', 'w')
for i in range (1,int(koht)+1):
for j in range (1,int(rida)+1):
print(j, end = " ")
f.write(str(j)+' ')
print()
f.write('\n')
f.close()
valjastaarv()
Upvotes: 2