《编程小白的第一本Python入门书》学习记录(1-7章)

重新再回头来看看python,原来都是用的Pyhon2,好多都忘了,更新下知识,今年的第一本书,简单记录下。
下载地址:https://pan.baidu.com/s/19qpUFZlegEWd3Zlhc-HMSQ 提取码: evnu


P27-print()函数

  • print()函数用于打印输出,最常见的一个函数。
    注意:print 在 Python3.x 是一个函数,但在 Python2.x 版本不是一个函数,只是一个关键字,所以下面的语法只对python3有,python2中会报错。
  • 语法 print(*objects, sep=' ', end='\n', file=sys.stdout)
  • 参数
    • objects -- 复数,表示可以一次输出多个对象。输出多个对象时,需要用 , 分隔。
    • sep -- 用来间隔多个对象,默认值是一个空格。
    • end -- 用来设定以什么结尾。默认值是换行符 \n,我们可以换成其他字符串。
    • file -- 要写入的文件对象。
  • 返回值,无
  • 实例
    print("cisco","huawei")    #默认多字符串的间隔符为空格
    print("cisco","huawei",sep = "&" )     #可以加上sep修改间隔符
    print("cisco","huawei",sep="*",end="*********")  #设置结尾符
    f = open("d:/tmp/1.txt","w+")   #写入文件前,先打开文件,并设置写属性。
    print("cisco","huawei",sep="*",file=f)
    

P45练习题-初级难度

def calc (h):
    kg = h/1000
    return  '其实重量为' +  str(kg) + 'kg'
a = int(input("请输入重量,单位为g" +  "\n"))
print ( calc(a))


P45-中级难度-直角边

import math
def shuxue(a,b):
    c = a**2 + b**2
    d = math.sqrt(c)
    return "The right triangle third side's length is " + str(d)
a = int(input("输入第一个直角边" + "\n"))
b = int(input("请输入第二个直角边" + "\n"))
print(shuxue(a,b))

P52-在tmp目录创建文件

def create(name,msg):
    path = "d:/tmp/"
    full_path = path + name + ".txt"
    file = open(full_path,"w")
    file.write(msg)
    file.close()
    print("done")
create("test","hello world")
create("test","ni mei")

P63-密码输错3遍就禁止再次输入密码

def login():
    password = ['!@#', '123']
    retries = 3
    while retries > 0 :
        pwd = input('请输入密码: ' )
        if pwd == password[-1]:
            print('恭喜你,成功登陆!')
            break
        elif pwd == password[0]:
            newpwd = input('请输入新的密码: ')
            password.append(newpwd)
            del password[-2]
            print('你的密码已更改为'+password[-1])
            break
        else:
            print('密码错误,请重新输入!')
            retries = retries - 1
    else:
        print('密码错误超过3次,账户琐定10分钟')
login()

P70-设置函数在tmp目录创建从1到10的txt文本

def create():
    path = 'd:/tmp/'
    for i in range(1,11):
        full_path = path + str(i) + '.txt'
        f = open(full_path,'w')
        f.close()
create()

P70-复利

def invest(amount,rate=5,time=8):
    for i in range(1,time + 1):
        total = float(amount) * ((1 + float(rate) / 100) ** float(i))
        print('year '+ str(i) + ': $'+ str(total))
a = input('principal amount: ')
invest(a)

P70-打印1-100的偶数

def invest(amount,rate=5,time=8):
    for i in range(1,time + 1):
        total = float(amount) * ((1 + float(rate) / 100) ** float(i))
        print('year '+ str(i) + ': $'+ str(total))
a = input('principal amount: ')
invest(a)

P72-综合练习-摇骰子

import random
while True:
    BBB = input('你来猜猜大小:')
    a = random.randrange(1,7)
    b = random.randrange(1,7)
    c = random.randrange(1,7)
    s = [a,b,c]
    if 11 <= sum(s) <= 18:
        print('你的点数为大,',end=' ')
        if BBB == '大':
            print('你赢了')
        elif BBB == '小':
            print('你输了')
        else:
            print('但是你输入错误了,请重新输入')
    elif BBB == 'exit':
        break
    else:
        print('你的点数为小,',end=' ')
        if BBB == '大':
            print('你输了了')
        elif BBB == '小':
            print('你赢了')
        else:
            print('但是你输入错误了,请重新输入')

