python 老師布置的作業 自己實踐的結果
一、回顧內容
1、頂部
解釋器
編碼(2.7默認ascii,3.6默認utf-8)
2、print("hello")2.7
print "hello" 3.6
3、編碼之間的關系
ascii 萬國碼 (最少兩個字節unicode) gbk utf-8
1個字節 最少兩個字節 2個 中文3個字節
4、命名
首字母不是數字
變量名不能是關鍵字
數字字母下劃線
變量存在的意義-->方便調用
5、條件
if條件:
pass
elif 條件:
pass
else:
pass
注意縮進,冒號
6、while
while 條件:
pass 每次條件被判斷成立無限執行
continue 中止此次循環,從新開始循環
break 終止所有循環
7、運算符
*=
+=
-=
/=
%= 取余
一個等號是賦值,兩個等號才是等于
num = 13
zq = num % 2 #余數
if zq == 0:
# 偶數
else:
# 奇數
in 判斷元素在不在列表里面
num = “zq”
li = ["zq","zw"]
if num in li:
print('zai')
else:
print('buzai')
再加一個判斷是否以z開頭的
if num in li and num.startwith('z')
# and 可以在加一個條件
8、基本的數據類型
int,整形
n = 123
n = int(123) # int類的 ——init——
s = "123"
m = int(s) #字符串類型轉換整形
整形有個長度限制,32位電腦正負2的31次方....(python2.7)
python3.6里面沒有long了 不管多長的數字都是int。2.7里面超過范圍會轉換成長整形
s = "132sdfg" #字符串里面只包含數字時才能轉換
m = int(s)
str,字符串
s = "zq"
s = str("zq")
a = 123
m = str(a) 把一個數字轉換成字符串
=======
bytes =》 字節類型
str =》 字符串
目的:字節轉換成字符串
b = 字節類型的對象
# m = bytes(b)
m = str(b,encoding=“utf-8”)
首字母變大寫 去空格 變大小寫 替換 是否為數字、字母 開頭結尾 查找
個數 格式化 編碼解碼 居中左飄右飄 連接
li = ["zq","ss"]
l1 = "_".join(li)
l1對應的值 zq_ss
list,列表
i = [11,22,33]
i = list(11,22,33) 這是錯誤的
i = list([11,22,33]) list 是個類名 后面小括號里面的元素只能有一個但是里面必須用中括號加序列
=====
t = (11,22,33)
i = list([t]) 這是錯誤的 出來的結果是這樣的[(11,22,33)]
i = list(t) 這是正確的
t = [11,22,33]
t = [11,22,33,]這兩種是樣的
列表的公共功能:
索引
切片
for
長度
enumerate
刪除 del li[0]
del li[0:2]
特有的功能:
翻轉
排序
追加
插入
索引位置
刪除
pop
擴展
清楚
tuple:
t = (11,22,33,44)
t = tuple(可迭代的對象)
li = (11,22,33,44)
l1 = tuple(li)
公共功能:
索引
切片
for
長度
enumerate
in
特有的功能:
個數
索引位置
特性:不能修改....
dict:
d = {"k":123,"k2":65}
d2 = {
"k":123,
"k2":156
}
li = [1,2,3,4]
字典: key:10 遞加
value: 列表的元素
dic = []
for i,j in enumerate(li,10):
new_dict = dict(enumerate(li,10))
公共功能:
索引
增加 dic[key]=vlue
刪除
for
長度
in
特有的功能:
項 鍵 值 get haskey--》is
update
fromkey
字符串,字節
str
bytes
a = "張強" gbk編碼的字節
b = bytes(a,encoding="gbk") type(b)=> bytes
c = str(b,encoding="gbk")
int優化機制
a = 123
b = 123
id(a)
相同,因為有優化,-5~257
a = 123
b = a
二、作業
1、元素分類
有如下值集合【11,22,33,44,55,66,77,88,99,90】,將所有大于66的值保存至字典的第一個key中,將小于66的值保存至第二個key的值中。
既:{k1:大于66的所有值,k2:小于66的所有值}
第一種方法
# li = [11,22,33,44,55,66,77,88,99,90]
#字典
# {
# "k1":[11,22,33,44,55],
# "k2":[66,77,88,99]
# }
#code
li = [11,22,33,44,55,66,77,88,99,90]
l1 = []
l2 = []
for i in li:
if i <= 66:
l1.append(i)
else:
l2.append(i)
temp = {"k1":l1, "k2":l2}
print(temp)
第二種方法
dic = {
"k1":[],
"k2":[]
}
li = [11,22,33,44,55,66,77,88,99,90]
for i in li:
if i <= 66:
dic['k1'].append(i)
else:
dic['k2'].append(i)
print(dic)
2、查找
查找列表中元素,移動空格,并查找以a或A開頭并且以c結尾的所有元素。
h=["alec","aric","Alex","Tony","rain"]
tu=["alec","aric","Alex","Tony","rain"]
dic=['k1':"alec",'k2':"aric",'k3':"Alex",'k4':"Tony",'k5':"rain"]
li = ["aleb","aric"," Alex","Tony","rain"]
for i in li:
new_i = i.strip()
if new_i.startswith('a') or new_i.startswith('A') and new_i.endswith('c'):
print(i)
換成元組序列也一樣
li = ("aleb","aric"," Alex","Tony","rain")
for i in li:
new_i = i.strip()
if new_i.startswith('a') or new_i.startswith('A') and new_i.endswith('c'):
print(i)
dic={'k1':"alec",'k2':"aric",'k3':"Alex",'k4':"Tony",'k5':"rain"}
for i in dic.values():
new_i = i.strip()
if new_i.startswith('a') or new_i.startswith('A') and new_i.endswith('c'):
print(i)
3、輸出商品列表,用戶輸入序號,顯示用戶選中的商品
商品li=["手機","電腦","鼠標","游艇"]
li = ["手機","電腦","鼠標","游艇"]
# for i,j in enumerate(li):
# print(i,j)
for i,j in enumerate(li):
print(i+1,j)
num = input('num:')
num = int(num)
len_i = len(li)
# if num >0 and num < 5:
if num > 0 and num <= len_i:
good = li[num-1]
print(good)
else:
print("商品不存在")
5、用戶交互,顯示省市縣三級聯動的選擇
dic = {
"河北":{
"石家莊": ["上單","打野","下路"],
"邯鄲" : ["地方","對方","好人"]
},
"河南":{
"鄭州": ["上上","下下","左左"],
"開封" : ["悠悠","多少","東方"]
},
"山西":{
"太原": ["一一","二二","三三"],
"長治" : ["四四","嗚嗚","溜溜"]
}
}
#循環輸出所有的省
for x in dic:
print(x)
i1 = input("請輸入省份:")
a = dic[i1]
#循環輸出所有的市
for j in a:
print(j)
i2 = input("請輸入省份:")
b = dic[i1][i2]
#print(b)#列表類型
for z in b:
print(z)
4、購物車
功能要求:
a.要求用戶輸入總資產,例如:2000
b.顯示商品列表,讓用戶根據序號選擇商品,加入
購物車
c.購買,如果商品總額大于總資產,提示賬戶余額
不足,否則,購買成功。
d.附加:可充值、某商品移除購物車
goods = [
{"name":"電腦","price":1999},
{"name":"鼠標","price":10},
{"name":"游艇","price":20},
{"name":"美女","price":998}
]
allset = 0
car_list = []
# {
# "電腦":{'price':"單個商品價格","num":"購買多少"}
# }
i1 = input("請輸入總資產:")
allset_all = int(i1)
for i in goods:
#i, 每一個列表的元素,字典
print(i['name'],i['price'])
while True:
i2 = input('請選擇商品(Y/y結算):')
if i2.lower() == "y":
break
for j in goods:
if j['name'] == i2:
# print(j)
car_list.append(j)
print(car_list)
# 結算
all_price = 0
for item in car_list:
p = item['price']
all_price = all_price + p
print(allset_all,all_price)
if all_price > allset_all:
print('不行')
else:
print('行')
#總資產
asset_all = 0
i1 = input("請輸入總資產:")
asset_all = int(i1)
goods = [
{"name":"電腦","price":1999},
{"name":"鼠標","price":10},
{"name":"游艇","price":20},
{"name":"美女","price":998}
]
for i in goods:
# {"name":"電腦","price":1999}
print(i['name'],i['price'])
car_dict = {}
# car_dict = {
# "電腦":{"price":"單價", "num":123}
# }
while True:
i2 = input("請選擇商品(Y/y結算):") # 電腦
if i2.lower() == "y":
break
# 循環所有的商品,查找需要的商品
for item in goods:
if item['name'] == i2:
name = item['name']
# 判斷購物車是否已經有該商品,有,num+1
if name in car_dict.keys():
# pass
car_dict[name]['num'] = car_dict[name]['num'] + 1
else:
car_dict[name] = {"num":1,"single_price": item['price']}
print(car_dict)
# {
# '電腦': {'num': 6, 'single_price': 1999} 6*1999
# '鼠標': {'num': 3, 'single_price': 10}} 3*10
# }
all_price = 0
for k,v in car_dict.items():
n = v['single_price']
m = v['num']
all_sum = m*n
all_price = all_price + all_sum
if all_price > asset_all:
print('買不起')
else:
從第一個print往后一格效果完全不一樣
#總資產
asset_all = 0
i1 = input("請輸入總資產:")
asset_all = int(i1)
goods = [
{"name":"電腦","price":1999},
{"name":"鼠標","price":10},
{"name":"游艇","price":20},
{"name":"美女","price":998}
]
for i in goods:
# {"name":"電腦","price":1999}
print(i['name'],i['price'])
car_dict = {}
# car_dict = {
# "電腦":{"price":"單價", "num":123}
# }
while True:
i2 = input("請選擇商品(Y/y結算):") # 電腦
if i2.lower() == "y":
break
# 循環所有的商品,查找需要的商品
for item in goods:
if item['name'] == i2:
name = item['name']
# 判斷購物車是否已經有該商品,有,num+1
if name in car_dict.keys():
# pass
car_dict[name]['num'] = car_dict[name]['num'] + 1
else:
car_dict[name] = {"num":1,"single_price": item['price']}
print(car_dict)
# {
# '電腦': {'num': 6, 'single_price': 1999} 6*1999
# '鼠標': {'num': 3, 'single_price': 10}} 3*10
# }
all_price = 0
for k,v in car_dict.items():
n = v['single_price']
m = v['num']
all_sum = m*n
all_price = all_price + all_sum
if all_price > asset_all:
print('買不起')
else:
print('可以')