0

Code:

for i in range(2, 21):
    for j in range(1, 11):
        with open(f"tables/Multiplication_table_of_{i}.txt", 'w') as f:
            f.write(f"{i}X{j}={i*j}")
            if j!=10:
                f.write('\n')

By using the above code I'm unable to write the complete table. It gives only values like 2X10, 3X10 , 4X10 and etc. and not the entire table.

Whereas the code given below writes the whole table,

for i in range(2, 21):
    with open(f"tables/Multiplication_table_of_{i}.txt", 'w') as f:
        for j in range(1, 11):
            f.write(f"{i}X{j}={i*j}")
            if j!=10:
                f.write('\n')

Can anyone please explain me what's happening??? I'm unable to iterate the code.

Tharu
  • 188
  • 2
  • 14
  • 1
    not able to read your code, please format it properly – SKJ Oct 09 '21 at 06:44
  • Opening the file like `open(f"tables/Multiplication_table_of_{i}.txt", 'w')` erases any existing contents. So if you do this inside the loop, only the last result will be saved at the end. Please see the linked duplicate for details. – Karl Knechtel Oct 09 '21 at 06:49

0 Answers0