P76-摇骰子赌博

import random
#摇骰子系统
def roll_points(times=3,points='none'):
    if points is 'none':
        points = []
    while times > 0 :
        point = random.randrange(1,7)
        points.append(point)
        times = times - 1
    return  points
#比大小系统
def roll_result(total):
    if  total > 10:
        return 'Big'
    elif total < 11:
        return 'Small'
#游戏系统
def start_game(start):
    while start > 0:
        print('<<<<<<<<<    GAME START    >>>>>>>>>')
        your_choice = input('"Big" or "Small":')
        while your_choice  in ['Big', 'Small']:
            money = input('How much you wanna bet:')
            if not money.isdigit() :
                break
            else:
                if int(money) > start:
                    break
                else:
                    print('<<<<<<<<<    Roll    >>>>>>>>>')
                    points = roll_points()
                    print('The points is {},'.format(points),end=' ')
                    if roll_result(sum(points)) == your_choice:
                        result = 'You Win'
                        totals = start + int(money)
                    else:
                        result = 'You Lose'
                        totals = start - int(money)
                    print(result)
                    start = totals
                    break
        if your_choice == 'bye':
            break
        else:
            print('You have only {}, play again with "Big"/"Small" or exit with "bye"'.format(start))
    else:
        print('GAME OVER')
start_game(1000)

P77-检查手机号

CN_mobile = [134,135,136,137,138,139,150,151,152,157,158,159,182,183,184,187,188,147,178,1705]
CN_union = [130,131,132,155,156,185,186,145,176,1709]
CN_telecom = [133,153,180,181,189,177,1700]
def phone():
    number = input('Enter Your number:')
    if not number.isdigit():
        print('please enter right number')
        phone()
    else:
        num1 = int(number[0:3])
        num2 = int(number[0:4])
        if len(number) != 11:
            print('Invaild length,your name should be in 11 digits')
            phone()
        elif num1 in CN_telecom or num2 in CN_telecom:
            print('Operator:CN_telecom')
            print('we should send verification code to your phone:{}'.format(number))
        elif num1 in CN_union or num2 in CN_union:
            print('Operator:CN_union')
            print('we should send verification code to your phone:{}'.format(number))
        elif num1 in CN_mobile or num2 in CN_mobile:
            print('Operator:CN_moblie')
            print('we should send verification code to your phone:{}'.format(number))
        else:
            print('No such a operator')
            phone()
phone()

P89-zip()函数

  • zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。
  • 如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用 * 号操作符,可以将元组解压为列表。
    zip 方法在 Python 2 和 Python 3 中的不同:在 Python 3.x 中为了减少内存,zip() 返回的是一个对象。如需展示列表,需手动 list() 转换。
  • zip 语法:zip([iterable, ...])
  • 参数说明:iterabl -- 一个或多个迭代器;
  • 返回值,返回元组列表。
  • 实例
    num = [1,2,3,4,5,6]
    str = ['1st','2nd','3th','4th','5th','6th','7th']
    test = {i:j for i,j in zip(num,str)}
    print(test)
    {1: '1st', 2: '2nd', 3: '3th', 4: '4th', 5: '5th', 6: '6th'}
    

P90-推导式

  • 这东西有些地方也叫列表解析式,其实是一样的东西。下面一个py测试普通写法和推导式的区别。
    import time
    a = []
    t0 = time.perf_counter()
    for i in range(1,20000000):
        a.append(i)
    print(time.perf_counter() - t0,'seconds process time')
    t1 = time.perf_counter()
    b = [i for i in range(1,20000000)]
    print(time.perf_counter() - t1,'seconds process time')
    运行后,区别还是有的,虽然循环的次数确实比较多,在书上比较老的版本中20000次的差距都比较明显,确实py也在进步,并且和书上的例子用的函数也不一样,用的并不是上面的time.perf_counter()而是用time.clock(),但是这个函数在3.8就会被移除的,当前版本是3.7,所以我就换了新的函数。
    3.2525775990000003 seconds process time
    1.4710991059999996 seconds process time
    字典推导式也差不多,如下:
    g = {i:j for i,j in zip(range(1,6),'abcde')}

P92-词频统计

  • split()函数,通过指定分隔符对字符串进行切片,如果参数 num 有指定值,则分隔 num+1 个子字符串。语法str.split(str="",num=string.count(str))[n] str:表示为分隔符,默认为空格,但是不能为空('')。若字符串中没有分隔符,则把整个字符串作为列表的一个元素。num:表示分割次数,如果存在参数num,则仅分隔成 num+1 个子字符串,并且每一个子字符串可以赋给新的变量。[n]:表示选取第n个分片。
    str = 'www.cisco.com'
    a = str.split('.')
    b = str.split('.')[1]
    c = str.split('.',1)
    print(a)
    print(b)
    print(c)
    输出结果
    ['www', 'cisco', 'com']
    cisco
    ['www', 'cisco.com']
    
  • strip() 方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。注意:该方法只能删除开头或是结尾的字符,不能删除中间部分的字符。其中string.punctuation代表着所有的标点符号。
    import string
    list = ['.baynk5211.vicp.cc',  '_baynk5211.vicp.cc']
    list2 = [a.strip('.') for a in list]
    list3 = [a.strip(string.punctuation) for a in list]
    print(list2,list3,sep='\n')
    运行结果
    ['baynk5211.vicp.cc', '_baynk5211.vicp.cc']
    ['baynk5211.vicp.cc', 'baynk5211.vicp.cc']
    
  • sorted()排序方法,
    num = [ 1,5,7,2,9.11,8]
    str = ['z','d','a','f','cisco','huawei']
    print(sorted(num))
    print(sorted(str,reverse=True))  #默认情况下reverse=False
    list = [('c',4),('a',3),('d',1),('b',2)]
    print(sorted(list,key=lambda x:x[0]))
    print(sorted(list,key=lambda x:x[1]))
    运行结果
    [1, 2, 5, 7, 8, 9.11]
    ['z', 'huawei', 'f', 'd', 'cisco', 'a']
    [('a', 3), ('b', 2), ('c', 4), ('d', 1)]
    [('d', 1), ('b', 2), ('a', 3), ('c', 4)]
  • 最终环境的py。只能用来统计英文文本词频。
    import string
    def counter(path):
        with open(path,'r') as txt:
            words = [a.strip(string.punctuation).lower() for a in txt.read().split()]
            list1 = [a for a in words]
            list2 = [words.count(a) for a in words]
            dic = {x:y for x,y in zip(list1,list2)}
            result1= sorted(dic.items(),key=lambda x:x[1],reverse=True)
            result2= sorted(dic.items(),key=lambda x:x[1])
            m = 0
            n = 0
            max = [ ]
            min = [ ]
            while True:
                if result1[m][1] > result1[m+1][1]:
                    max.append(result1[m][0])
                    print('文章中出现次数最多的是{},一共出现了{}次。'.format(sorted(max), result1[m][1]))
                    break
                else:
                    max.append(result1[m][0])
                    m = m + 1
            while True:
                if result2[n][1] < result2[n+1][1]:
                    min.append(result2[n][0])
                    print('文章中出现次数最少的是{},一共出现了{}次。'.format(sorted(min),result2[n][1]))
                    break
                else:
                    min.append(result2[n][0])
                    n = n + 1
    counter( 'd:/tmp/Walden.txt')

