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/ Explanation:

Latest Current Affairs 2024 Online Exam Quiz for One day Exam Online Typing Test CCC Online Test Python Programming Tutorials Best Computer Training Institute in Prayagraj (Allahabad) Online MBA 2 years Online MCA Online BCA Best Website and Software Company in Allahabad