5
I was writing a program that would give me all prime numbers between 1 and a certain number that should be informed by the user. After several adjustments to the code, I came to the following final version, which apparently works as it should:
from math import *
num = int(input("Informe o limite dos primos: "))
for i in range(1, num+1):
for j in range(2, ceil(sqrt(i+1))):
if i % j == 0:
break
else:
print(i, end = " ")
The code provides the following output:
================ RESTART: C:\Users\usuario2\Desktop\Primos.py ================
Informe o limite dos primos: 20
1 2 3 5 7 11 13 17 19
>>>
================ RESTART: C:\Users\usuario2\Desktop\Primos.py ================
Informe o limite dos primos: 50
1 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
>>>
================ RESTART: C:\Users\usuario2\Desktop\Primos.py ================
Informe o limite dos primos: 100
1 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
However I noticed something very curious: I have one else
out of a if
. How can it? in my view, it should not work. Why does it work?
In Python the
for
possesseselse
.– Woss
@Anderson as well?
– Cadu
@Wictor yes, I’ve been making changes and testing until it works out, but now I want to understand how Else can function outside the if.
– Cadu
Yes, I commented, before reading the question, now I’m curious waiting for the answer of @Andersoncarloswoss :P +1
– Wictor Chaves
http://book.pythontips.com/en/latest/for_-_Else.html
– Wictor Chaves
As @Andersoncarloswoss said, on
python
you can add aelse
at the end of the:for x in range(0,10): print(x) else: print(x)
– Sidon