0

This is a prime number checker. I don't understand why when I type the code like this:

**pr = 0**
def prime_checker(number):
    
    for i in range(2,number):
        if number % i == 0:
            pr += 1
    if pr == 0:
        print("This is a prime number")
    else:
        print("This is not a prime number")
            
n = int(input("Check this number: "))
prime_checker(number=n)

it gives me an error but when I type it like this:

def prime_checker(number):
    **pr = 0**
    for i in range(2,number):
        if number % i == 0:
            pr += 1
    if pr == 0:
        print("This is a prime number")
    else:
        print("This is not a prime number")
            
n = int(input("Check this number: "))
prime_checker(number=n)

the code works as planned. All I did was move the "pr" variable inside the prime_checker function. What exactly is going on here?

  • Have a read of this - https://www.programiz.com/python-programming/global-keyword – ScoJo Jan 25 '21 at 17:07
  • Does this answer your question? [Python scope: "UnboundLocalError: local variable 'c' referenced before assignment"](https://stackoverflow.com/questions/146359/python-scope-unboundlocalerror-local-variable-c-referenced-before-assignmen) – sahasrara62 Jan 25 '21 at 17:08
  • Does this answer your question? [Using global variables in a function](https://stackoverflow.com/questions/423379/using-global-variables-in-a-function) – bbnumber2 Jan 25 '21 at 17:08
  • The issue is that `pr += 1` is equivalent to `pr = (pr + 1)`, and in Python you can't do `pr = (anything)` unless you first use `global pr` in the scope in which you're trying to do the assignment, since, `pr` was declared in global scope. – Random Davis Jan 25 '21 at 17:23

0 Answers0