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 Python Programming Tutorials Best Computer Training Institute in Prayagraj (Allahabad) Online Exam Quiz O Level NIELIT Study material and Quiz Bank SSC Railway TET UPTET Question Bank career counselling in allahabad Best Website and Software Company in Allahabad Website development Company in Allahabad