數據類型,字符串,文件處理

數據類型python

字符編碼git

文件處理api

 

數據類型服務器

1什麼是數據?app

x=10.10是咱們要存儲的數據ide

2 數據類型ui

  數字(整形,長整形,浮點型,複數)google

  字符串編碼

  字節串:在介紹字符編碼時介紹字節bytes類型spa

  列表

  元組

  字典

集合

 可變or不可變

    !!!可變:值變,id不變。可變==不可hash

    !!!不可變:值變,id就變。不可變==hash

數字類型:

Int:做用:年齡;級別;等級;身份證號等

X=10 #x=int()

Float:做用:

字符串類型

#/usr/bin/env python
# Author:hongjie.gao
# 用途:名字,性別,地址,愛好等  存一個值(特殊之處在於能夠把裏面的小的字符串取出來),有序的,不可變的
name='ghj' #name=str('ghj')
# print(id(name),type(name),name)
# # 按索引取值(正向取,反向取),只能取,不能修改
# print(name[0],type(name[0]))
# print(name[-2],type(name[-2]))
# # 切片(顧頭不顧尾,步長)
# print(name[1:2])
#
# GHJ='hello world'
# print(GHJ[1:7])
# print(GHJ[1:7:2])
fhm='qlwertyuiop 123'
# print(fhm[1:13])
# print(fhm[1:13:2])
# print(fhm[1:13:3])
# print(fhm[:])
# print(fhm[::3])
# 倒着取
# print(fhm[::-1])

# 長度
# fhm='qlwertyuiop 123'
# print(len(fhm))

# 成員運算in和 not in
# fhm='qlwertyuiop 123'
# print(' 123'in fhm)
# print('1234'in fhm)
# print(' 1234'not in fhm)

# 移除空白strip:去掉首尾的字符  重點 經常使用的
# 左:left
# 右:right

password='ghj123       '
# password=password.strip()
# print(password)
# print(password.strip())

passw = '  **123    $$***   '
# passw=passw.strip()
# print(passw.strip())
# print(passw.strip('*| |$'))



# 切分split       重點 經常使用的
user_info='name;age;hobbies;sex'
# print(user_info.split(';'))
# print(user_info.split(';')[0])
# 默認空格切
# cmd='put   a.txt'
# print(cmd.split()[0])

# file_info='put  /a/b/c/d/a.txt'
# print(file_info.split()[0])
# print(file_info.split('/',1)[0])

#
# ghj='ghj say i have one electric car'
# print(ghj.split(maxsplit=1))

# ghj='ghj_good'
# print(ghj.endswith('good'))    # 以什麼結尾
# print(ghj.startswith(ghj))      # 以什麼開頭

ghj='GHJ sayi have one electric car,my name is GHJ '
# print(ghj.replace('GHJ','ghj'))         #替換,前面old,後面new,默認全替換
# print(ghj.replace('GHJ','ghj',1 ))       #替換一次

# print('my name is %s,my age is %s'%('ghj',25))  # 字符串的格式化
# print('my name is {},my age is {}'.format('ghj',25))  # 有幾個佔位符就傳幾個值
# print('{0},{0},{1}'.format('ghj',25))   # 花括號裏能夠控制位置
# print('my name is {x},my age is {y}'.format(y=25,x='ghj'))  #能夠不依賴位置傳值

# find,rfind,index,rindex,count   瞭解部分
# find
ghj='hello world'
# print(ghj.find('or'))   # 查找子字符串的起始位置,從左到右找,若是有,則返回第一個子字符串索引
# print(ghj.find('dadada'))   # 查找子字符串的起始位置,從左到右找,若是沒有,則返回-1
# rfind  從右往左找
# index
# print(ghj.index('or'))  # 查找子字符串的起始位置,從左到右找,若是有,則返回第一個子字符串索引
# print(ghj.index('dadadad'))      # 查找子字符串的起始位置,從左到右找,若是沒有,則報錯
# rindex 從右往左找
# count
# print(ghj.count('l',0,4))  #查找包含子字符串的個數,顧頭不顧尾
# print(ghj.count('l',0,2))

# split        # 把字符串切割成列表  經常使用操做
user_info='name;age;hobbies;sex'
# l= user_info.split(';')
# print(l)
#
# # join     # 把列表還原成字符串    經常使用操做
# print(':'.join(l))
# print(''.join(l))
# print(' '.join(l))


# center,ljust,rjust,zerofill       經常使用操做
# ===========ghj============
# print('ghj'.center(30,'='))  #中間對齊,補夠30個
# print('ghj'.ljust(30,'='))  #往左對齊,補夠30個
# print('ghj'.rjust(30,'='))  #往右對其,補夠30個
# print('ghj'.zfill(30))  #直接指定寬度,往右對齊,以0補充,補夠30個
#
#  \t 製表符
# ghj='abc\t123'
# print(ghj)   #pycharm默認以一個空格
# print(ghj.expandtabs(3))    #expandtabs指定以幾個空格

