简体   繁体   中英

Getting an NameError but my variable is defined

I do not know why I am getting this error

NameError: name 'len_num' is not defined

def is_armstrong_number(num):
#Convert number to string
    num_str = str(num)
#Get length of number
    len_num = len(num_str)
#Select each number in string and store it in list
for x in range(1,len_num):
    num_list.insert(x,num_str[x])
#Convert back to int
    int(num_list)
#Compare armstrong number and list
for x in range(1,len_num):
   if num == num_list(x) ** len_num:
    print("It is an armstrong number")
else: print("It is not an armstrong number")
pass  

len_num is local to the function so I do not see the issue with the name since it is defined before it is used.

Your issues could be with identation. Compare with my code:

def is_armstrong_number(num):
    #Convert number to string
    num_str = str(num)
    #Get length of number
    len_num = len(num_str)
    #Select each number in string and store it in list
    for x in range(1,len_num):
        num_list.insert(x,num_str[x])
    #Convert back to int
        int(num_list)
    #Compare armstrong number and list
    for x in range(1,len_num):
       if num == num_list(x) ** len_num:
        print("It is an armstrong number")
    else: print("It is not an armstrong number")
    pass

is_armstrong_number(2)
# Output
# It is not an armstrong number
~                      

I don't get the error after running.

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