Programming Examples

Python program to write first n prime number in text file


Write a Python program which write a first n prime in txt file (each line contain one prime no.)

Solution:

prime=[]
limit=int(input("How many prime numnbers you want to write : "))
n=2
count=0
while count<=limit:
    flag=True
    for a in range(2,n):
        if n%a==0:
            flag=False
    if flag==True:
        count=count+1
        prime.append(str(n)+"\n")
    n=n+1
fp=open("prime.txt","w")
fp.writelines(prime)
fp.close()
Output

CCC Online Test 2021 CCC Practice Test Hindi Python Programming Tutorials Best Computer Training Institute in Prayagraj (Allahabad) Best Java Training Institute in Prayagraj (Allahabad) Best Python Training Institute in Prayagraj (Allahabad) O Level Online Test in Hindi Bank SSC Railway TET UPTET Question Bank career counselling in allahabad Sarkari Naukari Notification Best Website and Software Company in Allahabad Sarkari Exam Quiz