python返回变量时出错,但它会打印fin

2024-09-28 03:14:59 发布

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

想弄明白为什么我会在没有声明变量时出错

这很好:

 def findLargestIP():
         for i in tagList:
                 #remove all the spacing in the tags
                 ec2Tags = i.strip()
                 #seperate any multiple tags
                 ec2SingleTag = ec2Tags.split(',')
                 #find the last octect of the ip address
                 fullIPTag = ec2SingleTag[1].split('.')
                 #remove the CIDR from ip to get the last octect
                 lastIPsTag = fullIPTag[3].split('/')
                 lastOctect = lastIPsTag[0]
                 ipList.append(lastOctect)
                 largestIP  = int(ipList[0])
                 for latestIP in ipList:
                         if int(latestIP) > largestIP:
                                 largestIP = latestIP
 #       return largestIP
         print largestIP

在数字标签列表中,最大的#是16,它输出:

python botoGetTags.py 
16

但是上面只打印出了我需要传递给另一个函数的变量,但是当我修改上面的代码时

         return largestIP
 #       print largestIP

并调用函数:

         return largestIP
         #print largestIP

 findLargestIP()
 print largestIP

我得到这个错误:

python botoGetTags.py
Traceback (most recent call last):
  File "botoGetTags.py", line 43, in <module>
    print largestIP
NameError: name 'largestIP' is not defined

我猜我必须初始化全局变量。。但是当我通过使largestIP=0这样做时,它返回0而不是函数中的值

谢谢


Tags: theinpyforreturntagsremovesplit
2条回答

当函数返回一个值时,必须将它赋给一个要保留的值。函数内部定义的变量(如下面示例中的b只存在于函数内部,不能在函数外部使用

def test(a):
    b=a+1
    return b
test(2) # Returns 3 but nothing happens
print b # b was not defined outside function scope, so error
# Proper way is as follows
result=test(2) # Assigns the result of test (3) to result
print(result) # Prints the value of result

这是因为largestIP只存在于findLargestIP函数的作用域中

由于此函数返回一个值,但您只需调用它而不给新变量赋值,因此此值随后会“丢失”

您应该尝试以下方法:

def findLargestIP():
    # ...
    return largestIP

myIP = findLargestIP() # myIP takes the value returned by the function
print myIP

相关问题 更多 >

    热门问题