python 学习之二 函数篇

时间:2022-09-07 17:13:47

1、函数
#!/usr/bin/python
# Filename:function1.py
def sayhello():
print'Hello world'
sayhello() #call the function

2、行参
#!/usr/bin/python
# Filename:function2.py
def which_max(a,b):
if a > b:
print a, 'is the max' #注意缩进了!!!错了好几次了
else:
print b, 'is the max'
which_max(12,3)
m=2
n=10
which_max(m,n)
print'Done'

3、局部变量
#注意:IndentationError: unindent does not match any outer indentation level
#应该是缩进问题,特别是把几个不同的源码拷到一块修改调式的时候容易遇到,因为两个人写的程序缩进可能不一样,有的是tab,有的是空格
#!/usr/bin/python
# Filename:func_local.py
def func(x):
# print 'hello1'
print 'x is', x
# print 'hello2'
x = 2
print 'change x is', x
x = 10
func(x)
print 'x is still', x
print 'Done'

4、全局变量
#!/usr/bin/python
# Filename:func_global
def func():
global x
print 'x is',x
x = 1
print 'change x is',x
# start to the function
print 'hello'
x = 20
func()
print 'ture of x is',x
*乘两个数相乘或是返回一个被重复若干次的字符串2 * 3得到6。'la' * 3得到'lalala'。
5、默认值#! /usr/bin/python
# Filename:func_default.py

def say(message, times = 3):
print message * times #这里有点不解,为什么这么表达???
# *乘两个数相乘或是返回一个被重复若干次的字符串2 * 3得到6。'la' * 3得到'lalala'。
say('hello') #相当于hello执行三次,调用say()函数
say('hell0', 5)
#注释say(6,'hello'') 为无效

6、关键参数
#!/usr/bin/python
# Filename: func_key.py

def func(a, b=5, c=10):
print 'a is', a, 'and b is', b, 'and c is', c
func(3, 7)
func(25, c=24)
func(c=50, a=100)