0
Can someone help me create a user defined list and print all the prime numbers in it using the for loop
10 Answers
+ 2
Language ?
Python, C, C++, Java, JavaScript or any other.
+ 1
Attempts?
+ 1
anusha read the comments:
in your code,
it checks for input n is prime or not only..
a=[]
n=int(input())
for i in range(0,n):
if i<n: #no need this, it's always true
l=int(input())
a.append(l) # indent it into loop, currently it's out side loop
# next this code checks for n is prime or not. Print n if only it's prime
if n>1:
for i in range(2,n):
if(n%i)==0:
break
else:
print(n)
But actually you need to check list items are prime or not..
So create function for prime check that add you code for prime in function and call the function on each item of list like
for i in a :
isPrime(i)
And function :
def isPrime(n) :
#codd for prime check n
Try this..
Hope it helps...
+ 1
#0 to n prime numbers: [Python đ]
n = int(input())
for prime in range(2,n):
for i in range(2,prime):
if(prime%i)==0:
break
else:
print(prime)
0
Sorry i didnt understand
0
anusha
Attempts means did you try to solve if so then share your code here.
0
Language python
0
I did try to solve but it was incorrect
The code is
a=[]
n=int(input())
for i in range(0,n):
if i<n:
l=int(input())
a.append(l)
if n>1:
for i in range(2,n):
if(n%i)==0:
break
else:
print(n)
0
Note that although it's perfectly valid Python to put an input() statement within a loop, that won't work within SL playground. Here, to get a list of numbers as input, you could read them all on one line, separated by spaces (like 15 3 8 12 7) then parse that into a list with:
nums = [int(x) for x in input().strip().split()]
As for searching for primes, in your inner loop, make sure only to try factors up to sqrt(n), (not up to n itself) otherwise your algorithm is extremely inefficient.
0
Create an array that has user defined inputs and with the help of for loop,
fetch all the prime numbers and print the numbers.