Write a python function Read_Prime(fname, list) which takes a list of numbers as an input, use this number to write them in a file "primes.txt" . The function then read the file and return a list containing only prime numbers as shown in the example. Also, write the exception handling code to show the proper message.
Example-1
Example-2
Example-2
Input:
primes.txt
[1,2,3,4,5,6,7]
Output:
[1,2,3,5,7]
Input:
primes.txt
[3,6,5,13,18,21]
Output:
[3,5,13]
Input:
primes.txt
[2,4,6,8,10]
Output:
[2]
import json
def Read_Prime(fname, list):
array=[]
rez =[]
isdig = 0
for number in list:
if not number.isdigit():
isdig = 1
print(f'{number} is not number')
return
else:
array.append(int(number))
if isdig == 0:
with open(fname, 'w') as fw:
json.dump(array, fw) # write list
with open(fname, 'r') as fr:
lst = json.load(fr) # read list
for i in range(len(lst)):
isprime = 1
if lst[i] > 1:
for num in range (2, lst[i]):
if lst[i] % num == 0:
isprime = 0
if isprime == 1:
rez.append(int(lst[i]))
else:
rez.append(int(lst[i]))
if len(rez) == 0:
print('No prime numbers')
return rez
print('Enter filename: ', end='')
filename = input()
print('Enter list: ', end='')
a = input().split()
print(Read_Prime(filename, a))
Comments
Leave a comment