P111-类属性和实例属性

  • #类属性如果被重新赋值,是否会影响到类属性的引用?
    class TestA:
        attr = 1
    obj_a = TestA()
    TestA.attr = 42
    print(obj_a.attr)
    #会的!!!
    #实例属性如果被重新赋值,是否会影响到类属性的引用?
    class TestB:
        attr = 1
    obj_a = TestB()
    obj_b = TestB()
    obj_a.attr = 42
    print(obj_b.attr)
    #不会
    #类属性实例属性具有相同的名称,那么.后面引用的将会是什么?
    class TestC:
        attr = 1
        def __init__(self):
            self.attr = 42
    obj_a = TestC()
    print(obj_a.attr)
    print(TestC.__dict__)
    print(obj_a.__dict__)
    #是实例属性
    
  • Python中属性的引用机制是自外而内的,当你创建了一个实例以后,准备开始引用属性,这时候编译器会先搜索该实例是否拥有该属性,如果有,则引用;如果没有,将搜索这个实例所属的类是否有这个属性,如果有,则引用,没有那就只能报错了。

P115-填充用户假数据

  • 感觉书上在这里写的太随便了,写个子类一点意义都没体现出来 ,不过这个生成器(yiled)还是很好玩的,于是改成自己能够理解的了,相比之下,感觉还是JAVA学习过程中的理解比较清晰。。。
  • 在做文件处理时,碰到了两个问题,第一个是文件编码的问题,虽然文件确实是UTF_8的,但是仍然会报GBK无法识别,并且已经去pycharm中改过编码了,只能在读取文件时加上编码方式;
  • 第二个问题就是,readlines()敲成了readline(),调试了半天才发现不对。。。找了下区别:
    1. read 读取整个文件
    2. readline 读取下一行
    3. readlines 读取整个文件到一个迭代器以供我们遍历(读取到一个list中,以供使用,比较方便)
    txt = 'd:/tmp/test.txt'
    with open(txt,'r') as f:
        print(f.read())
        print('*'*100)
    with open(txt, 'r') as f:
        print(f.readline())
        print(f.readline(2)) #这里尝试一下指定字符
        print(f.readline())
        print('*'*100)
    with open(txt, 'r') as f:
        print(f.readlines())
    
    运行结果为
  • 最终代码:
    import random
    fn_path = 'D:/Tmp/f_name.txt'
    ln_path = 'D:/Tmp/l_name.txt'
    fn = []
    ln = []
    with open(fn_path,'r',encoding='utf_8') as f:
        for line in f.readlines():
            fn.append(line.strip('\n'))
        fn = list(set(fn))
    with open(ln_path,'r',encoding='utf_8') as f:
        for line in f.readlines():
            ln.append(line.strip('\n'))
        ln = list(set(ln))
    class FakeUser:
        def fake_name(self,amount=1):
            while amount > 0:
                full_name = random.choice(fn)+random.choice(ln)
                yield full_name
                amount -= 1
        def fake_gender(self,amount=1):
            while amount > 0:
                gender = random.choice(['男','女'])
                yield gender
                amount -= 1
    class SnsUser(FakeUser):
        def fake_age(self,amount=1):
            while amount > 0:
                age = random.randrange(10,60)
                yield age
                amount -= 1
    def information(num):
        name_list = []
        gender_list = []
        age_list = []
        user_a = SnsUser()
        #这里SnsUser里面没有fake_name方法,但是也可以直接调用,这就是调用了父类函数
        for name in user_a.fake_name(num):
            name_list.append(name)
        for gender in user_a.fake_gender(num):
            gender_list.append(gender)
        for age in user_a.fake_age(num):
            age_list.append(age)
        n = 0
        while n < num :
            print(name_list[n],gender_list[n],age_list[n])
            n += 1
    information(10)
  • 运行结果
    焦萃 女 14
    陈珠 女 27
    秦森 女 21
    贾司 男 22
    字朗 女 56
    翁骄 女 42
    运珊 男 23
    出惕 女 50
    封麟 女 10
    鹿璨 女 41

结束语

第八章则是讲解第三方库,这里就不记录了,确实非常适合新手看,很简单易懂,如果有时间的话,大概2天左右就看完了,比较推荐,但是由于知识点很粗糙,还需要再去看一些知识点比较系统的书籍,下本书见。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值