想弄明白为什么我会在没有声明变量时出错
这很好:
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而不是函数中的值
谢谢
当函数返回一个值时,必须将它赋给一个要保留的值。函数内部定义的变量(如下面示例中的
b
)只存在于函数内部,不能在函数外部使用这是因为
largestIP
只存在于findLargestIP
函数的作用域中由于此函数返回一个值,但您只需调用它而不给新变量赋值,因此此值随后会“丢失”
您应该尝试以下方法:
相关问题 更多 >
编程相关推荐