python—函数实例一

1.函数的定义

练习:判断输入的是不是一个数字

1
2
3
4
5
6
7
8
9
#!/usr/bin/env python
def  isNum():
     sth  =  raw_input ( "Please input something: " )
     try :
         if  type ( int (sth))  = =  type ( 1 ):
             print  "%s is a number"  %  sth
     except  Exception:
         print  "%s is not a number"  %  sth
isNum()


2.函数的参数

练习:判断输入的是不是一个数字

1
2
3
4
5
6
7
8
9
10
11
12
#!/usr/bin/env python
import  sys
def  isNum(s):
     for  in  s:
         if  in  "1234567890" :
             pass
         else :
             print  "%s is not a number"  %  s
             break
     else :
         print  "%s is a number"  %  s
isNum(sys.argv[ 1 ])


3.函数的默认参数

listdir()函数

练习:判断输入的是不是一个数字

1
2
3
4
5
6
7
8
9
10
11
12
13
#!/usr/bin/env python
import  os
def  isNum(s):
     for  in  s:
         if  in  "1234567890" :
            pass
         else :
            break
     else :
         print  s
 
for  in  (os.listdir( "/proc" )):
     isNum(i)


注:默认参数必须写在后面

1
2
3
4
5
6
7
8
9
In [ 3 ]:  def  fun(x = 1 ,y):
...:      print  x + y
File  "<ipython-input-3-3b7bae6400b0>" , line  1
def  fun(x = 1 ,y):
SyntaxError: non - default argument follows default argument
In [ 4 ]:  def  fun(x,y = 1 ):
...:      print  x + y
...:
In [ 5 ]: fun( 2 )


4.1函数变量

练习:函数内部(局部)不能进行全局变量赋值等操作;如果申明成全局变量,才可以

1
2
3
4
5
6
7
8
#!/usr/bin/env python
=  1
def  fun():
     global  x
     x + = 1
     print  x
fun()
print  x


结果:

2

2


练习2:把函数内部变量,申明成全局变量,外部也可以通过函数调用

1
2
3
4
5
6
7
8
9
10
11
12
#!/usr/bin/env python
=  1
def  fun():
     global  x
     + =  1
     global  y
     =  3
     print  x
     print  y
fun()
print  x
print  y


结果:

2

3

2

3


练习3:locas() :统计变量,返回字典

1
2
3
4
5
6
7
8
#!/usr/bin/env python
=  1
def  fun():
     =  1
     =  1
     print  locals ()
fun()
print  locals ()

结果:

1
2
{ 'y' 1 'x' 1 }
{ '__builtins__' : <module  '__builtin__'  (built - in )>,  '__file__' '18.py' '__package__' None 'x' 1 'fun' : <function fun at  0x7f53bc8938c0 >,  '__name__' '__main__' '__doc__' None }


5.函数返回值

练习1:默认返回none

1
2
3
4
#!/usr/bin/env python
def  fun():
     print  "hello,world"
print  fun()

结果:

hello,world

None


练习2:自定义return返回值,return之后的语句将不再执行

1
2
3
4
5
6
#!/usr/bin/env python
def  fun():
     print  "hello,world"
     return  "heihei"
     print  "haha"
print  fun()

结果:

hello,world

heihei


练习3:判断输入是否为数字

函数里很少使用print,使用return,更加简化

1
2
3
4
5
6
7
8
9
10
#!/usr/bin/env python
import  os
def  isNum(s):
     for  in  s:
         if  not  in  "1234567890" :
             return  False
     return  True
for  in  (os.listdir( "/proc" )):
     if  isNum(i):
         print  i


练习4:isdigit()判断输入是否为数字

isdigit():判断字符串是否为纯数字(脚本更更简化)

1
2
3
4
5
6
7
8
9
#!/usr/bin/env python
import  os
def  isNum(s):
     if  s.isdigit():
         return  True
     return  False
for  in  (os.listdir( "/proc" )):
     if  isNum(i):
         print  i


6.多类型传值(元组或字典)和冗余参数

一个元组只表示一个参数;元组加一个*,则可以把元组中的元素作为参数,传到脚本中;带参数的元组只能放在后面,否则有语法错误

练习1:

1
2
3
4
5
6
In [ 2 ]:  def  fun(x,y,z):
...:      print  +  + z
...:
In [ 3 ]: a  =  [ 1 , 2 ]
In [ 4 ]: fun( 3 , * a)
6


报错:

In [5]: fun(*a,3)

File "<ipython-input-5-8a9ea4381ff5>", line 1

fun(*a,3)

SyntaxError: only named arguments may follow *expression


练习2:

字典传参(形参名和实参名一致,位置无所谓)

1
2
3
4
5
6
In [ 8 ]:  def  fun(x,y,z):
...:      print  +  + z
...:
In [ 9 ]: a  =  { "x" : 1 , "y" : 2 , "z" : 3 }
In [ 10 ]: fun( * * a)
6

或者:

In [11]: fun(x=1,y=2,z=3)

6


练习3:

1
2
3
4
5
6
7
8
9
In [ 1 ]:  def  fun(x, * argv, * * kwargv):
...:          print  x
...:          print  argv
...:          print  kwargv
...:
In [ 2 ]: fun( 1 )
1
()
{}

练习4:

以等号或字典形式

1
2
3
4
5
6
7
8
9
10
In [ 6 ]:  def  fun(x, * argv, * * kwargv):
...:          print  x
...:          print  argv
...:          print  kwargv
...:
In [ 7 ]: t  =  [ 1 , 2 ]
In [ 8 ]: fun( 1 , 2 , "a" , * t,y = 1 , * * { "b" : 1 , "c" : 2 })
1
( 2 'a' 1 2 )
{ 'y' 1 'c' 2 'b' 1 }


7.函数的递归调用(函数调用本身)

条件:

1)必须有最后的默认结果,即if n == 0

2)递归参数必须向默认结果收敛,即factorial(n-1)

练习:阶乘,n乘以f(n-1)

1
2
3
4
5
6
7
#!/usr/bin/env python
def  factorial(n):
     if  = =  0 :
         return  1
     else :
         return  *  factorial(n - 1 )
print  factorial( 5 )


结果:

120


练习2:累加,n加f(n-1)

1
2
3
4
5
6
7
#!/usr/bin/env python
def  factorial(n):
     if  = =  0 :
         return  0
     else :
         return  +  factorial(n - 1 )
print  factorial( 5 )


结果:

15











本文转自 huangzp168 51CTO博客,原文链接:http://blog.51cto.com/huangzp/2046626,如需转载请自行联系原作者
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值