zoukankan      html  css  js  c++  java
  • 核心数据类型

    1 什么是数据?

      x=10,10是我们要存储的数据

    2 为何数据要分不同的类型

      数据是用来表示状态的,不同的状态就应该用不同的类型的数据去表示

    3 数据类型

      数字(整形,长整形,浮点型,复数)

      字符串

      字节串:在介绍字符编码时介绍字节bytes类型

      列表

      元组

      字典

      集合

    4 按照以下几个点展开数据类型的学习

    #一:基本使用
    1 用途
    
    2 定义方式
    
    3 常用操作+内置的方法
    
    #二:该类型总结
    1 存一个值or存多个值
        只能存一个值
        可以存多个值,值都可以是什么类型
    
    2 有序or无序
    
    3 可变or不可变
        !!!可变:值变,id不变。可变==不可hash
        !!!不可变:值变,id就变。不可变==可hash

    数字

    整型与浮点型

    #整型int
      作用:年纪,等级,身份证号,qq号等整型数字相关
      定义:
        age=10 #本质age=int(10)
    
    #浮点型float
      作用:薪资,身高,体重,体质参数等浮点数相关
    
        salary=3000.3 #本质salary=float(3000.3)
    
    #二进制,十进制,八进制,十六进制

    其他数字类型(了解)

    #长整形(了解)
        在python2中(python3中没有长整形的概念):      
        >>> num=2L
        >>> type(num)
        <type 'long'>
    
    #复数(了解)  
        >>> x=1-2j
        >>> x.real
        1.0
        >>> x.imag
        -2.0

    内置数学函数

    pow,abs,round,int,hex,oct,bin等

    公用模块

    math,random

    字符串

    #作用:名字,性别,国籍,地址等描述信息
    
    #定义:在单引号双引号三引号内,由一串字符组成
    name='egon'
    
    #优先掌握的操作:
    #1、按索引取值(正向取+反向取) :只能取
    #2、切片(顾头不顾尾,步长)
    #3、长度len
    #4、成员运算in和not in
    
    #5、移除空白strip
    #6、切分split
    #7、循环

     需要掌握的操作

    #1、strip,lstrip,rstrip
    #2、lower,upper
    #3、startswith,endswith
    #4、format的三种玩法
    #5、split,rsplit
    #6、join
    #7、replace
    #8、isdigit
    #strip
    name='*egon**'
    print(name.strip('*'))
    print(name.lstrip('*'))
    print(name.rstrip('*'))
    
    #lower,upper
    name='egon'
    print(name.lower())
    print(name.upper())
    
    #startswith,endswith
    name='alex_SB'
    print(name.endswith('SB'))
    print(name.startswith('alex'))
    
    #format的三种玩法
    res='{} {} {}'.format('egon',18,'male')
    res='{1} {0} {1}'.format('egon',18,'male')
    res='{name} {age} {sex}'.format(sex='male',name='egon',age=18)
    
    #split
    name='root:x:0:0::/root:/bin/bash'
    print(name.split(':')) #默认分隔符为空格
    name='C:/a/b/c/d.txt' #只想拿到顶级目录
    print(name.split('/',1))
    
    name='a|b|c'
    print(name.rsplit('|',1)) #从右开始切分
    
    #join
    tag=' '
    print(tag.join(['egon','say','hello','world'])) #可迭代对象必须都是字符串
    
    #replace
    name='alex say :i have one tesla,my name is alex'
    print(name.replace('alex','SB',1))
    
    #isdigit:可以判断bytes和unicode类型,是最常用的用于于判断字符是否为"数字"的方法
    age=input('>>: ')
    print(age.isdigit())
    
    示例
    #1、find,rfind,index,rindex,count
    #2、center,ljust,rjust,zfill
    #3、expandtabs
    #4、captalize,swapcase,title
    #5、is数字系列
    #6、is其他
    
    #find,rfind,index,rindex,count
    name='egon say hello'
    print(name.find('o',1,3)) #顾头不顾尾,找不到则返回-1不会报错,找到了则显示索引
    # print(name.index('e',2,4)) #同上,但是找不到会报错
    print(name.count('e',1,3)) #顾头不顾尾,如果不指定范围则查找所有
    
    #center,ljust,rjust,zfill
    name='egon'
    print(name.center(30,'-'))
    print(name.ljust(30,'*'))
    print(name.rjust(30,'*'))
    print(name.zfill(50)) #用0填充
    
    #expandtabs
    name='egon	hello'
    print(name)
    print(name.expandtabs(1))
    
    #captalize,swapcase,title
    print(name.capitalize()) #首字母大写
    print(name.swapcase()) #大小写翻转
    msg='egon say hi'
    print(msg.title()) #每个单词的首字母大写
    
    #is数字系列
    #在python3中
    num1=b'4' #bytes
    num2=u'4' #unicode,python3中无需加u就是unicode
    num3='四' #中文数字
    num4='Ⅳ' #罗马数字
    
    #isdigt:bytes,unicode
    print(num1.isdigit()) #True
    print(num2.isdigit()) #True
    print(num3.isdigit()) #False
    print(num4.isdigit()) #False
    
    #isdecimal:uncicode
    #bytes类型无isdecimal方法
    print(num2.isdecimal()) #True
    print(num3.isdecimal()) #False
    print(num4.isdecimal()) #False
    
    #isnumberic:unicode,中文数字,罗马数字
    #bytes类型无isnumberic方法
    print(num2.isnumeric()) #True
    print(num3.isnumeric()) #True
    print(num4.isnumeric()) #True
    
    #三者不能判断浮点数
    num5='4.3'
    print(num5.isdigit())
    print(num5.isdecimal())
    print(num5.isnumeric())
    '''
    总结:
        最常用的是isdigit,可以判断bytes和unicode类型,这也是最常见的数字应用场景
        如果要判断中文数字或罗马数字,则需要用到isnumeric
    '''
    
    #is其他
    print('===>')
    name='egon123'
    print(name.isalnum()) #字符串由字母或数字组成
    print(name.isalpha()) #字符串只由字母组成
    
    print(name.isidentifier())
    print(name.islower())
    print(name.isupper())
    print(name.isspace())
    print(name.istitle())

    列表

    #作用:多个装备,多个爱好,多门课程,多个女朋友等
    
    #定义:[]内可以有多个任意类型的值,逗号分隔
    my_girl_friends=['alex','wupeiqi','yuanhao',4,5] #本质my_girl_friends=list([...])
    或
    l=list('abc')
    
    #优先掌握的操作:
    #1、按索引存取值(正向存取+反向存取):即可存也可以取      
    #2、切片(顾头不顾尾,步长)
    #3、长度
    #4、成员运算in和not in
    
    #5、追加
    #6、删除
    #7、循环
    #ps:反向步长
    l=[1,2,3,4,5,6]
    
    #正向步长
    l[0:3:1] #[1, 2, 3]
    #反向步长
    l[2::-1] #[3, 2, 1]
    #列表翻转
    l[::-1] #[6, 5, 4, 3, 2, 1]

    元组

    #作用:存多个值,对比列表来说,元组不可变(是可以当做字典的key的),主要是用来读
    
    #定义:与列表类型比,只不过[]换成()
    age=(11,22,33,44,55)本质age=tuple((11,22,33,44,55))
    
    #优先掌握的操作:
    #1、按索引取值(正向取+反向取):只能取   
    #2、切片(顾头不顾尾,步长)
    #3、长度
    #4、成员运算in和not in
    
    #5、循环

    字典

    #作用:存多个值,key-value存取,取值速度快
    
    #定义:key必须是不可变类型,value可以是任意类型
    info={'name':'egon','age':18,'sex':'male'} #本质info=dict({....})
    或
    info=dict(name='egon',age=18,sex='male')
    或
    info=dict([['name','egon'],('age',18)])
    或
    {}.fromkeys(('name','age','sex'),None)
    {'age': None, 'name': None, 'sex': None}
    #优先掌握的操作: #1、按key存取值:可存可取 #2、长度len #3、成员运算in和not in #4、删除 #5、键keys(),值values(),键值对items() #6、循环

    集合

    #作用:去重,关系运算,
    
    #定义:
                知识点回顾
                可变类型是不可hash类型
                不可变类型是可hash类型
    
    #定义集合:
                集合:可以包含多个元素,用逗号分割,
                集合的元素遵循三个原则:
                 1:每个元素必须是不可变类型(可hash,可作为字典的key)
                 2:没有重复的元素
                 3:无序
    
    注意集合的目的是将不同的值存放到一起,不同的集合间用来做关系运算,无需纠结于集合中单个值
     
    
    #优先掌握的操作:
    #1、长度len
    #2、成员运算in和not in
    
    #3、|合集
    #4、&交集
    #5、-差集
    #6、^对称差集
    #7、==
    #8、父集:>,>= 
    #9、子集:<,<=

    数据类型总结

    按存储空间的占用分(从低到高)

    数字
    字符串
    集合:无序,即无序存索引相关信息
    元组:有序,需要存索引相关信息,不可变
    列表:有序,需要存索引相关信息,可变,需要处理数据的增删改
    字典:无序,需要存key与value映射的相关信息,可变,需要处理数据的增删改

    按存值个数区分

    标量/原子类型 数字,字符串
    容器类型 列表,元组,字典

    按可变不可变区分

    可变 列表,字典
    不可变 数字,字符串,元组

    按访问顺序区分

    直接访问 数字
    顺序访问(序列类型) 字符串,列表,元组
    key值访问(映射类型) 字典

      

     Python表达式操作符及程序

    #作业一: 三级菜单
    #要求:
    打印省、市、县三级菜单
    可返回上一级
    可随时退出程序
    menu = {
        '北京':{
            '海淀':{
                '五道口':{
                    'soho':{},
                    '网易':{},
                    'google':{}
                },
                '中关村':{
                    '爱奇艺':{},
                    '汽车之家':{},
                    'youku':{},
                },
                '上地':{
                    '百度':{},
                },
            },
            '昌平':{
                '沙河':{
                    '老男孩':{},
                    '北航':{},
                },
                '天通苑':{},
                '回龙观':{},
            },
            '朝阳':{},
            '东城':{},
        },
        '上海':{
            '闵行':{
                "人民广场":{
                    '炸鸡店':{}
                }
            },
            '闸北':{
                '火车战':{
                    '携程':{}
                }
            },
            '浦东':{},
        },
        '山东':{},
    }
    
    
    
    tag=True
    while tag:
        menu1=menu
        for key in menu1: # 打印第一层
            print(key)
    
        choice1=input('第一层>>: ').strip() # 选择第一层
    
        if choice1 == 'b': # 输入b,则返回上一级
            break
        if choice1 == 'q': # 输入q,则退出整体
            tag=False
            continue
        if choice1 not in menu1: # 输入内容不在menu1内,则继续输入
            continue
    
        while tag:
            menu_2=menu1[choice1] # 拿到choice1对应的一层字典
            for key in menu_2:
                print(key)
    
            choice2 = input('第二层>>: ').strip()
    
            if choice2 == 'b':
                break
            if choice2 == 'q':
                tag = False
                continue
            if choice2 not in menu_2:
                continue
    
            while tag:
                menu_3=menu_2[choice2]
                for key in menu_3:
                    print(key)
    
                choice3 = input('第三层>>: ').strip()
                if choice3 == 'b':
                    break
                if choice3 == 'q':
                    tag = False
                    continue
                if choice3 not in menu_3:
                    continue
    
                while tag:
                    menu_4=menu_3[choice3]
                    for key in menu_4:
                        print(key)
    
                    choice4 = input('第四层>>: ').strip()
                    if choice4 == 'b':
                        break
                    if choice4 == 'q':
                        tag = False
                        continue
                    if choice4 not in menu_4:
                        continue
    
                    # 第四层内没数据了,无需进入下一层
    三级菜单面条版
    menu = {
        '北京':{
            '海淀':{
                '五道口':{
                    'soho':{},
                    '网易':{},
                    'google':{}
                },
                '中关村':{
                    '爱奇艺':{},
                    '汽车之家':{},
                    'youku':{},
                },
                '上地':{
                    '百度':{},
                },
            },
            '昌平':{
                '沙河':{
                    '老男孩':{},
                    '北航':{},
                },
                '天通苑':{},
                '回龙观':{},
            },
            '朝阳':{},
            '东城':{},
        },
        '上海':{
            '闵行':{
                "人民广场":{
                    '炸鸡店':{}
                }
            },
            '闸北':{
                '火车战':{
                    '携程':{}
                }
            },
            '浦东':{},
        },
        '山东':{},
    }
    
    
    
    #part1(初步实现):能够一层一层进入
    layers = [menu, ]
    
    while True:
        current_layer = layers[-1]
        for key in current_layer:
            print(key)
    
        choice = input('>>: ').strip()
    
        if choice not in current_layer: continue
    
        layers.append(current_layer[choice])
    
    
    
    #part2(改进):加上退出机制
    layers=[menu,]
    
    while True:
        if len(layers) == 0: break
        current_layer=layers[-1]
        for key in current_layer:
            print(key)
    
        choice=input('>>: ').strip()
    
        if choice == 'b':
            layers.pop(-1)
            continue
        if choice == 'q':break
    
        if choice not in current_layer:continue
    
        layers.append(current_layer[choice])
    三级菜单文青版
    #作业二:请闭眼写出购物车程序
    #需求:
    用户名和密码存放于文件中,格式为:egon|egon123
    启动程序后,先登录,登录成功则让用户输入工资,然后打印商品列表,失败则重新登录,超过三次则退出程序
    允许用户根据商品编号购买商品
    用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒
    可随时退出,退出时,打印已购买商品和余额
    import os
    
    product_list = [['Iphone7',5800],
                    ['Coffee',30],
                    ['疙瘩汤',10],
                    ['Python Book',99],
                    ['Bike',199],
                    ['ViVo X9',2499],
    
                    ]
    
    shopping_cart={}
    current_userinfo=[]
    
    db_file=r'db.txt'
    
    while True:
        print('''
        1 登陆
        2 注册
        3 购物
        ''')
    
        choice=input('>>: ').strip()
    
        if choice == '1':
            #1、登陆
            tag=True
            count=0
            while tag:
                if count == 3:
                    print('33[45m尝试次数过多,退出。。。33[0m')
                    break
                uname = input('用户名:').strip()
                pwd = input('密码:').strip()
    
                with open(db_file,'r',encoding='utf-8') as f:
                    for line in f:
                        line=line.strip('
    ')
                        user_info=line.split(',')
    
                        uname_of_db=user_info[0]
                        pwd_of_db=user_info[1]
                        balance_of_db=int(user_info[2])
    
                        if uname == uname_of_db and pwd == pwd_of_db:
                            print('33[48m登陆成功33[0m')
    
                            # 登陆成功则将用户名和余额添加到列表
                            current_userinfo=[uname_of_db,balance_of_db]
                            print('用户信息为:',current_userinfo)
                            tag=False
                            break
                    else:
                        print('33[47m用户名或密码错误33[0m')
                        count+=1
    
        elif choice == '2':
            uname=input('请输入用户名:').strip()
            while True:
                pwd1=input('请输入密码:').strip()
                pwd2=input('再次确认密码:').strip()
                if pwd2 == pwd1:
                    break
                else:
                    print('33[39m两次输入密码不一致,请重新输入!!!33[0m')
    
            balance=input('请输入充值金额:').strip()
    
            with open(db_file,'a',encoding='utf-8') as f:
                f.write('%s,%s,%s
    ' %(uname,pwd1,balance))
    
        elif choice == '3':
            if len(current_userinfo) == 0:
                print('33[49m请先登陆...33[0m')
            else:
                #登陆成功后,开始购物
                uname_of_db=current_userinfo[0]
                balance_of_db=current_userinfo[1]
    
                print('尊敬的用户[%s] 您的余额为[%s],祝您购物愉快' %(
                    uname_of_db,
                    balance_of_db
                ))
    
                tag=True
                while tag:
                    for index,product in enumerate(product_list):
                        print(index,product)
                    choice=input('输入商品编号购物,输入q退出>>: ').strip()
                    if choice.isdigit():
                        choice=int(choice)
                        if choice < 0 or choice >= len(product_list):continue
    
                        pname=product_list[choice][0]
                        pprice=product_list[choice][1]
                        if balance_of_db > pprice:
                            if pname in shopping_cart: # 原来已经购买过
                                shopping_cart[pname]['count']+=1
                            else:
                                shopping_cart[pname]={'pprice':pprice,'count':1}
    
                            balance_of_db-=pprice # 扣钱
                            current_userinfo[1]=balance_of_db # 更新用户余额
                            print("Added product " + pname + " into shopping cart,33[42;1myour current33[0m balance " + str(balance_of_db))
    
                        else:
                            print("买不起,穷逼! 产品价格是{price},你还差{lack_price}".format(
                                price=pprice,
                                lack_price=(pprice - balance_of_db)
                            ))
                        print(shopping_cart)
                    elif choice == 'q':
                        print("""
                        ---------------------------------已购买商品列表---------------------------------
                        id          商品                   数量             单价               总价
                        """)
    
                        total_cost=0
                        for i,key in enumerate(shopping_cart):
                            print('%22s%18s%18s%18s%18s' %(
                                i,
                                key,
                                shopping_cart[key]['count'],
                                shopping_cart[key]['pprice'],
                                shopping_cart[key]['pprice'] * shopping_cart[key]['count']
                            ))
                            total_cost+=shopping_cart[key]['pprice'] * shopping_cart[key]['count']
    
                        print("""
                        您的总花费为: %s
                        您的余额为: %s
                        ---------------------------------end---------------------------------
                        """ %(total_cost,balance_of_db))
    
                        while tag:
                            inp=input('确认购买(yes/no?)>>: ').strip()
                            if inp not in ['Y','N','y','n','yes','no']:continue
                            if inp in ['Y','y','yes']:
                                # 将余额写入文件
    
                                src_file=db_file
                                dst_file=r'%s.swap' %db_file
                                with open(src_file,'r',encoding='utf-8') as read_f,
                                    open(dst_file,'w',encoding='utf-8') as write_f:
                                    for line in read_f:
                                        if line.startswith(uname_of_db):
                                            l=line.strip('
    ').split(',')
                                            l[-1]=str(balance_of_db)
                                            line=','.join(l)+'
    '
    
                                        write_f.write(line)
                                os.remove(src_file)
                                os.rename(dst_file,src_file)
    
                                print('购买成功,请耐心等待发货')
    
                            shopping_cart={}
                            current_userinfo=[]
                            tag=False
    
    
                    else:
                        print('输入非法')
    
    
        else:
            print('33[33m非法操作33[0m')
    复制代码
    购物车面条版
  • 相关阅读:
    Elasticsearch 深入5
    Elasticsearch 深入4
    Elasticsearch 深入3
    Elasticsearch 深入2
    Elasticsearch1简单深入
    Kibana简单操作Elasticsearch
    什么是非阻塞同步?
    面向对象之思考
    使用spring代码中控制事务
    mybatis 中使用oracle merger into
  • 原文地址:https://www.cnblogs.com/hanbowen/p/9111767.html
Copyright © 2011-2022 走看看