一、数据类型

1.什么是数据?

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

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

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

3 数据类型

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

  字符串

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

  列表

  元组

  字典

  集合

4.数字

#整型int   

作用:年纪,等级,身份证号,qq号等整型数字相关   

定义:age=10  #本质age=int(10)

#浮点型float   

作用:薪资,身高,体重,体质参数等浮点数相关

定义:salary=3000.3  #本质salary=float(3000.3)

#二进制,十进制,八进制,十六进制

age = 20
print(bin(age)) #10 ---->2
print(oct(age)) # 10 --->8
print(hex(age)) # 10 --->16

 5.字符串

#作用:名字,性别,国籍,地址等描述信息

#定义:在单引号\双引号\三引号内,由一串字符组成 name='egon' #优先掌握的操作:

#1、按索引取值(正向取+反向取) :只能取

name = 'abb'
print(name[1])

#2、切片(顾头不顾尾,步长)

name = 'hello zxy'
print(name[1:3])  #[1:5:2]隔了两个
el 

#3、长度len

name = 'egon'
print(len(name))

#4、成员运算in和not in

#5、移除空白strip

name = input('请输入name:')
name=name.strip()
print(name)
#简写
name = input('请输入name:')
print(name.strip())
name = '****egon88888'
print(name.strip('*'))
#lstrip 除去左边的 rstrip除去右边的

除去乱码

#6、切分split

user_info='root:x:0:0::/root:/bin/bash'
print(user_info.split(':')[5])
print(user_info.split(':',2))#切分两次

#7、循环

 字符串的其他方法

#开头结尾
name = 'zbbzxy'
print(name.endswith('xy')) #以xy结尾的
print(name.startswith('zb')) #以zb开头的

True
True
#替换
name = 'he say : she is he'
print(name.replace('he','SB'))
print(name.replace('he','SB',1))#只替换第一个
#format格式化
print('{} {} {}'.format('zbb',18,'boy'))
print('{1} {2} {0}'.format('zbb',18,'boy'))
print('{name} {age} {gender}'.format(name='zbb',age=18,gender='boy'))#可以不按照顺序来
print('NAME:{name} AGE:{age} GENDER:{gender}'.format(name='zbb',age=18,gender='boy'))
#isdigit
' print(num.isdigit())#判断是否为字符串 True
while True:
    ages=input('请输入age').strip()
    if len(ages) == 0:
        continue
    if ages.isdigit():
        ages =int(ages)
        print(ages,type(ages))
        break

任性玩

 只需要了解的方法

name = 'qwerty'
print(name.find('w'))
print(name.find('x')) #找不到不会报错,会显示-1,顾头不顾尾
print(name.find('w',3,6)) #从3 ---6中找w   xfind从右边找
#字母变换大小写
name = 'ZBB'
print(name .lower())  #变小写
name = 'zxy'
print(name.upper())   #变大写  
#captalize,swapcase,title
print(name.capitalize()) #首字母大写
print(name.swapcase()) #大小写翻转
msg='egon say hi'
print(msg.title()) #每个单词的首字母大写 
#is其他
print('===>')
name='egon123'
print(name.isalnum()) #字符串由字母或数字组成
print(name.isalpha()) #字符串只由字母组成
#在python3中
num1=b'4' #bytes类型
num2=u'4' #unicode,python3中无需加u就是unicode
num3='四' #中文数字
num4='Ⅳ' #罗马数字  

六、列表

#作用:多个装备,多个爱好,多门课程,多个女朋友等

#定义:[]内可以有多个任意类型的值,逗号分隔

my_girl_friends=['alex','wupeiqi','yuanhao',4,5]

#优先掌握的操作:

#1、按索引存取值(正向存取+反向存取):即可存也可以取

#2、切片(顾头不顾尾,步长)

my_friends =['zbb','zxy']
print(my_friends[])

#3、长度

print(len(my_friends)) #统计元素的个数

#4、成员运算in和not in

print('zbb' in my_friends)
True

#5、追加

my_friends =['zbb','zxy']
my_friends.append('oldboy')
print(my_friends)

#6、删除

my_friends.pop() #默认按照索引删除列表最后一个
print(my_friends)#remove按照值删除

#7、循环

其他操作(了解)

my_friends =['zbb','zxy']
my_friends.insert(1,'nb')  #插入
print(my_friends)

  

my_friends =['zbb','zxy']
print(my_friends.clear()) #清除
print(my_friends.copy())  #f复制
my_friends.extend(['123','233','13']) #追加多个
print(my_friends)
显示结果
['zbb', 'zxy', '123', '233', '13']

  

my_friends.reverse()#翻转
print(my_friends)

  

l=[2,4,5,6,1,-1]
l.sort() #翻转排序 l.sort(reverse=True)
print(l)

  

七、元组

#作用:存多个值,对比列表来说,元组不可变(是可以当做字典的key的),主要是用来读

#定义:与列表类型比,只不过[]换成()

age=(11,22,33,44,55)  ###本质age=tuple((11,22,33,44,55))

#优先掌握的操作:

#1、按索引取值(正向取+反向取):只能取

#2、切片(顾头不顾尾,步长)

#3、长度

#4、成员运算in和not in

#5、循环

age=(2,3,44,22,33)
print(age.index(2)) #查看索引
print(age.count(44))  #统计元素有多少个

 练习

#简单购物车,要求如下:

实现打印商品详细信息,用户输入商品名和购买个数,则将商品名,价格,购买个数加入购物列表,如果输入为空或其他非法输入则要求用户重新输入  

msg_dic={
'apple':10,
'tesla':100000,
'mac':3000,
'lenovo':30000,
'chicken':10,
}

l=[]
while True:
    for key in msg_dic:
        print('商品名:{name}' '价格:{price}'.format(name=key,price=msg_dic[key]))
    choice=input('购买的商品名:').strip()
    if len(choice)==0 or choice not in msg_dic:
        continue
    count=input('购买的数量:').strip()
    if count.isdigit():
        count=int(count)
        l.append((choice,msg_dic[choice],count))
    print(l)

八、字典

#作用:存多个值,key-value存取,取值速度快  字典是无序的

#定义:key必须是不可变类型(可hash类型),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)

#优先掌握的操作:
#1、按key存取值:可存可取

#取值
info={'name':'egon','age':18,'sex':'male'}
print(info['age'])
#存值
info['hg']=1.80
print(info)
print(info.get('name'))  #也是取值
print(info.get('n'))   #没有的值不会报错,显示none

#2、长度len
#3、成员运算in和not in

#4、删除

info={'name':'egon','age':18,'sex':'male'}
print(info.pop('name'))  #取代的是值
print(info)

egon
{'age': 18, 'sex': 'male'}
print(info.popitem()) #取到的是key+值   随机弹
print(info)

('sex', 'male')
{'name': 'egon', 'age': 18}

#5、键keys(),值values(),键值对items()

info={'name':'egon','age':18,'sex':'male'}
print(info.keys())
print(info.values())

# dict_keys(['name', 'age', 'sex'])
# dict_values(['egon', 18, 'male'])

# 只取key或者值
for key in info.keys():
    print(key)
    # name
    # age
    # sex
for key in info.values():
    print(key)
    # egon
    # 18
for  key,vel in   info.items():
    print(key,vel)

name egon
age 18
sex male

#6、循环

#7字典追加

