python程序设计基础4:python函数设计和使用

这一节我们将学习python函数的使用,包括一些变量以及参数的设定还有如何写出可以复用的代码。函数就是一段具有特定功能的、被封装的、可重用的程序。主要还是以例进行学习。

1、输入圆形的半径,得出相应的圆的面积。

少量的几个半径,其实你可以将代码重复的赋值几次代码就行了。但是为了代码的简洁,你可以写一个简单的循环。

代码:

radius=input(‘please input radiuses in list‘)
for r in radius:
    print‘the area of the circle with the radius of %f is:‘%r,3.14*r*r

结果:

please input radiuses in list[2,3,4]
the area of the circle with the radius of 2.000000 is: 12.56
the area of the circle with the radius of 3.000000 is: 28.26
the area of the circle with the radius of 4.000000 is: 50.24

2、比较两个数的大小,若是a小于b,则交换两个的位置。

x,y=input(‘please input two number: ‘)


def swap(a,b):
    if a<b:
        a,b=b,a
        print a,b
swap(x,y)
print x,y


结果:

please input two number: 2,3
3 2
2 3

可以看出来,没有得到我们想要的结果。在C语言中使用指针的方式来解决这个问题。

所以,我们使用全局变量:

def func():
    global a,b
    a,b=input(‘please input 2numbers:‘)
    if a<b:
        a,b=b,a
    print ‘a=‘,a,‘b=‘,b


func()

结果:

please input 2numbers:2,3
a= 3 b= 2

3、python中的‘*’和‘**‘可以处理输入参数的个数不确定的情况,’**‘主要用于字典的引用。区别于C语言中的指针引用。

例子:定义一个函数,如下:

def func(a,b,c=1,*p,**pa):
    print a,b,c
    print p
    print pa


func(1,2,3,4,5,6,7,x=3,y=5,z=‘iker‘)

结果:

1 2 3
(4, 5, 6, 7)
{‘y‘: 5, ‘x‘: 3, ‘z‘: ‘iker‘}


4、输入一个年份,判断是否为闰年。

代码:

def runnian(a):
    if a%400==0 or (a%4==0 and a%100!=0):
        print‘%d is a run year!‘%a
    else:
        print‘%d is not a run year!‘%a


a=input(‘please input a year number:‘)
runnian(a)


结果:

please input a year number:2013
2013 is not a run year!



python程序设计基础4:python函数设计和使用,布布扣,bubuko.com

python程序设计基础4:python函数设计和使用

上一篇:前端学习笔记(4) - JavaScript宏观与微观任务


下一篇:java 练习笔记