mardi 1 décembre 2015

A confusion about scopes of If Else statements in python

def numbers_def(n):
    #######if-1#######
    if n <= 1:
        print('0 and 1 is special numbers')
        return False
    ######end of if-1######

    for x in range(2, n):
        ########if-2#######
        if n % x == 0:
            print('({}) = ({}) X ({})'.format(n, x, x))
            return False
        #####end of if-2#####


    #######else-1######
    else:
        print('({}) is a prime number'.format(n))
        return True

for x in range(0, 20):
    numbers_def(x)

This is a simple Python program to find the prime numbers between 0 to 20, that i found in a video tutorial. In above program if-1 start's in line number 2, and stop in line number 6. if-2 is in side of the for loop And there is a else-1 which is not belongs to any of the above if statements. If it was belongs to if-1 it should generate the following output when the parameter n is equal to 4

4 = 2 X 2 
4 is a prime number

How does that else-1 act for this program? What is the purpose of using return boolean values? Thank you!

Aucun commentaire:

Enregistrer un commentaire