首页 > 代码库 > 函数的声明

函数的声明

导入时间模块

In [2]: import time

 

In [3]: time.ctime(time.time())

Out[3]: ‘Wed Apr  5 15:16:26 2017‘

 

In [4]: time.time()

Out[4]: 1491376668.733707

 

In [5]: time.ctime(time.time())        //转换时间格式

Out[5]: ‘Wed Apr  5 15:18:07 2017‘

声明函数

In [6]: def myprint():                    //声明myprint()函数

   ...:     print "hello world"

   ...:     

 

In [7]: myprint()                //调用myprint()函数

hello world

 

In [8]: print myprint()

hello world

None

 

 

函数

 

In [1]: def f():    //定义函数f()

   ...:     a= 1

   ...:     b=3

   ...:     c=2

   ...:     return a,b,c  //返回a,b,c的值,省略了括号

   ...:

 

In [2]: f()

Out[2]: (1, 3, 2)

 

In [3]: a,b,c =f()       //将f()函数的值依次赋给a,b,c

 

In [4]: print a,b,c

1 3 2

 

In [5]: def abs(x):         //定义绝对值函数

   ...:     if x>=0:         

   ...:         return x       //当x为正数时,返回x的值

   ...:     else:

   ...:         return -x       //否则返回-x的值

   ...:     

 

In [6]: abs(2)

Out[6]: 2

 

In [7]: abs(-5)

Out[7]: 5

 

In [8]: def abs(x):

   ...:     if x>=0:

   ...:         print x

   ...:     else:

   ...:         print -x

   ...:         

 

In [9]: abs(-5)

5

 

In [10]: print abs(-13)

13                                //

None                               //

In [12]: def power(x):              //定义3次方函数

   ....:     return x*x*x

   ....:

 

In [13]: power(2)               

   ....:     return x**3           

   ....:                        #In [20]: def power(x):     

Out[13]: 8                      #....:     return x**3

                                #....:

In [14]: power(3)               #In [21]: power(3)

Out[14]: 27                     #Out[21]: 27

 

--------------------

 

 

In [15]: def abs(x):          //声明绝对值函数abs()                

   ....:     return x if x>=0 else -x  //x>=0时返回x,否则返回-x

   ....:

 

In [16]: abs(-5)

Out[16]: 5

 

In [17]: abs(5)

Out[17]: 5

 

In [22]: def info(name,age=18,address="xi‘an"):

   ....:     print name,age,address

   ....:     

 

In [23]: info("hzy")         //传递参数

hzy 18 xi‘an

 

In [24]: info ("hzy",20)

hzy 20 xi‘an

 

In [16]: def add(*args):         

   ....:     sum =0

   ....:     for i in args:

   ....:         sum =sum +i

   ....:     return sum

   ....:

 

In [17]: add(1,2,3,4)

Out[17]: 10


本文出自 “12444546” 博客,谢绝转载!

函数的声明