Faced with a practical situation and aiming at a better efficiency of the code it would be interesting to organize the logic of the question as follows:
- Capture the value of
n
;
- Calculate all the prime numbers which were greater than or equal to
"2"
and less than or equal to "n"
.
With this logic I implemented the following code:
def exibir_primos(n):
li = 2
numeros_primos = list()
while li <= n:
if primo(li):
numeros_primos.append(li)
li += 1
return numeros_primos
def primo(m):
i = 1
cont = 0
while i <= m:
if m % i == 0:
cont += 1
i += 1
if cont != 2:
return False
else:
return True
num = int(input('Digite um número inteiro: '))
print(f'\033[32mOs números primos entre "2" e "{num}" são:\n{exibir_primos(num)}')
See here the functioning of the code.
Note that when we execute this code we receive the following message: Digite um número inteiro:
. Right now we must enter an integer number.
Later this value is sent to function exibir_primos()
. From this moment the block while
shall travel through the closed interval [2, n] and, with the aid of the block if
, will be verified whether each element, of the respective interaction, is in fact a number cousin. So the block if
will ask the function primo()
if the value li
is in fact a prime number. At this time the funcao()
shall calculate the amount of li
. If this amount is equal to 2, the function exibir_primos
receive from the function primo()
the value True. Otherwise, the function exibir_primos
will receive the value False.
If the function returns primo()
be it False, the for
of function exibir_primos
end the respective interaction and start the next one. If the function returns primo()
be it True, the value that has been confirmed as prime will be added to the list numeros_primos
.
This verification will be performed to each of the numbers who are in the closed interval [2, n]. After you have completed these checks, the function return - which in this case is the list numeros_primos
- will be shown.
Example:
Imagine we wish to know which prime numbers are greater or equal to 2 and less than or equal to 26.
At the time of execution of the code we received the message: Digite um número inteiro:
. Right now we must type...
26
...and press enter
.
From now on the code will perform all the work and show us the following output:
Os números primos entre "2" e "26" são:
[2, 3, 5, 7, 11, 13, 17, 19, 23]
Note that the program will display all prime numbers greater than or equal to "2" and less than or equal to "26".
Observing:
The numbers 24, 25 and 26 were not displayed in the list - as were other numbers - because they were not prime.
what is that
/033
in theprint(f)
? What does he do?– yoyo
@Yoyo, the
\033
is an octal code that serves as an escape character ANSI.– Solkarped