1.数字:int(整型)
32位机器:-2**31~2**31-1
64位机器:-2**63~2**63-1
float(浮点型)
2.布尔值
真或假
1或0
bool(0)
3.字符串
name = “wanghuafeng”
print(“my name is ”+ name + “and you?”)
万恶的加号,开辟多块内存空间。
4.列表
创建列表:
name_list = ['wanghuafeng', 'alex', 'eric', 'snow', 'radar', 'dc']
取出第一个元素:
name_list[0]
切片
注意:切片顾头不顾尾,并且从左往右
取出第一个和第二个元素:
name_list[0,2]
取后3个元素:
name_list[-3:]
取前3个元素:
name_list[:3]
多次切片:
name_list[:3][:2][0][3]
修改:
name_list[2] = 'git'
插入(一次只能插一个):
name_list.insert(2,'svn')
追加:
name_list.append('lilei')
删除:
name_list.remove('dc')
删除第2个元素
name_list.remove(name_list[1])
删除第2第3个元素
del name_list[1:3]
删除列表
del name_list
打印奇数个元素(步长)
name_list[::2]
判断元素在该列表中:
name_list = ['wanghuafeng', 'alex', 'eric', 'snow', 'radar', 'dc', 2, 2, 2, 3, 4, 5, 6, 7]
if 2 in name_list:
print("2 is in name_list")
统计列表中相同元素个数:
name_list = ['wanghuafeng', 'alex', 'eric', 'snow', 'radar', 'dc', 2, 2, 2, 3, 4, 5, 6, 7]
if 2 in name_list:
num_of_ele = name_list.count(2)
print("%s个2 is /are in name_list" % num_of_ele)
查找元素在列表中的位置
name_list = ['wanghuafeng', 'alex', 'eric', 'snow', 'radar', 'dc', 2, 2, 2, 3, 4, 5, 6, 7]
if 2 in name_list:
num_of_ele = name_list.count(2)
position_of_ele = name_list.index(2)
print("%s个2 is /are in name_list, position is %s" % (num_of_ele,position_of_ele))
找到元素并修改
name_list = ['wanghuafeng', 'alex', 'eric', 'snow', 'radar', 'dc', 2, 2, 2, 3, 4, 5, 6, 7]
if 2 in name_list:
num_of_ele = name_list.count(2)
position_of_ele = name_list.index(2)
name_list[position_of_ele] = 888
print("%s个2 is /are in name_list, position is %s" % (num_of_ele,position_of_ele))
print(name_list)
修改列表中相同的元素
name_list = ['wanghuafeng', 'alex', 'eric', 'snow', 'radar', 'dc', 2, 2, 2, 3, 4, 5, 6, 7]
if 2 in name_list:
num_of_ele = name_list.count(2)
position_of_ele = name_list.index(2)
name_list[position_of_ele] = 999
print("%s个2 is /are in name_list, position is %s" % (num_of_ele,position_of_ele))
print(name_list)
for i in range(name_list.count(2)):
ele_index = name_list.index(2)
name_list[ele_index] = 988
print(name_list)
扩展列表
name1 = ['wanghuafeng', 'alex', 'eric', 'snow', 'radar', 'dc', 2, 2, 2, 3, 4, 5, 6, 7]
name2 = ['zhangsan', 'lisi', 'wangxiao', 2, 2, 3, 4, 5]
name1.extend(name2)
print(name1)
print(name2)
反转列表
name1 = ['wanghuafeng', 'alex', 'eric', 'snow', 'radar', 'dc', 2, 2, 2, 3, 4, 5, 6, 7]name1.reverse()print(name1)
排序
python3中数字和字符串不能一起排序python2中按照ascii码的顺序排序,一般数字在前name1.sort()
取出列表中的元素
name = ['wanghuafeng', 'alex', 'eric', 'snow', 'radar', 'dc', 2, 2, 2, 3, 4, 5, 6, 7取出列表中的3个元素
list1 = name.pop(2)
默认取出最后一个元素
name.pop()
print(name)
print(list1)
列表复制
name = ['wanghuafeng', 'alex', [1, 1, 5, 8, 9], 'eric', 'snow', 'radar', 'dc', 2, 2, 2, 3, 4, 5, 6, 7]
name1 = name.copy()
print(name)
print(name1)
name[0] = 'WANG'
print(name)
print(name1)
嵌套列表
name = ['wanghuafeng', 'alex', [1, 1, 5, 8, 9], 'eric', 'snow', 'radar', 'dc', 2, 2, 2, 3, 4, 5, 6, 7]
name1 = name.copy()
name[0] = 'WANG'
name[2][1] = 88888888
print(name)
print(name1)
name1[2][3] = 99999999
print(name)
print(name1)
深copy和浅copy
浅copy:name.copy默认只拷贝第一层,嵌套的列表不copy,嵌套的列表指向了其它内存地址,copy只是引用了其地址相当于软连接
深copy:name3.deepcopy(name)
import copy
name = ['wanghuafeng', 'alex', [1, 1, 5, 8, 9], 'eric', 'snow', 'radar', 'dc', 2, 2, 2, 3, 4, 5, 6, 7]
name1 = name.copy()
name[0] = 'WANG'
name[2][1] = 88888888
print(name)
print(name1)
name1[2][3] = 99999999
print(name)
print(name1)
浅copy
name2 = copy.copy(name)
print(name2)
深copy
name[2][4] = 222222
name3 = copy.deepcopy(name)
name3[2][4] = 33333333333
print(name)
print(name3)
查看列表长度
print(len(name3))
元组
r = (1, 2, 3, 4, 5, 1, 1, 2)查看类型
print(type(r))
统计元组中1的个数
print(r.count(1))
查找元组中2的位置
print(r.index(2))
字符串
去掉前后空格
user_name = input("user:")
if user_name.strip() == 'wang':
print("Welcome!")
分割
names = " wang,hua,feng"
name5 = names.split(',')
print(name5)
合并
names = " wang,hua,feng"
name5 = names.split(',')
print(name5)
print('|'.join(name5))
判断是否有空格
name = 'wang hua feng'
print('' in name)
首字母大写
name = 'wang hua feng'
print(name.capitalize())
格式化
name = "hello, {name}, it's been a long {age} time since last time spoke..."
name_msg = name.format(name="ahha", age=25)
print(name_msg)
name2 = "haha{0}, dddddssss{1}"
print(name2.format('wang',23))
切片
name = 'wanghuafeng'
print(name[2:8])
填充
name = 'wanghuafeng'
print(name.center(29,'*'))
查找
name = 'wanghuafeng'
print(name.find('a'))
判断是否是数字
age = input("your age:")
if age.isdigit():
age = int(age)
print("age is %s" % age)
else:
print("Invalid date type")
判断是否有数字,但不能有特殊字符
name = 'aaaas2ss2ssd'
print(name.isalnum())
是否以sd结尾
name = 'aaaas2ss2ssd'
print(name.endswith('sd'))
是否以aa开头
name = 'aaaas2ss2ssd'
print(name.startswith('aa'))
大小写转换
name = 'aaaas2ss2ssd'
print(name.upper())
print(name.lower())
算数运算
+ - * / % ** //
取商
print(11/2)
取模
print(11%2)
取商的整数部分
print(13//2)
比较运算
== > < >= <=
赋值运算
= += -= *= /= %= **= //=
逻辑运算
and or not
成员运算
in not in
身份运算
is is not
type(a) is list
位运算
&:按位与
|:按位或
^:按位异或
~:按位取反
<<:左移
>>:右移
计算机中能表示的最小单位,是一个二进制位;计算机中能存储的最小单位,是一个二进制位(bit)
8bit = byte(字节)
1024byte = 1kbyte
1024kbyte = 1mbyte
1024mbyte = 1gb
1024gb = 1T
while循环
循环100次
count = 0
while True:
print("哈哈")
count += 1
if count == 100:
print("结束")
break
50-60之间不打印
count = 0
while True:
count += 1
if count > 50 and count < 60:
continue
print("哈哈 ...%s" % count)
if count == 100:
print("结束")
break
数据字典
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: WangHuafeng
id_db = {
421087198901298697: {
'name': 'radar',
'age' : 22,
'addr':'HuBei',
},
421087154671298697: {
'name': 'snow',
'age': 22,
'addr': 'AnHui',
},
421087133221298697: {
'name': 'fish',
'age': 10,
'addr': 'Shanxi',
},
}
#自动去重,key需唯一
print(id_db)
print(id_db[421087133221298697])
#修改
id_db[421087133221298697]['name'] = "NiuRen"
print(id_db[421087133221298697])
#删除
id_db.pop(421087133221298697)
print(id_db)
id_db[421087154671298697].pop("addr")
print(id_db)
#copy复制
#clear清空
#get获取
v = id_db.get(421087198901298697)
print(v)
#update
dict1 = {
'name':'Bottle',
421087154671298697: {
'name': 'radar',
},
}
id_db.update(dict1)
print(id_db)
print(id_db)
#id_db.items()把字典转换为元组,数据量大时不要使用
print(id_db.items())
dict_values = id_db.values()
dict_keys = id_db.keys()
print(dict_keys)
print(dict_values)
421087154671298697 in id_db #eauals to above has key(x)
id_db.setdefault(421087154671298697,"haha") #取一个值key,如果不存在就设置一个值;如果存在直接设置值
print(id_db)
print(dict.fromkeys([1,2,3,4,5]),'bfgb') #把字典里的所有值都当作key
print(id_db.popitem()) #随机删除,尽量不要用
for k,v in id_db.items(): #效率低,需要有一个字典转换为列表操作
print(k)
print(v)
for key in id_db: #效率高
print(key,id_db[key])
购物车
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: WangHuafeng
#输入工资一次性
salary = input("Input your salary:")
if salary.isdigit():
salary = int(salary)
else:
exit("Invalid date type...")
welcome_msg = 'Welcome to Wang Shopping mall.'.center(50,'-')
print(welcome_msg)
product_list = [
('iphone', 5800),
('Mac Air', 8000),
('xiaomi', 19.9),
('coffee', 30),
('Tesla', 820000),
('Bike', 900),
]
exit_flag = False
print("Product list.".center(50,'-'))
shop_car = []
while not exit_flag: #while exit_flag is not True
for item in enumerate(product_list): #enumerate枚举
#p_name, p_price = product_item
#print(p_name, p_price)
#print(item)
index = item[0]
p_name = item[1][0]
p_price = item[1][1]
print(index,'.',p_name,p_price)
user_choice = input("[q=quit,c=check]What do you want to buy : ")
if user_choice.isdigit(): #肯定选择shopping
user_choice = int(user_choice)
if user_choice < len(product_list):
p_item = product_list[user_choice]
if p_item[1] <= salary: #买得起
shop_car.append(p_item) #加入购物车
salary -= p_item[1] #扣钱
print("Added [%s] into shop car,you current balance is \033[31;1m][%s]\033[0m" % (p_item, salary))
else:
print("Your balance is [%s], cannot afford this." % salary)
else:
if user_choice == 'q' or user_choice == 'quit':
print("purchased products as below".center(40,'*'))
for item in shop_car: #打印已购买的商品
print(item)
print("END".center(40,'*'))
print("Your balance is \033[41;1m][%s]\033[0m" % salary)
print("Bye")
exit_flag = True
elif user_choice == 'c' or user_choice == 'check':
print("purchased products as below".center(40, '*'))
for item in shop_car: # 打印已购买的商品
print(item)
print("END".center(40, '*'))
print("Your balance is [%s]" % salary)