Use of Else outside an if

Asked

Viewed 48 times

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?

  • 5

    In Python the for possesses else.

  • @Anderson as well?

  • @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.

  • 1

    Yes, I commented, before reading the question, now I’m curious waiting for the answer of @Andersoncarloswoss :P +1

  • 1

    http://book.pythontips.com/en/latest/for_-_Else.html

  • 1

    As @Andersoncarloswoss said, on python you can add a else at the end of the: for x in range(0,10): print(x) else: print(x)

Show 1 more comment
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.