python 笔记 return的使用 《笨办法学Python》习题21 ——12.28

习题 21:  函数可以返回东西

ex21.py

#-*-coding:utf-8-*-
#这一章在我看来就是学会使用函数进行运算并返回一个值
#其运算方式是内置的,+-*/
#在我看来主要目的是定义一个运算的过程并返回数值
 
#例如这里,定义一个函数,虽然叫add加法,但是我们也可以命名其为subtract
#重要的是return值的方式
#当然打印也很重要,毕竟用于交互的话还是需要提示的
#%d用过很多次了,有符号整数
def add(a, b):
	print "ADDING %d + %d"%(a, b)
	return a + b
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(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 credit, 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?"

运行结果:



自我练习

ex21_1.py

#-*-coding:utf-8-*-
'''
 
其实这一章,我理解起来完全没什么问题。但是让我自己想我很难想到这些运用方法。
我想,最难也最重要的是imagination,想象力
我感觉python的函数,其实就和我的世界有异曲同工之妙。
我们定义一个函数和一些变量,组成了一部分零件。
然后利用这些“零件”进行嵌套和结合,最终搭成摩托大楼。
 
'''
 
def add(a,b,c):
	print "ADDING %d +%d +%d" % (a, b, c)
	return a + b + c
#我认为return才最重要,他定义了函数的运算过程或者说运行方式,并返回结果
 
 
 
def subtract(a,b,c):
	print "ADDING %d +%d +%d" % (a, b, c)
	return a + b + c
def strange(a,b,c):
	print "ADDING %d +%d +%d" % (a, b, c)
	return "Yes,it could print some text,even if it is independent of the variable"
 
a = add(4,3,2)
 
b = subtract(4,3,2)
 
c = strange(1,2,3)
 
 
print "%d"% a
 
print "%d, %d"% (a,b)
 
print "%s"% c
 
 
 
print "In fact,add and subtract are same!"
 
ADD_3_2_2 = add(3,2,2)
 
print "3+2+2=%d" %ADD_3_2_2

运行结果:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值