d={}
print(d)
d['name']='zbb'
d['
d['hobby']=[] #追加多个值 最好的是列表
d['hobby'].append('play')
d['hobby'].append('game')
print(d)

练习

有如下值集合 [11,22,33,44,55,66,77,88,99,90...],将所有大于 66 的值保存至字典的第一个key中,将小于 66 的值保存至第二个key的值中 即: {'k1': 大于66的所有值, 'k2': 小于66的所有值}

a=[11,22,33,44,55,66,77,88,99,90]

dic={'k1':[],'k2':[]}
for i  in  a:
    if i>66:
        dic['k1'].append(i)
    else:
        dic['k2'].append(i)
print(dic)#显示如下{'k1': [77, 88, 99, 90], 'k2': [11, 22, 33, 44, 55, 66]}

统计s='hello alex alex say hello sb sb'中每个单词的个数

s = 'hello alex alex say hello sb sb'
l = s.split()
dic={}
for aa in l:
    if aa  not in dic:
        dic[aa]=1
    else:
        dic[aa]+=1
print(dic)

九、集合

s={1,'a',1,2,1,1,1}  或者  s=set({1,'a',1,2,1,1,1})

#作用:去重,关系运算

#定义

可变类型是不可hash类型

不可变类型是可hash类型

#定义集合:

集合:可以包含多个元素,用逗号分割,

集合的元素遵循三个原则:

1:每个元素必须是不可变类型(可hash,可作为字典的key)

2:  元素唯一

3:无序

注意集合的目的是将不同的值存放到一起,不同的集合间用来做关系运算,无需纠结于集合中单个值

#优先掌握的操作:
#1、长度len
#2、成员运算in和not in

print('alex' not in pythons)  

#3、|合集

print(s1 | s2)

#4、&交集

s1={2,4,5,6,1}
s2={2,4,11,12}
print(s1 & s2)

#5、-差集

print(s1 - s2)

#6、^对称差集

print(s1 ^ s2)

#7、==
#8、父集:>,>=

print(s1 >= s2)

#9、子集:<,<=

#10、 加 add  删除 pop随机删除

remove指定删除   没有会报错

discard()  删除不会报错  相当于  rm  -f  不会输出信息

一.关系运算
  有如下两个集合,pythons是报名python课程的学员名字集合,linuxs是报名linux课程的学员名字集合
  pythons={'alex','egon','yuanhao','wupeiqi','gangdan','biubiu'}
  linuxs={'wupeiqi','oldboy','gangdan'}
  1. 求出即报名python又报名linux课程的学员名字集合

print(pythons & linuxs)

  2. 求出所有报名的学生名字集合

print(pythons | linuxs)

  3. 求出只报名python课程的学员名字

print(pythons - linuxs)

  4. 求出没有同时这两门课程的学员名字集合

print(pythons ^ linuxs)

  

二.去重

   1. 有列表l=['a','b',1,'a','a'],列表元素均为可hash类型,去重,得到新列表,且新列表无需保持列表原来的顺序

l=['a','b',1,'a','a']

   2.在上题的基础上,保存列表原来的顺序

l1=[]

for item in l:
    if item not in l1:
        l1.append(item)
print(l1)

   3.去除文件中重复的行,肯定要保持文件内容的顺序不变

   4.有如下列表,列表元素为不可hash类型,去重,得到新列表,且新列表一定要保持列表原来的顺序

l=[
{'name':'egon','age':18,'sex':'male'},
{'name':'alex','age':73,'sex':'male'},
{'name':'egon','age':20,'sex':'female'},
{'name':'egon','age':18,'sex':'male'},
{'name':'egon','age':18,'sex':'male'},
]

l1=[]
for item in l:
    if item not in l1:
        l1.append(item)
print(l1)

  

十、数据类型总结

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

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

按存值个数区分

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

按可变不可变区分

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

按访问顺序区分

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

十一、字符编码

unicode----->encode-------->utf-8

utf-8-------->decode---------->unicode

http://www.cnblogs.com/linhaifeng/articles/5950339.html   参考文档

十二、文件处理

计算机系统

计算机系统分为:计算机硬件,操作系统,应用程序三部分。

在python中

#1. 打开文件,得到文件句柄并赋值给一个变量
f=open('a.txt','r',encoding='utf-8') #默认打开模式就为r  window 默认打开的GBK  代码不加utf8 的话会显示乱码

#2. 通过句柄对文件进行操作
data=f.read()

print(data)

#3. 关闭文件
f.close()

f=open('a.txt','r')的过程分析

#1、由应用程序向操作系统发起系统调用open(...)

#2、操作系统打开该文件,并返回一个文件句柄给应用程序

#3、应用程序将文件句柄赋值给变量f

屁股决定思维

打开一个文件包含两部分资源:操作系统级打开的文件+应用程序的变量。在操作完毕一个文件时,必须把与该文件的这两部分资源一个不落地回收,回收方法为:
1、f.close() #回收操作系统级打开的文件
2、del f #回收应用程序级的变量

其中del f一定要发生在f.close()之后,否则就会导致操作系统打开的文件还没有关闭,白白占用资源,
而python自动的垃圾回收机制决定了我们无需考虑del f,这就要求我们,在操作完毕文件后,一定要记住f.close()

经常忘记怎么办?? 傻瓜式操作

with关键字来帮我们管理上下文
with open('a.txt','w') as f:
    pass

with open('a.txt','r') as read_f,open('b.txt','w') as write_f:
    data=read_f.read()
    write_f.write(data)

 

打开文件的模式

 

模式可以是以下方式以及他们之间的组合:

Character Meaning
‘r' open for reading (default)
‘w' open for writing, truncating the file first
‘a' open for writing, appending to the end of the file if it exists
‘b' binary mode
‘t' text mode (default)
‘+' open a disk file for updating (reading and writing)
‘U' universal newline mode (for backwards compatibility; should not be used in new code)
#1. 打开文件的模式有(默认为文本模式):
r ,只读模式【默认模式,文件必须存在,不存在则抛出异常】
w,只写模式【不可读;不存在则创建;存在则清空内容】
a, 之追加写模式【不可读;不存在则创建;存在则只追加内容】

#2. 对于非文本文件,我们只能使用b模式,"b"表示以字节的方式操作(而所有文件也都是以字节的形式存储的,使用这种模式无需考虑文本文件的字符编码、图片文件的jgp格式、视频文件的avi格式)
rb
wb
ab

#3. 了解部分
"+" 表示可以同时读写某个文件
r+, 读写【可读,可写】
w+,写读【可读,可写】
a+, 写读【可读,可写】

x, 只写模式【不可读;不存在则创建,存在则报错】
x+ ,写读【可读,可写】
xbb模式
以b方式打开时,读取到的内容是字节类型,写入时也需要提供字节类型,不能指定编码
f=open('a.txt','rb')
print(f.read().decode('utf-8'))
#了解f.readable() #文件是否可读f.writable() #文件是否可读f.closed #文件是否关闭f.encoding #如果文件打开模式为b,则没有该属性f.flush() #立刻将文件内容从内存刷到硬盘f.name

  

操作文件的方法

#掌握
f.read() #读取所有内容,光标移动到文件末尾   自动就没有换行符
f.readline() #读取一行内容,光标移动到第二行首部

print(f.readline(),end="")   #把换行符 设置为空

f.readlines() #读取每一行内容,存放于列表中

['11\n', '23\n', '231414414\n', '32132141\n', '干干于'] 

f.write('1111\n222\n') #针对文本模式的写,需要自己写换行符

f.write('1111\n222\n'.encode('utf-8')) #针对b模式的写,需要自己写换行符

f.writelines(['333\n','444\n']) #文件模式

f.writelines([bytes('333\n',encoding='utf-8'),'444\n'.encode('utf-8')]) #b模式

文件内光标移动

一: read(3):

  1. 文件打开方式为文本模式时,代表读取3个字符

  2. 文件打开方式为b模式时,代表读取3个字节

3. print(f.tell) 显示光标的位置

4.f.seek(6) 跳转的 第六个光标的位置

二: 其余的文件内光标移动都是以字节为单位如seek,tell,truncate

注意:

  1. seek有三种移动方式0,1,2,其中1和2必须在b模式下进行,但无论哪种模式,都是以bytes为单位移动的

f.seek(6,0)    0是开头 1 当前位置  2 是末尾    f.seek(-1,2)

  2. truncate是截断文件,所以文件的打开方式必须可写,但是不能用w或w+等方式打开,因为那样直接清空文件了,所以truncate要在r+或a或a+等模式下测试效果

从开头开始截取 f.truncate(5)   只留前几个

import time
with open('test.txt','rb') as f:
    f.seek(0,2)
    while True:
        line=f.readline()
        if line:
            print(line.decode('utf-8'),end ='0')
        else:
            time.sleep(0.2)

  

文件的修改

文件的数据是存放于硬盘上的,因而只存在覆盖、不存在修改这么一说,我们平时看到的修改文件,都是模拟出来的效果,具体的说有两种实现方式:

方式一:将硬盘存放的该文件的内容全部加载到内存,在内存中是可以修改的,修改完毕后,再由内存覆盖到硬盘(word,vim,nodpad++等编辑器)

import os

with open('a.txt') as read_f,open('.a.txt.swap','w') as write_f:
    data=read_f.read() #全部读入内存,如果文件很大,会很卡
    data=data.replace('alex','SB') #在内存中完成修改

    write_f.write(data) #一次性写入新文件

os.remove('a.txt')
os.rename('.a.txt.swap','a.txt')

方式二:将硬盘存放的该文件的内容一行一行地读入内存,修改完毕就写入新文件,最后用新文件覆盖源文件 

import os

with open('a.txt') as read_f,open('.a.txt.swap','w') as write_f:
    for line in read_f:
        line=line.replace('alex','SB')
        write_f.write(line)

os.remove('a.txt')
os.rename('.a.txt.swap','a.txt')
#作业:请闭眼写出购物车程序
#需求:
用户名和密码存放于文件中,格式为: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('''
登陆
注册
购物
    ''')

    choice=input('>>: ').strip()

    ':
        #1、登陆
        tag=True
        count=0
        while tag:
            if count == 3:
                print('\033[45m尝试次数过多,退出。。。\033[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('\n')
                    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('\033[48m登陆成功\033[0m')

                        # 登陆成功则将用户名和余额添加到列表
                        current_userinfo=[uname_of_db,balance_of_db]
                        print('用户信息为:',current_userinfo)
                        tag=False
                        break
                else:
                    print('\033[47m用户名或密码错误\033[0m')
                    count+=1

    ':
        uname=input('请输入用户名:').strip()
        while True:
            pwd1=input('请输入密码:').strip()
            pwd2=input('再次确认密码:').strip()
            if pwd2 == pwd1:
                break
            else:
                print('\033[39m两次输入密码不一致,请重新输入!!!\033[0m')

        balance=input('请输入充值金额:').strip()

        with open(db_file,'a',encoding='utf-8') as f:
            f.write('%s,%s,%s\n' %(uname,pwd1,balance))

    ':
        if len(current_userinfo) == 0:
            print('\033[49m请先登陆...\033[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,\033[42;1myour current\033[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('\n').split(',')
                                        l[-1]=str(balance_of_db)
                                        line=','.join(l)+'\n'

                                    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('\033[33m非法操作\033[0m')

购物车程序面条版

  

最新文章

  1. JavaEE基础(十一)/Eclipse介绍
  2. 【转】ASP.NET Cookies简单应用 记住用户名和密码
  3. windows主线程等待子线程退出卡死问题
  4. Winfroms---看看吧客官~
  5. IKAnalyzer使用停用词词典进行分词
  6. Ubuntu Server PHP常用扩展库的安装
  7. 使用js实现ajax的get请求步骤
  8. 41.Linux应用调试-修改内核来打印用户态的oops
  9. CentOS 6忘记root密码的解决办法
  10. java-----理解java的三大特性之多态
  11. 13: ELK(ElasticSearch+Logstash+ Kibana)搭建实时日志分析平台
  12. cobbler登录web界面时出现“Internal Server Error”
  13. 买or不买?如何测试博彩公司赔率是否合理?
  14. css的特性
  15. 【持续更新】 | OpenCV 学习笔记
  16. “数据上帝” Jeff Hammerbacher
  17. 获取当前操作系统的ip
  18. 基于sendEmail的简单zabbix邮件报警
  19. LINQ to Entities does not recognize the method &#39;Int32 ToInt32(System.String)&#39; method, and this method cannot be translated into a store expression
  20. java8,方法引用

热门文章

  1. 《Android应用性能优化》 第8章 图形
  2. iOS 判断设备是否越狱了
  3. Halcon从某一个图片以指定区域绘制到另一个图像
  4. BridgePattern(23种设计模式之一)
  5. loj2395 [JOISC 2017 Day 2]火车旅行
  6. 数组队列C++实现
  7. 在WindowsXP+IIS5.1下运行ASP.NET MVC3
  8. PLSQL连接Oracle11g 64位
  9. sqlserver 时间差转换为天时分秒
  10. pch文件的创建与配置