简体   繁体   中英

I keep on getting NameError: name 'a' is not defined?

def main():
   a == 3
   b = a + 1
   c = b + 1
   print(a)

if (a<0):
    print(a<0)
    print(c)

else:
    print('a is not less than 0')
    print(a)

I watched the khan academy video #1 on Python programming and tried to duplicate it but it kept on giving the error above. Thanks for your help I am a first time python user

You are not assigning to a ; you are instead testing for equality with a double == :

a == 3

Since you didn't assign anything to a yet to compare with 3 , that results in a NameError .

Remove one = sign to assign instead:

a = 3

This all assumes that the rest of your code is indented correctly to match the rest of your function:

def main():
    a = 3
    b = a + 1
    c = b + 1
    print(a)

    if (a<0):
        print(a<0)
        print(c)

    else:
        print('a is not less than 0')
        print(a)

== is used for comparison tests. You need to use = for variable assignment:

a = 3

Also, as your code currently stands, the stuff outside of main will not be able to access a because it is local to the function. Hence, you need to indent it one level:

def main():
   a = 3
   b = a + 1
   c = b + 1
   print(a)

   if (a<0):
       print(a<0)
       print(c)

    else:
       print('a is not less than 0')
       print(a)

main()

I think you want the following code:

def main():

    a = 3
    b = a + 1
    c = b + 1
    print(a)
    if (a<0):

        print(a<0)
        print(c)

    else:

       print('a is not less than 0')
       print(a)

main()

You want the if statements to be inside the function that you're making, in this case main(). Otherwise, 'a' will not be defined because it is inside the function main(). Welcome to python, and to stack overflow!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM