这一节我们将学习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