# ghj='ghj Say hello word'          瞭解部分
# print(ghj.capitalize())  #首字母大寫
# print(ghj.upper())   #所有大寫
# print(ghj.lower())  #所有小寫
# print(ghj.title())  #每一個單詞的首字母大寫、
# print(ghj.swapcase())   #大小寫反轉



# is系列
ghj='ghj Say hello word'
# print(ghj.isupper())  #判斷是否所有大寫
# print(ghj.islower())    #判斷是否所有小寫
# print(ghj.istitle())    #判斷每一個單詞的首字母是否大寫


ghj='abc123'
GHJ='dadad'
print(ghj.isalnum())              #字符串是由字母或數字組成

print(ghj.isalpha())              #字符串是由字母組成
print(GHJ.isalpha())
# ghj='  '
# print(ghj.isspace())           # 不是重點       #判斷是否全是空格,是==ture

# ghj='aaaaif123'
# GHJ='aaaaai f123'
# print(ghj.isidentifier())          # 不是重點   #判斷這個字符串裏包不包含python的關鍵字
# print(GHJ.isidentifier())


# 判斷數字
# print(ghj.isdigit())      #重點   判斷字符串裏包含的字符是否是純數字(bytes,unicode)
# age=25
# ghj=input('age>>:').strip()  #用戶輸出的字符串,把空格所有去掉
# if ghj.isdigit():            #判斷用戶輸入的字符串裏包含的字符是否是純數字
#     ghj=int(ghj)             #把字符串轉爲數字類型
#     if ghj==age:             #
#         print('ok')          #
# else:
#     print('必須輸入數字')

num1 = b'4'  # bytes
num2 = u'4'  # unicode,python3中無需加u就是unicode
num3 = '四'  # 中文數字
num4 = '壹'  # 漢字
num5 = 'Ⅳ'  # 羅馬數字

# print(num1.isdigit())
# print(num2.isdigit())
# print(num3.isdigit())
# print(num4.isdigit())
# print(num5.isdigit())
# isdigit只能判斷bytes,unicode類型的數字

# print(num2.isdecimal())
# print(num3.isdecimal())
# print(num4.isdecimal())
# print(num5.isdecimal())
# isdecima只能判斷unicode類型

# print(num2.isnumeric())
# print(num3.isnumeric())
# print(num4.isnumeric())
# print(num5.isnumeric())
# snumeric能判斷中文數字,羅馬數字,漢字數字,銀行用

列表類型

#!/use/bin/env python
#Aothor:hongjie.gao
# 可變(id沒變,值變),能夠存多個值,值能夠是任意類型,有序,
#做用:多個裝備,多個愛好,多門課程,多個女友等

#定義:[]內能夠有多個任意類型的值,逗號分隔
# my_girl_friends=['yangmi','liuyifei','liutou',4,5] #本質my_girl_friends=list([...])
# print(my_girl_friends)

# 優先掌握的操做:
# 按索引存取值(正向存取+反向存取):便可存也能夠取
# print(my_girl_friends[2])   # 取出第三個女朋友  正取(從0 開始)
# print(my_girl_friends[-1])  # 取出最後一個女朋友  反取(從-1開始)
# print(id(my_girl_friends))
# my_girl_friends[0]='fanbingbing'
# print(id(my_girl_friends))    #  id沒變

# 切片(顧頭不顧尾,步長)
# print(my_girl_friends[0:2])     #取出前兩個女朋友,默認步長1
# print(my_girl_friends[0:2:2])

# 長度
# print(len(my_girl_friends))

# 成員運算in和not in(判斷列表的元素在不在列表裏面)
# print('liutou'in my_girl_friends)
# print(4 in my_girl_friends)
# print(6 not in my_girl_friends)

# 追加
# my_girl_friends.append(['6號','7號'])
# print(my_girl_friends)
# 刪除
# del my_girl_friends[2] #通用的刪,能夠刪除列表,字符串等
# print(my_girl_friends)
# print(my_girl_friends.remove('yangmi'))  #remove:指定元素來刪,單純的刪除,不會返回刪除的值
# print(my_girl_friends)

# my_girl_friends.pop()       #pop按照索引來刪,默認從末尾開始刪 (-1)
# print(my_girl_friends)
# ghj=my_girl_friends.pop(1)          #取出刪除的值,至關於剪切
# print(my_girl_friends)
# print(ghj)
# 循環


