第五章开头就写了两个字:数字
然后我当时就愣住了:数字?讲什么?
然后想了想,这本书果真全面啊。要是其他的书籍,早就不讲这东西的。
还是看看吧。
5.1 数字类型
数字提供了标量存储和直接访问。它是不可更改类型,也就是说变更数字的值会生成新的对象。
>>> num1 = num2 = 10.1>>> id(num1)36987552>>> id(num2)36987552这里最好还是解释一下:10.1创建了一个对象,然后num1,num2都指向这个对象。所以他们的id是一样的。
>>> num1 = 10.1>>> num2 = 10.1>>> id(num1)36987728>>> id(num2)51770800而这里的num1,num2却属于不同的对象,看其id就知道了。
如何更新数字对象
通过给数字对象(重新)赋值,我们可以“更新”一个数值对象。之所以要加上引号,是因为实际上我们并没有更新对象的原始数值。这是因为数值对象是不可改变对象。python的对象模型与常规对象模型有些不同。我们所认为的更新实际上是生成一个新的数值对象,并得到它的引用。
如何删除数字对象
按照python的法则,你无法真正删除一个数值对象,你仅仅是不再使用它而已。如果你实际上想删除一个数值对象的引用,使用del语句。删除对象的引用之后,你就不能再使用这个引用(变量名),除非你给它赋一个新值。如果试图使用一个已经被删除的对象引用,会引发NameError异常。
5.4.1 复数的内建属性
>>> aComplex = -9 + 8j>>> aComplex(-9+8j)>>> aComplex.real-9.0>>> aComplex.imag8.0>>> aComplex.conjugate()(-9-8j)对于一大堆的优先级,推荐使用括号,为人为己。
一些内建函数:
abs(num) 返回num的绝对值
coerce(num1, num2) 将num1和num2转换为同一类型,然后以一个元祖的形式返回
divmod(num1, num2) 除法-取余运算的结合。返回一个元祖(num1 / num2, num1 % num2)
pow(num1, num2, mod = 1) 取num1的num2次方,如果提供Mod参数,则计算结果再对mod进行取余运算
round(flt, ndig = 0) 接受一个浮点数flt并对其四舍五入,保存ndig位小数。若不提供ndig参数,则默认小数点后0位
5.6.3 仅用于整数的函数
进制转换函数
oct(),hex()两个函数:返回字符串表示8进制和16进制。
>>> hex(255)'0xff'>>> oct(255)'0377'ASCII转换函数 函数chr()接受一个单字节整数值,返回一个字符串,其值为对应的字符。函数ord()则相反,它接受一个字符,返回其对应的整数值。
>>> chr(97)'a'>>> chr(65)'A'>>> ord('a')97>>> ord('A')65编程风格建议:最好不要在函数内使用print语句输出信息,而是通过return语句返回必要的值。
PS:这章我快看崩溃了
那,开始做习题吧。原本头晕晕的准备去写邮件的,想了想,善始善终嘛。
做习题的时候,想到一点:很多事情,看似简单,实际上确实简单。但是我们还是要把简单的事给做好。
生活中心情通常都是因为琐碎的事而烦躁。
工作需要沉淀。既然没大师在身边指导,那么就靠自己从简单的事学起,慢慢成长
--------------有感于《程序员修炼之道--从小工到专家》
5-2 运算符
(a) 写一个函数,计算并返回两个数的乘积 (b) 写一段代码调用这个函数,并显示它的结果"计算两个数的乘积,并显示其结果"def add(num1, num2): return num1 * num2if __name__ == "__main__": num1 = raw_input("please enter number1:") num2 = raw_input("please enter number2:") print "the product is: %d" % (add(int(num1), int(num2)))程序输入输出:
>>> please enter number1:3please enter number2:4the product is: 12当然,这里没有进行一些额外的判断,比如输入是字符串啊。
5-3 标准类型运算符. 写一段脚本,输入一个测验成绩,根据下面的标准,输出他的评分
成绩(A-F)。 A: 90–100 B: 80–89 C: 70–79 D: 60–69 F: <60mark_value = {10:"A",9:"A",8:"B",7:"C",6:"D", 5:"F",4:"F",3:"F",2:"F",1:"F",0:"F"}while True: num1 = raw_input("please enter your mark(-1 to quit)") if num1 == "-1": break print "your mark is:%s" % mark_value[int(num1) / 10]程序输入输出:
>>> please enter your mark(-1 to quit)45your mark is:Fplease enter your mark(-1 to quit)67your mark is:Dplease enter your mark(-1 to quit)78your mark is:Cplease enter your mark(-1 to quit)89your mark is:Bplease enter your mark(-1 to quit)90your mark is:Aplease enter your mark(-1 to quit)100your mark is:Aplease enter your mark(-1 to quit)-1这里用到了传说中的表格驱动法,这样可以高效的处理类似于一堆if--else--if--else--if的操作。
对这种方法感兴趣的,请参考《代码大全2》,程序员入门到圣经(PS:还没开始看,就翻了几页,刚好看到表格驱动法,就将就用了。)
当然,这里异常不在目前的代码考虑范围内。
5-4 取余。判断给定年份是否是闰年。使用下面的公式:
一个闰年就是指它可以被4 整除,但不能被100 整除, 或者它既可以被4 又可以被100 整除。比如 1992,1996 和2000 年是闰年,但1967 和1900 则不是闰年。下一个是闰年的整世纪是 2400 年。"判断闰年"def Leapyear(year): return bool((not(year % 4)) and (year % 100)) or ((not(year % 4)) and (not(year % 100)))if __name__ == "__main__": year = raw_input("please enter the year:") if Leapyear(int(year)): print "leap year" else: print "not leap year"5-5 取余。取一个任意小于1 美元的金额,然后计算可以换成最少多少枚硬币。硬币有1美分,5 美分,10 美分,25 美分四种。1 美元等于100 美分。举例来说,0.76 美元换算结果应该是 3 枚25 美分,1 枚1 美分。类似76 枚1 美分,2 枚25 美分+2 枚10 美分+1 枚5 美分+1枚1 美分这样的结果都是不符合要求的。 我想起来LISP里面那个变态可怕的美元题目,神奇的递归和迭代在LISP里面呼风唤雨。我们来看看这道题该怎么解。
"""取一个任意小于1美元的金额,然后计算可以换成最少多少枚硬币。硬币有1美分,5美分,10美分,25美分"""def NumOfdollar(money): num = [25,10,5,1] count = 0 for i in num: result = divmod(money, i) count += result[0] money = result[1] return countif __name__ == "__main__": while True: money = raw_input("please enter the money(0 to quit):") if money == "0": break else: print "the count is: %d" % NumOfdollar(int(money))这里绝妙的用到了divmod这个函数。
程序输入输出:
>>> please enter the money(0 to quit):76the count is: 4please enter the money(0 to quit):89the count is: 8please enter the money(0 to quit):45the count is: 3please enter the money(0 to quit):34the count is: 6please enter the money(0 to quit):0
5-6 算术。写一个计算器程序 你的代码可以接受这样的表达式,两个操作数加一个运算符:N1 运算符 N2. 其中 N1 和 N2 为整数或浮点数,运算符可以是+, -, *, /, %, ** 分别表示加法,减法, 乘法, 整数除,取余和幂运算。计算这个表达式的结果,然后显示出来。提示:可以使用字符串方法 split(),但不可以使用内建函数 eval().
"""计算器程序,模仿内建函数eval()"""def new_eval(strEval): num = strEval.split(" ") if num[1] == "+": return int(num[0]) + int(num[2]) elif num[1] == "-": return int(num[0]) - int(num[2]) elif num[1] == "*": return int(num[0]) * int(num[2]) elif num[1] == "/": return int(num[0]) / int(num[2]) elif num[1] == "%": return int(num[0]) % int(num[2]) elif num[1] == "**": return int(num[0]) ** int(num[2]) else: return "error operator"if __name__ == "__main__": while True: strEval = raw_input("please enter the eval(q to quit):") if strEval.lower() == "q": break print "the result is : %d" % (new_eval(strEval))程序输入输出:
>>> please enter the eval(q to quit):2 * 3the result is : 6please enter the eval(q to quit):2 ** 3the result is : 8please enter the eval(q to quit):3 - 2the result is : 1please enter the eval(q to quit):q5-10 转换。写一对函数来进行华氏度到摄氏度的转换。转换公式为C = (F - 32) * (5 / 9)应该在这个练习中使用真正的除法, 否则你会得到不正确的结果。
"""华氏度到摄氏度的转换"""def new_tran(strTemp): return ((int(strTemp) * 1.0 - 32) * (5.0 / 9.0))if __name__ == "__main__": strTemp = raw_input("please enter the temperature:") print "the result is:%f" % new_tran(strTemp)程序输入输出:
>>> please enter the temperature:56the result is:13.3333335-11 取余。 (a) 使用循环和算术运算,求出 0-20 之间的所有偶数 (b) 同上,不过这次输出所有的奇数 (c) 综合 (a) 和 (b), 请问辨别奇数和偶数的最简单的方法是什么? (d) 使用(c)的成果,写一个函数,检测一个整数能否被另一个整数整除。 先要求用户输 入两个数,然后你的函数判断两者是否有整除关系,根据判断结果分别返回 True 和 False;
num1 = []num2 = []for i in range(21): if i % 2 == 0: num1.append(i) else: num2.append(i)print num1print num2
def fun1(num1, num2): num = [] num = divmod(num1, num2) return (num[0] != 0) and (num[1] == 0)if __name__ == "__main__": while True: num1 = raw_input("please enter number1:(q to quit)") num2 = raw_input("please enter number2:(q to quit)") if (num1.lower() == "q") or (num2.lower() == "q"): break print fun1(int(num1), int(num2))程序输入输出:
>>> please enter number1:(q to quit)2please enter number2:(q to quit)3Falseplease enter number1:(q to quit)3please enter number2:(q to quit)2Falseplease enter number1:(q to quit)4please enter number2:(q to quit)2Trueplease enter number1:(q to quit)2please enter number2:(q to quit)4Falseplease enter number1:(q to quit)qplease enter number2:(q to quit)q5-13 转换。写一个函数把由小时和分钟表示的时间转换为只用分钟表示的时间。
"""将小时:分钟形式直接表示为分钟格式"""def Tran(strTime): num = [] num = strTime.split(":") return int(num[0]) * 60 + int(num[1])if __name__ == "__main__": while True: strTime = raw_input("please enter the time,like 12:12(q to quit):") if strTime.lower() == "q": break print "the time is:%d minutes" % (Tran(strTime))程序输入输出:
>>> please enter the time,like 12:12(q to quit):12:12the time is:732 minutesplease enter the time,like 12:12(q to quit):3:12the time is:192 minutesplease enter the time,like 12:12(q to quit):q5-14 银行利息。写一个函数,以定期存款利率为参数, 假定该账户每日计算复利,请计算并返回年回报率。
"""输入存款和日利率,返回年回报率"""def GetMoney(money, rate): for i in range(365): money *= (1.0 + rate) return moneyif __name__ == "__main__": money = raw_input("please enter your money:") rate = raw_input("please enter your rate:") print "after a year, you money will be:%f" % GetMoney(float(money), float(rate))程序输入输出:
>>> please enter your money:100please enter your rate:0.01after a year, you money will be:3778.343433我怎么总感觉怪怪的。
5–15. 最大公约数和最小公倍数。请计算两个整数的最大公约数和最小公倍数。
"""求最大公约数和最小公倍数"""def CommonDiv(num1, num2): tempNum = abs(num1 - num2) if (num1 % tempNum) == (num2 % tempNum) == 0: return tempNum else: return CommonDiv(num2, tempNum)def CommonMul(num1, num2): tempNum = CommonDiv(num1, num2) return num1 * num2 / tempNumif __name__ == "__main__": while True: num1 = raw_input("please enter the number1(q to quit):") if num1.lower() == "q": break num2 = raw_input("please enter the number2(q to quit):") if num2.lower() == "q": break print "the common div is: %d" % (CommonDiv(int(num1), int(num2))) print "the common mul is: %d" % (CommonMul(int(num1), int(num2)))程序输入输出:
>>> please enter the number1(q to quit):15please enter the number2(q to quit):9the common div is: 3the common mul is: 45please enter the number1(q to quit):21please enter the number2(q to quit):14the common div is: 7the common mul is: 42please enter the number1(q to quit):q