《笨办法学python》加分习题21——我的答案

来源:互联网 发布:手机网络运营商无服务 编辑:程序博客网 时间:2024/05/22 14:39

这是我自己学习的答案,会尽力写的比较好。还望大家能够提出我的不足和错误,谢谢!

文中例题:

def add(a, b):    print "ADDING %d + %d" % (a, b)    return a + bdef subtract(a, b):    print "SUBTRACTING %d - %d" % (a, b)    return a - bdef multiply(a, b):    print "MULTIPLYING %d * %d" % (a, b)    return a * bdef divide(a, b):    print "DIVIDING %d / %d" % (a, b)    return a / bprint "Let's do some math with just functions!"age = add(30, 5)height = subtract(78, 4)weight = multiply(90, 2)iq = divide(100, 2)print "Age: %d, Height: %d, Weight: %d, IQ: %d" % (age, height, weight, iq)# A puzzle for the extra cerdit, type it in anyway.print "Here is a puzzle."what = add(age, subtract(height,multiply(weight, divide(iq, 2))))print "That becomes: ", what, "Can you do it by hand?"

运行结果:

这里写图片描述

习题答案:

1、这里提个C语言中的左值右值。大概理解就是左值是一个地址,右值是一个数据。
2、
其实就是分解计算了原先what的运算:
原先what的运算:

what = add(age, subtract(height,multiply(weight, divide(iq, 2))))

改为:

temp1 = divide(iq, 2)temp2 = multiply(weight, temp1)temp3 = subtract(height, temp2)what = add(age, temp3)

4、

def add(a, b):    print "ADDING %d + %d" % (a, b)    return a + bdef subtract(a, b):    print "SUBTRACTING %d - %d" % (a, b)    return a - bdef multiply(a, b):    print "MULTIPLYING %d * %d" % (a, b)    return a * bdef divide(a, b):    print "DIVIDING %d / %d" % (a, b)    return a / bage = 1height = 1weight = 4iq = 4what = 100temp3 = subtract(what, age)temp2 = add(temp3, height)temp1 = divide(temp2, weight)temp = multiply(temp1, iq)print "answer is %d " % temp
原创粉丝点击