# 其餘操做:
my_girl_friends=['yangmi','liuyifei','liutou',4,5,4] #本質my_girl_friends=list([...])
# my_girl_friends.insert(0,'GHJ')  # 按照索引往前插值
# print(my_girl_friends)
# my_girl_friends.insert(2,'FHM')
# print(my_girl_friends)

# my_girl_friends.extend([1,2,3,4,5])     #往列表最後加多個值
# print(my_girl_friends)

# print(my_girl_friends.count(4))         #統計指點元素的個數

# 瞭解:
# my_girl_friends.clear()   # 清空列表
# print(my_girl_friends)

# a=my_girl_friends.copy()      # 拷貝了一份列表
# print(a)

# my_girl_friends.reverse()     # 反轉列表
# print(my_girl_friends)

# a=[3,5,1,9,-8]
# a.sort()        # 排序,從小到大排序
# print(a)
# a.sort(reverse=True)  # 從大到小排序
# print(a)

# 練習:
# 加值
# 對列:先進先出,扶梯
#append,pop
# a=[]
# a.append('first')
# a.append('second')
# a.append('third')
# print(a)
# print(a.pop(0))
# print(a.pop(0))
# print(a.pop(0))
# insert,pop
# 堆棧:先進後出,後進先出
a=[]
a.insert(0,'first')
a.insert(0,'second')
a.insert(0,'third')
print(a)
print(a.pop(0))
print(a.pop(0))
print(a.pop(0))
# 刪值
# remove   pop

 

元組類型

#!/usr/bin/env python
# Author:hongjie.gao
# 存任意多個值,有序,不可變
# 比列表佔內存空間多   一般用在讀的操做

# 定義方式:
A=('a','b','c','d')   #A=tuple('a','b','c','d')
# print(id(A),type(A),A)

#優先掌握的操做:
# 按索引取值(正向取+反向取):只能取
# print(A[2])     #正向取
# print(A[-2])   # 反向取
# 切片(顧頭不顧尾,步長)
# print(A[0:2])       #產生了一個新的元組
# print(A)
# 長度
# print(len(A))
# 成員運算in和not in
# print('c'in A)
# print('f' not  in A )

#其餘操做:
# print(A.index('c'))     #查看索引
# print(A.index('DADA'))  #不存在就報錯
#
# print(A.count('a'))        #統計哥數
# #


# 字典的成員運算:


# msg_dic={
# 'apple':10,
# 'tesla':100000,
# 'mac':3000,
# 'lenovo':30000,
# 'chicken':10,
# }
# # print('apple' in msg_dic)    # 對於字典來講成員運算判斷的不是值,是key
#
# for key  in msg_dic:                     # for 循環不依賴索引,直接拿出值
#     print(key,msg_dic[key])                 # 每次打印出來都是無序 的

# for i in range(0,11,2):  #  按照索引來取值  range:指定起始位置,指定終止位置,顧頭不顧尾,還能夠指定步長  (和列表,元組很像)
# for i in range(10) # 不指定開始,表明從0到10,表明默認結束位置10
#     print(i)

#
# A=('a','b','c','d')
# for i in range(len(A)):
#     print(i,A[i])


# # 循環





#簡單購物車,要求以下:
# 實現打印商品詳細信息,用戶輸入商品名和購買個數,則將商品名,價格,購買個數加入購物列表,若是輸入爲空或其餘非法輸入則要求用戶從新輸入  
#
# msg_dic={
# 'apple':10,
# 'tesla':100000,
# 'mac':3000,
# 'lenovo':30000,
# 'chicken':10,
# }
# a=[]
# while True:
#     for key in msg_dic:
#         print(key, msg_dic[key])
#     choice = input('>>:').strip()
#     if choice not in msg_dic:
#         print('商品不存在')
#         continue
#     count = input('個數>>:').strip()
#     if not count.isdigit():
#         print('請輸入數字')
#         continue
#     else:
#         a.append((choice, msg_dic[choice], int(count)))
#         print(a)


# while+else
# for i in range(5):
#     print(i)
# else:
#     print('ok')
#

# for i in range(5):
#     if i == 3:
#         break
#     print(i)
# else:
#     print('ok')

字典類型

#!/usr/bin/env python
# Author:hongjie.gao
#做用:存多個值,key-value存取,取值速度快
#定義:key必須是不可變類型,value能夠是任意類型
# a={'a':1}   #字符串能夠當作字典的key
# b={1:2}     #數字能夠作字典的key
# c={['a',2,'mac']:3000}  #列表不能夠作字典的key
# c={('a',2,'mac'):3000}      #元組能夠作字典的key
# print(c[('a',2,'mac')])


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)

