Search code examples
pythonfunctionrangeinteger-division

I found this syntax for printing prime numbers and l am quite confused. I would like this community to clarify


Nums = range(1,60)

def is_prime(Nums):
    for x in range(2, Nums):
        if (Nums%x) ==0:
            return False
    return True

prime_numbers = list(filter(is_prime,Nums))

Print(prime_numbers)

With the for x in range(2, Nums) syntax, l expect an error to be raised since the Nums argument is not an interger. How ever, python interprets it successfully and moves to the next line of code.

Again, what does the if (Nums%x) ==0 syntax mean


Solution

  • You are confused because the code snipped uses the same variable name for the function argument and the global variable.

    The code can be interpreted as the following:

    Nums = range(1,60)
    
    def is_prime(n):
        print(n)
        for x in range(2, n):
            if (n%x) ==0:
                return False
        return True
    
    prime_numbers = list(filter(is_prime,Nums))
    
    print(prime_numbers)
    

    You can also use the type function to see what is the type of the Nums argument (n) inside the function (it is an integer).

    I recommend you to read here more about the filter function and if that is not sufficient, you can conduct further research on your own.


    The expression if (Nums%x) ==0:

    • % is the modulus operator in Python, which computes the remainder of the division of the number on its left (Nums) by the number on its right (x).

    • (Nums % x) calculates the remainder when Nums is divided by x.

    • (Nums % x) == 0 checks if the remainder is equal to zero.


    Additionally, I recommend learning more about naming conventions in Python, as they contribute to code readability and understandability

    Naming variables