I am trying to create a function that will display the prime numbers from a list of numbers that the user has entered. My problem is that my code does not correctly perform the part where it is defined which are primes or if no number entered is prime. What modifications could you make?
def numeros_primos():
valores = []
while True:
try:
valor = int(input("Ingrese los números: "))
if valor == 0:
break
valores.append(valor)
except ValueError:
print("Inserta un número.")
print(valores)
if valor > 1:
cont = 0
for i in range(2,valor):
resto = valor % i
if resto == 0:
cont+=1
if cont == 0:
print("Los numeros primos son: ", valor)
else:
print("Ningún número ingresado es un número primo")
The structure of your code can be improved. But if you don't want to change it too much you can use a function to check if it's prime or not.
Something like that:
The function is to everyone's taste, this example is from here. .
Other solution
For speed, check if it is a multiple of 2 and, if not, only check the odd divisors, up to
~n/2
, since if it is not prime, at least one divisor must be less than that limit.To get the results asked for a value, we check if it is prime and, if so, we put it in the output list
valores
:When finished,
valores
it will contain all the primes entered: