Home > front end >  Getting "UnboundLocalError: local variable 'n' referenced before assignment" whe
Getting "UnboundLocalError: local variable 'n' referenced before assignment" whe

Time:11-10

I've written a small code to check if my word is Palindrome or not:

def PalorNot():
  a =input("Enter your word here: ")
  for n in range(0,n 1,1):
    if (a[0]==a[-(n 1)]):
      print("Your word is a Palindrome")
      break
    else:
      print("Your word is not a Palindrome")

PalorNot()

However, I'm getting this error "UnboundLocalError: local variable 'n' referenced before assignment" when running my code.

Strange part is, if I comment out def PalorNot(): and it's call, code works flawless.

Any help would be appreciated as I'm trying to learn Python.

CodePudding user response:

It's because in this line:

for n in range(0,n 1,1):

You're trying to use n... to define n. You can't, because n doesn't exist yet until that line runs.

I believe what you want instead is:

for n in range(0,len(a),1):
  • Related