Python 函数中未定义变量

Python 函数中未定义变量,python,Python,我是一个初学者,我想制作一个计数器,然后使用该计数器检查一个数字是否颠倒,但我总是得到(name“count”未定义)错误 它不适用于数字大于3的数字,因为它只检查第一个数字和最后一个数字 更好的解决方案 def Counter(Num): Num = str(Num) count = 0 for i in Num: count = count + 1 # count variable is local to Counter function. r

我是一个初学者,我想制作一个计数器,然后使用该计数器检查一个数字是否颠倒,但我总是得到(
name“count”未定义
)错误

它不适用于数字大于3的数字,因为它只检查第一个数字和最后一个数字

更好的解决方案

def Counter(Num):
    Num = str(Num)
    count = 0
    for i in Num:
        count = count + 1
    # count variable is local to Counter function. return the value get make it available from where it is being called
    return count

def Reverse(Number):
    count = Counter(Number)
    Number = str(Number)
    if Number[0] == Number[count-1]: # index starts from zero. last index is count-1.
        print("The Original and The Reversed numbers are the same\n")
    else :
        print("The Original and the Reversed numbers aren't the same\n")
Reverse(123)

您可以将变量定义为全局变量,也可以执行count-1,否则索引超出范围

看起来count是在“Counter”函数中定义的,它超出了“Reverse”函数的范围。请使用完整的错误回溯更新您的问题。您对错误的声明与您发布的代码中的错误不匹配。
count
Counter
中定义。函数
Reverse
无法获取变量
count
。您的意思是:
如果数字[0]==Number[-1]:
?我调用了函数“Reverse”,它调用函数“Counter”,那么为什么变量“count”没有定义?您是对的,但这不是我的抱怨,我只是想知道,为什么在函数中调用count之后,它还没有定义。如果你不调用变量,你可以通过赋值来创建它们。然后,如果在函数内部创建它们并退出该函数,它们将被销毁。你可以按照这个答案返回它们的值。我不知道变量在函数结束后会被销毁,有没有办法在调用函数后保持变量的值?还有,为什么我应该避免使用globals呢?作为一个程序员,你应该非常非常努力地避免使用globals。
def Counter(Num):
    Num = str(Num)
    count = 0
    for i in Num:
        count = count + 1
    # count variable is local to Counter function. return the value get make it available from where it is being called
    return count

def Reverse(Number):
    count = Counter(Number)
    Number = str(Number)
    if Number[0] == Number[count-1]: # index starts from zero. last index is count-1.
        print("The Original and The Reversed numbers are the same\n")
    else :
        print("The Original and the Reversed numbers aren't the same\n")
Reverse(123)
def Reverse(Number):
     Number = str(Number)
     if Number == Number[::-1]:  # Number[::-1] reverses the string
         print("The Original and The Reversed numbers are the same\n")
     else :
        print("The Original and the Reversed numbers aren't the same\n")
def Counter(Num):
Num = str(Num)
count=0
for i in Num:
    count = count + 1

def Reverse(Number):
    count=  Counter(Number)
    Number = str(Number)
    if Number[0] == Number[count-1]:
        print("The Original and The   Reversed numbers are the same\n")
    else :
        print("The Original and the Reversed numbers aren't the same\n")
Reverse(123)