Python基本数据类型
运算符
2、比较运算:
3、赋值运算:
4、逻辑运算:
5、成员运算:
基本数据类型
int(整型)
在64位系统上,整数的位数为64位,取值范围为-2**63~2**63-1,即-9223372036854775808~9223372036854775807
“hello world”
- 移除空白
- 分割
- 长度
- 索引
- 切片
1
2
3
|
name_list = [ 'alex' , 'seven' , 'eric' ]
或 name_list = list ([ 'alex' , 'seven' , 'eric' ])
|
基本操作:
- 索引
- 切片
- 追加
- 删除
- 长度
- 切片
- 循环
- 包含
1
2
3
|
ages = ( 11 , 22 , 33 , 44 , 55 )
或 ages = tuple (( 11 , 22 , 33 , 44 , 55 ))
|
- 索引
- 切片
- 循环
- 长度
- 包含
1
2
3
|
person = { "name" : "mr.wu" , 'age' : 18 }
或 person = dict ({ "name" : "mr.wu" , 'age' : 18 })
|
常用操作:
- 索引
- 新增
- 删除
- 键、值、键值对
- 循环
- 长度
其他
1
2
3
|
li = [ 11 , 22 , 33 , 44 ]
for item in li:
print item
|
1
2
3
|
li = [ 11 , 22 , 33 ]
for k,v in enumerate (li, 1 ):
print (k,v)
|
1
2
3
4
5
6
7
8
|
print range ( 1 , 10 )
# 结果:[1, 2, 3, 4, 5, 6, 7, 8, 9] print range ( 1 , 10 , 2 )
# 结果:[1, 3, 5, 7, 9] print range ( 30 , 0 , - 2 )
# 结果:[30, 28, 26, 24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4, 2] |
练习题
一、元素分类
有如下值集合 [11,22,33,44,55,66,77,88,99,90…],将所有大于 66 的值保存至字典的第一个key中,将小于 66 的值保存至第二个key的值中。
即: {‘k1’: 大于66的所有值, ‘k2’: 小于66的所有值}
功能要求:
- 要求用户输入总资产,例如:2000
- 显示商品列表,让用户根据序号选择商品,加入购物车
- 购买,如果商品总额大于总资产,提示账户余额不足,否则,购买成功。
- 附加:可充值、某商品移除购物车
1
2
3
4
5
6
|
goods = [
{ "name" : "电脑" , "price" : 1999 },
{ "name" : "鼠标" , "price" : 10 },
{ "name" : "游艇" , "price" : 20 },
{ "name" : "美女" , "price" : 998 },
] |
五、用户交互,显示省市县三级联动的选择
1
2
3
4
5
6
7
8
9
10
11
12
13
|
dic = {
"河北" : {
"石家庄" : [ "鹿泉" , "藁城" , "元氏" ],
"邯郸" : [ "永年" , "涉县" , "磁县" ],
}
"河南" : {
...
}
"山西" : {
...
}
} |
li = [“alec”, ” aric”, “Alex”, “Tony”, “rain”]
tu = (“alec”, ” aric”, “Alex”, “Tony”, “rain”)
dic = {‘k1’: “alex”, ‘k2’: ‘ aric’, “k3”: “Alex”, “k4”: “Tony”}
for i in li:
b=i.strip()
if (b.startswith(“a”) or b.startswith(“A”)) and b.endswith(“c”):
print(b)
for i1 in tu:
c=i1.strip()
if (c.startswith(‘a’)or c.startswith(‘A’)) and c.endswith(‘c’):
print(c)
for i2 in dic:
d=dic[i2].strip()
if (d.startswith(‘a’) or d.startswith(‘A’)) and d.endswith(‘c’):
print (d)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
第四题购物车答案 shopping_cart = []
salary = 2000
goods = [
{ "name" : "电脑" , "price" : 3000 },
{ "name" : "鼠标" , "price" : 103 },
{ "name" : "游艇" , "price" : 200000 },
{ "name" : "美女" , "price" : 998 },
] for i in enumerate (goods):
index = i[ 0 ] #序号
p_list = i[ 1 ] #商品清单
p_name_list = p_list.get( 'name' ) #商品名称列表
p_price_list = p_list.get( 'price' ) #商品价格列表
print (index, ":" ,p_name_list,p_price_list)
while True :
choice = input ( "please enter your choice:" ).strip()
if choice.isdigit(): #如果选择为正整数
choice = int (choice) #输入为数字
if choice < len (goods) and choice > = 0 : #选择小于列表长度大于0时
p_item = goods[choice] #加入购物车
p_name = p_item.get( 'name' )
p_monery = p_item.get( 'price' )
if p_monery < = salary: #如果商品价格小于等于余额
shopping_cart.append(p_item) #加入购物车
salary - = p_monery #结算
print ( "购买的商品\033[32m:%s\033[0m已加入到购物车" .center( 40 , '-' ) % p_name)
for p_item in shopping_cart:
print (p_name,p_monery)
print ( "您的余额为\033[31m:%s\033[0m元" % salary)
else :
print ( "您的余额不足,差%s元" % ( abs (p_monery - salary)))
else :
print ( "没有此件商品!" )
else :
print ( "参数错误" )
if choice = = "q" or choice = = "quit" :
cost = 0
print ( "您购买的商品清单如下:" )
for p in shopping_cart:
print (p_name, p_monery)
cost + = p_monery
print ( "\033[32m消费总金额:" ,cost, "元\033[0m" )
print ( "\033[32m您的余额为:" ,salary, "元\033[0m" )
break
|
il = input(“请输入金额:”)
salary = int(il)
goods = [
{“name”: “电脑”, “price”: 3000},
{“name”: “鼠标”, “price”: 103},
{“name”: “游艇”, “price”: 200000},
{“name”: “美女”, “price”: 998},
]
for i in goods:
print(i[“name”], i[“price”])
#加车
while True:
shop = input(“请输入商品名称:”)
for item in goods:
if shop in item[“name”]:
name = item[“name”]
if name in shopping_cart.keys():
shopping_cart[name][“num”] = shopping_cart[name][“num”] + 1
else:
shopping_cart[name] = {“price”: item[“price”], “num”:1}
stop = input(“是否结账(Y/N):”)
if stop.upper() == “Y”:
break
#计算总价
totel = 0
for i, j in shopping_cart.items():
signle_sum = j[“price”] * j[“num”]
totel = totel + signle_sum
if totel > salary:
print(“穷逼”)
else:
ling = salary – totel
print(“购买成功!”)
print(“支付金额:%d,购买金额:%d,找回金额:%d” %(salary, totel, ling))
#9楼 2017-05-23 10:31 songkunhuang
print (“练习题4”)
def daYinShangPinLieBiao(good):
“””打印商品列表
按照预设格式打印商品列表”””
print (“序号\t”, “商品\t”, “价格\t” )
for key, shangpin in enumerate(good, 0):
print ((key),”\t”, (good[key][“name”]),”\t”, good[key][“price”])
def daYinGouWuChe(gouwu):
“””打印购物车内容”””
heji = 0
# print (gouwu)
print (“序号\t”, “商品\t”, “价格\t” , “数量\t”)
for key, shangpin in enumerate(gouwu, 0):
print ((key),”\t”, (gouwu[key][0]),”\t”, gouwu[key][1],”\t”, gouwu[key][2])
heji += gouwu[key][1] * gouwu[key][2]
print (“合计:”, heji, “元”)
return heji
#商品购买
def shangPinGouMai(gouwu):
while True:
daYinShangPinLieBiao(goods)
print (“退出请直接回车”)
xu_hao = (input(“请选择购买商品序号: “))
if xu_hao == “”:
return gouwu
shu_liang = (input (“请输入购买的数量: “))
gouwu +=[[goods[int(xu_hao)][“name”], goods[int(xu_hao)][“price”], int(shu_liang)]]
return gouwu
#结账及商品价格判断
def jieZhang():
heji = daYinGouWuChe(gouWuChe)
global yong_hu_zong_zi_chan
if heji > yong_hu_zong_zi_chan:
print (“余额不足!”)
print (“选择1进行充值”)
print (“选择2移除部分商品”)
num = input (“请输入选择(1或者2): “)
if num == “1”:
yong_hu_zong_zi_chan = chongZhi(yong_hu_zong_zi_chan)
elif num == “2”:
yuChuShangPin(gouWuChe)
jieZhang()
else:
print (“商品购买成功”)
#附加功能:充值
def chongZhi(zichan):
print (“您当前余额为:”, zichan, “元”)
num = int(input(“请输入您的充值金额: “))
zichan += num
print (“您当前余额为: “, zichan)
return zichan
#某商品从购物车的移除
def yuChuShangPin(gouwu):
daYinGouWuChe(gouwu)
num = int(input (“请输入您需要移除的商品序号: “))
del gouwu[num]
jieZhang()
#商品预设列表
goods = [
{“name”: “电脑”, “price”: 1999},
{“name”: “鼠标”, “price”: 10},
{“name”: “游艇”, “price”: 20},
{“name”: “玩具车”, “price”: 998},
]
#输入用户总资产
yong_hu_zong_zi_chan = int(input(“请输入用户初始总资产: “))
#购物车初始状态
gouWuChe = [
[“示例”, 200, 0],
]
heji = 0
# daYinShangPinLieBiao(goods)
# daYinGouWuChe(gouWuChe)
shangPinGouMai(gouWuChe)
# daYinGouWuChe(gouWuChe)
jieZhang()
1
2
3
4
5
6
7
8
9
10
11
|
a = [ 11 , 22 , 33 , 44 , 55 , 66 , 77 , 88 , 99 , 90 ]
b = {
"key1" :[],
"key2" :[]
} for i in a:
if i > 66 :
b[ "key1" ].append(i)
elif i < 66 :
b[ "key2" ].append(i)
print (b)
|
第二题:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
li = [ "alec" , " aric" , "Alex" , "Tony" , "rain" ]
tu = ( "alec" , " aric" , "Alex" , "Tony" , "rain" )
dic = { 'k1' : "alex" , 'k2' : ' Aric' , "k3" : "Alex" , "k4" : "Tony" }
for a in range ( len (li)):
li[a] = li[a].replace( " " , "")
print (li)
tu = list (tu)
for b in range ( len (tu)):
tu[b] = tu[b].replace( " " , "")
tu = tuple (tu)
print (tu)
for c in dic:
dic[c] = dic[c].replace( " " , "")
print (dic)
for a1 in li:
if (a1.startswith( "a" ) or a1.startswith( "A" )) and a1.endswith( "c" ):
print (a1)
for b1 in tu:
if (b1.startswith( "a" ) or b1.startswith( "A" )) and b1.endswith( "c" ):
print (b1)
for c1 in dic:
c2 = dic[c1].strip()
if (c2.startswith( "a" ) or c2.startswith( "A" )) and c2.endswith( "c" ):
print (c2)
|
第三题:
1
2
3
4
5
6
|
a = [ "手机" , "电脑" , '鼠标垫' , '游艇' ]
for i , a1 in enumerate (a, 1 ):
print (i , a1)
b = input ( "请输入商品编号:" )
b1 = int (b)
print (a[b1 - 1 ])
|
#17楼 2017-11-30 12:42 bird’linux
li = [“alec”, ” aric”, “Alex”, “Tony”, “rain”]
tu = (“alec”, ” aric”, “Alex”, “Tony”, “rain”)
dic = {‘k1’: “alex”, ‘k2’: ‘ aric’, “k3”: “Alex”, “k4”: “Tony”}
def Transform(args):
new_list=[]
if (True if type(args)==list or type(args)==tuple else False):
arg=list(args)
for i in arg:
i=i.strip()
if i.capitalize().startswith(‘A’) and i.endswith(‘c’):
new_list.append(i)
print(“%s符合条件的元素有:”%str(args),end=’ ‘)
for j in new_list:
print(j,end=’,’)
print()
else:
new_dic={}
for k in args:
args[k]=args[k].strip()
if args[k].capitalize().startswith(‘A’) and dic[k].endswith(‘c’):
print(“%s符合条件的元素有:”%str(args),args[k])
for i in [“li”,”tu”,”dic”]:
Transform(eval(i))
#18楼 2017-11-30 12:46 bird’linux
tu = (“alec”, ” aric”, “Alex”, “Tony”, “rain”)
dic = {‘k1’: “alex”, ‘k2’: ‘ aric’, “k3”: “Alex”, “k4”: “Tony”}
def Transform(args):
new_list=[]
if (True if type(args)==list or type(args)==tuple else False):
arg=list(args)
for i in arg:
i=i.strip()
if i.capitalize().startswith(‘A’) and i.endswith(‘c’):
new_list.append(i)
print(“%s符合条件的元素有:”%str(args),end=’ ‘)
for j in new_list:
print(j,end=’,’)
print()
else:
new_dic={}
for k in args:
args[k]=args[k].strip()
if args[k].capitalize().startswith(‘A’) and dic[k].endswith(‘c’):
print(“%s符合条件的元素有:”%str(args),args[k])
for i in [“li”,”tu”,”dic”]:
Transform(eval(i))
运算符
2、比较运算:
3、赋值运算:
4、逻辑运算:
5、成员运算:
基本数据类型
int(整型)
在64位系统上,整数的位数为64位,取值范围为-2**63~2**63-1,即-9223372036854775808~9223372036854775807
“hello world”
- 移除空白
- 分割
- 长度
- 索引
- 切片
1
2
3
|
name_list = [ 'alex' , 'seven' , 'eric' ]
或 name_list = list ([ 'alex' , 'seven' , 'eric' ])
|
基本操作:
- 索引
- 切片
- 追加
- 删除
- 长度
- 切片
- 循环
- 包含
1
2
3
|
ages = ( 11 , 22 , 33 , 44 , 55 )
或 ages = tuple (( 11 , 22 , 33 , 44 , 55 ))
|
- 索引
- 切片
- 循环
- 长度
- 包含
1
2
3
|
person = { "name" : "mr.wu" , 'age' : 18 }
或 person = dict ({ "name" : "mr.wu" , 'age' : 18 })
|
常用操作:
- 索引
- 新增
- 删除
- 键、值、键值对
- 循环
- 长度
其他
1
2
3
|
li = [ 11 , 22 , 33 , 44 ]
for item in li:
print item
|
1
2
3
|
li = [ 11 , 22 , 33 ]
for k,v in enumerate (li, 1 ):
print (k,v)
|
1
2
3
4
5
6
7
8
|
print range ( 1 , 10 )
# 结果:[1, 2, 3, 4, 5, 6, 7, 8, 9] print range ( 1 , 10 , 2 )
# 结果:[1, 3, 5, 7, 9] print range ( 30 , 0 , - 2 )
# 结果:[30, 28, 26, 24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4, 2] |
练习题
一、元素分类
有如下值集合 [11,22,33,44,55,66,77,88,99,90…],将所有大于 66 的值保存至字典的第一个key中,将小于 66 的值保存至第二个key的值中。
即: {‘k1’: 大于66的所有值, ‘k2’: 小于66的所有值}
功能要求:
- 要求用户输入总资产,例如:2000
- 显示商品列表,让用户根据序号选择商品,加入购物车
- 购买,如果商品总额大于总资产,提示账户余额不足,否则,购买成功。
- 附加:可充值、某商品移除购物车
1
2
3
4
5
6
|
goods = [
{ "name" : "电脑" , "price" : 1999 },
{ "name" : "鼠标" , "price" : 10 },
{ "name" : "游艇" , "price" : 20 },
{ "name" : "美女" , "price" : 998 },
] |
五、用户交互,显示省市县三级联动的选择
1
2
3
4
5
6
7
8
9
10
11
12
13
|
dic = {
"河北" : {
"石家庄" : [ "鹿泉" , "藁城" , "元氏" ],
"邯郸" : [ "永年" , "涉县" , "磁县" ],
}
"河南" : {
...
}
"山西" : {
...
}
} |