1

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()
1
  • write a newline at the end of the first loop Commented Jan 27, 2018 at 23:03

1 Answer 1

2

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()
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.