Namerror:name 'c' is not defined

def get_gcd(a,b):
    global c
    global gcd 
    global rem 
    if a == 0:
        gcd =+ a 
    elif b == 0:
        gcd =+ b
    else:
        while a%b == 0 or b%a == 0:
            if a<b: 
                c =+ a // b 
                rem =+ a % b
            elif a > b:
                c =+ b //a
                rem =+ b % a
    gcd = c
    print(gcd)    

get_gcd(2,0)

what could be causing this error:

Traceback (most recent call last):
File “/home/naemmastae/Desktop/Python projects/ulamspiral.py”, line 20, in
get_gcd(2,0)
File “/home/naemmastae/Desktop/Python projects/ulamspiral.py”, line 17, in get_gcd
gcd = c
NameError: name ‘c’ is not defined

The error is caused by c not being defined.

c is declared a global variable at the top of the function, but you still need to give it a value somewhere.

okay please show me what you are saying in action

It’s not clear what your script is dong, but as is, the else clause in your function will never run. so c will never have a value.

What’s does this script do?

Trying to access an undefined global variable:

def myfunc():
    global a
    print(a)

myfunc()

Result:

Traceback (most recent call last):

  File ~/tmp/untitled2.py:6
    myfunc()

  File ~/tmp/untitled2.py:3 in myfunc
    print(a)

NameError: name 'a' is not defined

If you define the variable before running the function, it works:

def myfunc():
    global a
    print(a)


a = 1
myfunc()

Result:

1

calculate gcd for two numbers

Ah, right. I know it as Greatest Common Factor.

c won’t have a value even if the else clause runs, because the += requires it to already be defined. The same NameError would still happen.

Yes, ty. I get that – just trying to establish the logic.

what if i’m to assign c to the result of an expression within the loop

Define c outside the loop first, perhaps with the value 0, or some other initial value that makes sense for your application.

The line gcd = c needs to be indented one more level so that it is lined up with the while ... line.

Your code uses =+ in six places. I don’t think that does what you are expecting. I think it is harmless though. Try removing the + sign.

Why do you have the three “global” lines?

saw it somwhere as a solution to an error i had

anyone who sees any error in my logic please dont hesitste to correct me im trying to find the hcf using the euclidean algorithm

@Emma
Not too sure if I fully understand this, but does this do what you want?

def GCD(A, B):
    while A != 0 and B != 0:
        x, R = divmod(A, B)
        A = B
        B = R
    return A


A = 1024
B = 28

print(GCD(A, B))

I followed the principles from here: