python 学习之二 函数篇

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)




                  


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值