Search code examples
pythonfunctionfile-handling

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?

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