无法理解python中变量的作用域

2024-05-07 16:24:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我编写了这个简单的函数来检查给定的字符串是否是回文

from math import ceil
p=0
def pal(s):
    y=0
    p=0
    for x in range(int(ceil(len(s)/2))):
        if s[x]==s[-x-1]:
            y+=1
            print y
    if y==int(ceil(len(s)/2)):
        print "Palindrome"
    else:
        print "Not Palindrome"

这个很好用。但是,如果我找到一个回文,我想把找到的变量改为1。否则为0。通过其他功能我想检查一下

if found==0:
   do_something
else:
   do_something

我得到变量未定义错误。如何解决此问题?你知道吗


Tags: 函数字符串fromimportlenifdefmath
1条回答
网友
1楼 · 发布于 2024-05-07 16:24:23

首先,让我们定义一个函数,如果它的参数是回文,则返回1,否则返回0:

def palindrome(s):
    return int(s == s[::-1])

现在,我们可以将回文函数的结果赋给变量found,并对其执行一些操作,例如print:

found = palindrome('abba')
if found == 1:
    print "Palindrome"
else:
    print "Not Palindrome"

使用全局变量

还可以使用全局变量从函数返回信息:

def palindrome(s):
    global found
    found = int(s == s[::-1])

palindrome('abccba')
if found == 1:
    print "Palindrome"
else:
    print "Not Palindrome"

然而,当使用全局变量时,代码往往更难调试和维护。因此,不鼓励大多数使用全局变量。举个例子,Google的python样式指南在标题:"Avoid global variables."下更详细地讨论了这个问题。你知道吗

相关问题 更多 >