【Python学习21】Python中函数的用法,使用函数进行简单的数学运算
# --coding: utf-8 -- # 定义4个简单的函数,分别是加、减、乘、除,定义函数要使用def这个关键字def add(a,b): # 使用def关键字定义了add这个函数,给add函数指定两个参数a和b
print "ADDing %d + %d" %(a,b) # 打印出函数中的两个变量
return a + b #利用return语句来返回函数的结果
# 以下3个函数的说明同add函数,就不赘述了
def subtract(a, b):
print "SUBTRACTING %d - %d" % (a, b)
return a - b
def multiply(a, b):
print "MULTIPLYING %d * %d" % (a, b)
return a * b
def divide(a, b):
print "DIVIDING %d / %d" % (a, b)
return a / b
print "Let's do some math with just functions!"
age = add(300, 5) #使用add函数给age变量赋值,所得的值就是add函数中两个变量通过函数return后的结果
height = subtract(78, 4)
weight = multiply(90, 2)
iq = divide(4, 2)
print "Age: %d,> # A puzzle for the extra credit, type it in anyway.
print "Here is a puzzle."
'''
下面这个公式稍稍有点复杂,应该从内往外开始读
解释一下这个公式:
1. 上面分别通过函数计算得到了age、height、weight、iq的值
2. 然后把这些值套用到函数中得到下面这样一个数学表达式
3. what = 35 + 74 - 180 * 50 / 2
4. 得到的结果就是-4391
'''
what = add(age, subtract(height, multiply(weight, divide(iq, 2))))
print "That becomes: ", what, "Can you do it by hand?"
页:
[1]