#優先掌握的操做:
# 按key存取值:可存可取
# info={'name':'egon','age':18,'sex':'male'}
# print(info['name'])  #取   輸入不存在的key報錯
# info['hobbies']=['read','music','play','sleep']  #存
# print(info)
# 長度len
# print(len(info))
# 成員運算in和not in
#
#
# 刪除
# print(info.pop('name'))  #返回key對應的值
# print(info.pop('nameda a',None))    #沒有key返回None
# 鍵keys(),值values(),鍵值對items()

# print(info.keys())  #打印全部key,dict_keys(['name', 'age', 'sex']),不是列表類型,屬於迭代類型
#
# for key in info.keys():
#     print(key)                  # 只取key,和默認的同樣
#
# print(info.values())
# for val in  info.values():
#     print(val)                  # 只取值
#
# print(info.items())
for item in info.items():
    print(item[0],item[1])
# 循環

# 其餘方法:
# info={'name':'egon','age':18,'sex':'male'}
# info.fromkeys()
# print(info.get('dadaadadad'))   #輸入不存在的key不報錯,打印None,也能夠本身指定
# print(info.popitem())           #返回key和value

# info.setdefault()
# info.update()

# 補充兩種賦值方式:
# 一:鏈式賦值
# x=10
# y=x
# x=y=z=10
# print(id(x),id(y),id(z))

# 交換兩個變量的值
# m=10
# n=20
# m,n=n,m
# print(m,n)
# 二:從一個數據類型中解壓出咱們想要的值

# t=()

 

做業

#!/usr/bin/env python
# Author:hongjie.gao

menu = {
    '北京':{
        '海淀':{
            '五道口':{
                'soho':{},
                '網易':{},
                'google':{}
            },
            '中關村':{
                '愛奇藝':{},
                '汽車之家':{},
                'youku':{},
            },
            '上地':{
                '百度':{},
            },
        },
        '昌平':{
            '沙河':{
                '老男孩':{},
                '北航':{},
            },
            '天通苑':{},
            '回龍觀':{},
        },
        '朝陽':{},
        '東城':{},
    },
    '上海':{
        '閔行':{
            "人民廣場":{
                '炸雞店':{}
            }
        },
        '閘北':{
            '火車戰':{
                '攜程':{}
            }
        },
        '浦東':{},
    },
    '山東':{},
}
print('輸入q退出程序,輸入B返回上一層')
q=True
while q:
    for i in menu:
        print( i)
    a=input('>:').strip()
    if a == 'q':
        q = False
    elif a == 'B':
        print('已經到頂層了')
    elif a in menu:
        while q:
            for o in menu[a]:
                print(o)
            b=input('>>:').strip()
            if b == 'q':
                q = False
            elif b=='B':
                break
            if b in menu[a]:
                while q:
                    for p in menu[a][b]:
                        print(p)
                    c = input('>>>:').strip()
                    if c == 'q':
                        q = False
                    elif c == 'B':
                        break
                    if c in menu[a][b]:
                        for r in menu[a][b][c]:
                            print(r)
                        z=input('>::')
                        if z == 'q':
                            q=False
                        elif b == 'B':
                            break
                        else:
                            print('我也是有底的')
                    else:
                        print('輸入的地址不存在')
            else:
                 print('輸入的地址不存在')
    else:
        print('輸入的地址不存在')

 

#!/usr/bin/env python
# Author:hongjie.gao
# 簡單購物車,要求以下:
# 實現打印商品詳細信息,用戶輸入商品名和購買個數,則將商品名,價格,購買個數加入購物列表,若是輸入爲空或其餘非法輸入則要求用戶從新輸入  
msg_dic = {
    'A': ['手機', 1000],
    'B': ['汽車', 100000],
    'C': ['電腦', 3000],
    'D': ['服務器', 30000],
    'E': ['杯子',10]
}
# print('輸入q退出程序')
a=[]
username='admin'
password='123'
count=0
ghj=True
while ghj:
    U=input('please input username>>:')
    if U==username:
        count = 0
        while ghj:
            P = input('please input password>>:')
            if P==password:
                print('Welcome to login')
                ghj=False
            else:
                count+=1
                if count==3:
                    print('wrong password')
                    ghj = False
    else:
        count+=1
        if count==3:
            print('wrong username')
            ghj = False
    print('輸入q退出程序')
    while True:
        salary = input('請輸入工資>>:')
        if  salary.isdigit():
            salary=int(salary)
        elif salary=='q':
            exit()
        else:
            print('請輸入數字')
            continue
        while True:
            for key in msg_dic:
                print(key, msg_dic[key])
            choice = input('>>:').strip()
            if choice=='q':
                exit()
            elif choice not in msg_dic:
                print('商品不存在')
                continue
            else:
                a.append( msg_dic[choice])
                print(a)
                if  msg_dic[choice][1] <= salary:
                    salary -= msg_dic[choice][1]
                    print(salary)
                    continue
                else:
                    print('餘額不足')

相關文章
相關標籤/搜索