后浪小萌新Python --- 函数就是变量

函数就是变量

定义函数的时候, 其实就是在定义一个类型是function的变量, 函数名就是变量名.

普通变量能做的事情函数都可以做

  1. 查看变量类型
  2. 使用变量中保存的数据
  3. 修改变量的值
  4. 变量可以作为列表元素

    举例:

def a():
    print('函数1')

b = [1, 2, 3]
# 1) 查看变量类型
print(type(b)) 
print(type(a))  

# 2) 使用变量中保存的数据
print(b)   
print(a)    

b2 = b
print(b2[1])
a2 = a
a2()

# 3) 修改变量的值
b = 100
print(b)

a = 'abc'
print(a)

# 4) 变量可以作为列表元素
x = 100

def y():
    return 'abc'

list1 = [x, y ,y()]
print(list1)    
print(list1[0]* 2, list1[0] % 10)
print(list1[2][0], list1[2].replace('a', 'A'))
print(list1[1]())  

运行结果

<class 'list'>
<class 'function'>
[1, 2, 3]
<function a at 0x0000013F569D4A68>
2
函数1
100
abc
[100, <function y at 0x0000013F569D4C18>, 'abc']
200 0
a Abc
abc

猜你喜欢

转载自blog.csdn.net/qq_26209771/article/details/107769519
今日推荐