Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Write a function called write_nums() that outputs the first positive n numbers to a txt file called nums.txt

I have to print first n positive numbers for ex if its first 10 positive numbers then the output should be as follows

1    1
2    2
3    3
4    4
5    5
6    6
7    7
8    8
9    9
10  10

it should print the first 10 numbers in 10 lines but my output is as follows:

1    1
2    2
3    3
4    4
5    5
6    6
7    7
8    8
9    9
10  10
11

how do i delete the 11th line?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

this is my code

def write_nums(n):
  with open("nums.txt", 'w') as fp:
    for i in range (1,11):
     fp.writelines(str(i)+"\n")   
pass
if __name__ == "__main__":
  write_nums(10) 
  # writes out the first 10 positive numbers to nums.txt

>Solution :

A very crude way of doing so can be by adding an if else statement for the last run of the loop

def write_nums(n):
  with open("nums.txt", 'w') as fp:
    for i in range (1,n+1):
      if i != n:
        fp.writelines(str(i)+"\n")
      else :
        fp.writelines(str(i))   
pass
if __name__ == "__main__":
  write_nums(10) 
  # writes out the first 10 positive numbers to nums.txt

I am not sure if this is the best way to do it, but it will get the code working the way you want it

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading