python核心编程(第二版)

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/udonsu/article/details/80744866

///  python是我第一门系统学习的编程语言,下列习题的答案也非官方标准答案,只是我个人的解答。作为一只菜鸡水平有限,如有错漏之处还请批评指正。///

Q: “==”和“is”和isinstance()的区别与联系?

A:(参考了别人的回答)" is" 是用来比较 a 和 b 是不是指向同一个内存单元,而"=="是用来比较 a 和 b指向的内存单元中的值是不是相等。不同对象的id不同,因而id的值也不同,但可以通过重写__eq__()方法进行运算符重载。(1)

判断变量类型时,推荐使用isinstance方法。(2)

(1) https://blog.csdn.net/kobebryantlin0/article/details/73391584

(2) https://segmentfault.com/q/1010000000127305


4-9 实践

a = 10
b = 10
c = 100
d = 100
e = 10.0
f = 10.0

print a is b   #True
print c is d   #True
print e is f   #False

咦说好的创建不同的对象呢,怎么出了叛徒???这其实是因为在python的垃圾回收机制中,存在“小整数池”的概念,为了优化速度,提前把这些数据存放在小整数对象池中,使用的时候不会重新分配新的内存空间。


5-3 写一段脚本,根据输入的成绩判断评分等级(A-F)

输入校验部分:也是写完才发现原来负数的isdigit返回False,原因是字符串带有的'-'字符不是数字……

关于如何让负数也被判断成整数请参考这篇博文:

https://www.cnblogs.com/liwenzhou/p/5125807.html

def transcore(score):
    if not score.isdigit(): #判断输入是否为数字
        return "a number please..."
    else:
        score_num = float(score) #将raw_input捕获的字符串转换为浮点数以供比较
        if 0 <= score_num < 60:
            return "F"
        elif 60 <= score_num < 70:
            return "D"
        elif 70 <= score_num < 80:
            return "C"
        elif 80 <= score_num < 90:
            return "B"
        elif 90 <= score_num <= 100:
            return "A"
        else:
            return "invalid score"

while True:
    ur_score = raw_input('Enter the score...')
    print transcore(ur_score)
            


5-4 判断所给年份是否为闰年,使用以下公式:可以被4整除但不能被100整除,或者可以被400整除。

def isleapyear(year):
    if not year.isdigit():
        return "invalid input..."
    else:
        year_num = int(year)
        if (year_num % 4 == 0 and year_num % 100 != 0) or\
           year_num % 400 == 0:
            return "yes"
        else:
            return "no"

while True:
    year = raw_input('Which year?...')
    print isleapyear(year)
    

5-5 美分换算

while True:
    money = int(input('HOW MANY CENTS? input a integer between 0 and 100...'))
    if money <= 0 or money >= 100: print "invalid input"
    else:
        answer = []
        money_left = money
        for each in (25, 10, 5, 1):
            a = money_left / each
            answer.append(a)
            money_left -= a * each

    print "\n25 cents * %d, 10 cents * %d, 5 cents * %d, 1 cents * %d \n"\
          % (answer[0], answer[1], answer[2], answer[3])

5-6 表达式计算器程序

# -*- coding: utf-8 -*-
from operator import * #operator模块提供了操作符的函数接口

operator = {"+":add, "-":sub, "*":mul, "/":floordiv, "%":mod, "**":pow} 

def isnum(char):  #判断是否为数字并转换为相应的类型
    if (char.lstrip('-')).isdigit(): return int(char) #整数
    else:
        try:
            trans = float(char) #浮点数
            return trans
        except ValueError: #不是数字
            return False
        

def splitexpr(char): #分割字符串
    for each in operator.keys():
        splited = char.split(each)
        if len(splited) == 2 and (isnum(splited[0]) and isnum(splited[1])): #成功匹配操作符,且左右均为数字
            answer = (isnum(splited[0]), each, isnum(splited[1])) 
            return answer 
            break
    return False          

def calc(answer): #计算与输出
    if answer == False: print "try again..."
    else:
        print answer[0], answer[1], answer[2], "=", operator[answer[1]](answer[0], answer[2])
        

while True:
    expression = raw_input('please enter an expression...')
    calc(splitexpr(expression))

5-10 摄氏到华氏的转换(利用__future__除法)

from __future__ import division

def change(f):
    c = (float(f) - 32.0) * (5.0 / 9.0)
    return c

f = input("摄氏温度?...")
print "华氏温度为 %.2f" %change(f)

5-17随机数

import random

N1 = random.randint(2,100)
list = [random.randint(0,2**31) for i in range(N1)]
print list
print list.sort()

展开阅读全文

没有更多推荐了,返回首页