1.模块
模块sys:
import sys
print(sys.path)#打印环境变量
print(sys.argv)#打印脚本文件的绝对路径
print(sys.argv[2])
模块os
import os
cmd_res1=os.system('dir')#查看当前目录,不保存结果
cmd_res2=os.popen('dir').read()#读取结果
print('-->',cmd_res2)
os.mkdir('new_dir')#创建模块
2.数据类型
三元运算:
a, b, c = 1, 3, 5
d = a if a > b else c
二进制:01
八进制:01234567
十进制:0123456789
十六进制:0123456789ABCDEF
字符串与bytes类型的转换:
msg='我爱北京'
msg_1=msg.encode(encoding='utf-8')
msg_2=msg_1.decode('utf-8')
3.列表list的常用方法
names=['Alice','Jack','Tom','Tony','Alisa']
print(names[0:-1:2])#切片,从左往右隔1行取
names.append('Mike')#在末尾添加
names.insert(1,'Helen')#在指定位置插入
names[2]='Rose'#更新
names.remove('Alice')#删除
del names[0]#删除
names.pop()#删除尾部元素,出栈
names.clear()#清空列表
name.reverse()#反转列表
names.sort()#ASCII码排序
names.extend(names2)#跟names2合并
names.index('Jack')#返回Jack的位置
names[names.index('Jack')]#返回Jack字符串
names.count('Jack')#统计Jack的次数
names2不一定根据names的变化而改变。
names2=names.copy()
names2=['Alice','Jack',['Tom','Alisa']]#不变
names2[2][0]='tom'#变
names3=copy.deepcopy(names)#names3完全克隆names
浅copy三种方法:联合账号的例子
names1=copy.copy(names)
names1=names[:]
names=list(names)
for循环:
for i in names:
print(i)
4.元组tuple:只有count()和index()方法,只能查询不能修改。
names=('Alex','Jack')
练习:购物车程序。要求:
- 启动程序后,让用户输入工资,然后打印商品列表
- 允许用户根据商品编号购买商品
- 用户选择商品后检测余额是否足够,足够就直接扣款,否则就提醒
- 可随时退出,退出时打印已购买商品和余额
product_list = [('iphone', 5800),
('mac pro', 9800),
('bike', 800),
('watch', 10600),
('coffee', 31),
('alex python', 120)]
shopping_list=[]
salary = input('Input your salary:')
if salary.isdigit():#判断输入的工资是数字?
salary = int(salary)
while True:
for index,item in enumerate(product_list):#打印商品编号和信息
print(index, item)
user_choice=input('Which do you want to buy?')
if user_choice.isdigit():
user_choice=int(user_choice)
if user_choice<len(product_list) and user_choice>=0:#输入编号范围
p_item=product_list[user_choice]#存储商品信息(名称,价格)
if p_item[1]<=salary:
shopping_list.append(p_item)
salary-=p_item[1]
print('Added %s into shopping cart,your current balance is %s'%(shopping_list,salary))
else:
print('Your salary is only %s and not enough.m'%salary)
else:
print('Product code [%s] is not exist.'%user_choice)
elif user_choice=='q':
print('---shopping list---')
for p in shopping_list:
print(p)
print('Your current balance:',salary)
exit()
else:
print('invalid option')