大蟒日志4

十、函数1

  1. 关键词def,函数调用
  2. 函数形参/实参
  3. 局部变量
  4. 全局语句
#2018.3.29
#FUNCTION
#1.Key word: def
def say_goodbye():
    print('goodbye my love')

say_goodbye() #call the function
say_goodbye() #again


#2.Function Parameters(parameter=formal parameter, argument=actual parameter注意区分!)
#Ex.Which is the minimum
def print_min(a,b):
    if a < b:
        print(a,'is minimum.')
    elif a == b:
        print(a,'is equal to',b)
    else:
        print(b,'is minimum.')
#以下两种调用方式结果相同
print_min(0.999999,1)

s = 0
t = -10
print_min(s,t)

#2018.3.30
#3.Local Variables 局部变量
x = 666

def func(x):
    print('x is', x)
    x = 2
    print('Change local x to', x)

func(x)
print('x is still', x)

#4.global statement 全局语句
#我们可以用global, 在函数中声明我们所引用的变量是全局变量
#即使函数中其他变量与全局变量无同名的,也应该在引用时用global声明, 以便清楚变量来由
x = 888

def func():
    global x
    print('x is', x)
    x = 666
    print('Change global x to', x)

func()
print('Value of x is', x)
'''
输出结果:
x is 888
Change global x to 666
Value of x is 666
'''

y = 888

def func():
    x = 666
    print('x is', x)
    global y
    print('Change global x to', y)

func()
'''
输出结果:
x is 666
Change global x to 888
'''
#在引用多个全局变量时,可以这样global x,y,z

【注】关于parameter和argument的区别请参考Wikipedia词条:
https://en.wikipedia.org/wiki/Parameter_%28computer_programming%29

【声明】本博文为学习笔记,含有个人修改成分,并非完全依照《a byte of python》,仅供参考。若发现有错误的地方,请不吝赐教,谢谢。同时,我也会不定期回顾,及时纠正。#

猜你喜欢

转载自blog.csdn.net/csdner_0/article/details/79763941
今日推荐