新手Python学习记录Day2

模块库

标准库

sys

import sys
print(sys.path) #打印出的目录是python全局的环境变量,表示导入该模块时系统所进行搜索的目录位置
print(sys.argv) #打印出的是该脚本所在的绝对路径位置
print(sys.argv[2]) #取列表中某一特定数据

os

import os

cmd_dir = os.system("dir") #查看当前路径的文件目录
print("--->",cmd_dir) #os输出的是直接显示结果,不保存结果

cmd_dir2 = os.popen("dir").read()
print("--->",cmd_dir2)
os.mkdir("new_dir") #创建多极目录 #失败

自定义库

#自己创建模块,再调用,用import
import login #可直接运行,但必须要在同一目录
#运行后生成了一个缓存文件夹__pycache__,内含文件login.cpython-35
#pyc文件是预编译后的自解码文件

字符串运算

三元运算

d = a if a>b else c
'''
条件为真则d=a
条件为假则d=c
'''
#二进制和字符串转换
'&20'.encode('utf-8') #字符串转二进制
b'\xe2\x82\xac20'.decode('utf-8') #二进制转字符串
print(mse.encode(encoding="utf-8"))
#字符串操作
name = "Zhangsan"
name.capitalize() #首字母大写
name.count("a") #字符串中几个a
name.center(50,"-") #排在中间,两边被"-"填充
name.endswith("ex") #判断字符串是否以此结尾
words= "my name is ..."
words.find("name") #得出该字符串的起始位置
print(words[words.find("name"):]) #输出name后的所有内容

words2="my \tname is {name}, and {age} years old"
print(words2.format(name="zhangsan",age=20)) #format
print(words2.format_map({"name":"zhangsan","age":20})) #字典

"ab23$".isalnum() #无特殊字符
"abA".isalpha() #是否纯字母

"1.23".isdecimal() #是否数字
"333.1".isnumeric() #是否只有数字符号

"=sa".isidentifier() #是否是一个合法的标识符

"Is Title".istitle() #是否单词的首字母都大写
"is title".title() #将首字母都大写
'is Title'.swapcase() #大写变小写,小写变大写

"zhangsan".upper()
"ZHANGSAN".lower()

print('\nans'.lstrip()) #去掉left的空格
print(' ans\n'.strip()) #去掉两边空格

p = str.maketrans('abcdef','123456') #自定义字母对应的数字,编写密码
print('zhang san'.translate(p))#根据对应解密码

print('zhang san'.replace('s','S',1)) #表示只替换一个

print('zhang san').rfind('s')) #找到最右边起的第一个的下标

print("+".join(['1','2','3'])) #得到1+2+3
print('1+2+3+4'.split('+')) #去除+,为了得到纯数字
"1 2 3 4".split() #按照空格分成一个列表 [1,2,3,4]
"1+2+\n3+4".splitlines()

'zero'.zfill(20) #不够的用0填充

列表

插入列表

names.append("Jiayi") #加至末尾
names.insert(1,"Yier") #表示确定的位置
names[1] = "change" #重新赋值

删除列表

names.remove("Yier")
del names[1]
names.pop(2) #如果不输入下标,则表示删除最后一个
names.clear() #清空列表所有内容

查询列表

print(names.index("ZhangSan"))
print(names.count("Lisi"))

names = ["ZhangSan","Lisi","Wangwu"]
print(names)
print(names[0])
print(names[0:2]) #切片,不包括结束位置[0,2)
print(names[-1]) #取的是最后一个值
print(names[0:]) #表示从头取道尾

其他操作

names.reverse() #列表反转
names.sort() #列表自动排序

names.extend(names2) #合并列表
names2 = [1,2,[3,3],4,5]
names3 = names2.copy() #浅copy,浅层的copy不会被更改,但深层的是储存的地址,因此names2改变后,names3也会改变
names2[1] = "a"
names2[2][0] = "b"
print(names2)
print(names3)

#为了解决这个问题,可以使用deepcopy,使得两个列表绝对独立
import copy
names3.copy.deepcopy(names2)

作业

程序:购物车程序
需求:
启动程序后,让用户输入工资,然后打印商品列表
允许用户根据商品编号购买商品
用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒
可随时退出,退出时,打印已购买商品和余额

goods = [
    ('IPhone',5800),
    ('Mac Pro',12000),
    ('Starbuck Latte',31),
    ('Bike',800),
]
salary = (input("Your salary...:"))
if salary.isdigit(): #如果强转会报错,所以用判断
    salary=int(salary)

'''
    for index,item in enumerate(goods):
        print(index,item)
'''
buy = []
while True:
    for item in goods:
        print(item)
    
    user_choice = input("You want...")
    if user_choice.isdigit():
        user_choice = int(user_choice)
        if user_choice < len(goods) and user_choice >=0:
            p_item = goods[user_choice]
            if p_item[1] <= salary:
                buy.append(p_item)
                salary -= p_item[1]
                print("Added %s into shopping cart, your current balance is \033[31;1m%s\033[0m"%(p_item,salary)) #高亮显示, 31红色,32绿色;41背景红色,42背景绿色 IDLE失败
            else:
                print("No enough money")
    if user_choice == "q":
        break
while True:
    for i in goods:
        print(i.index(i)+1,".  ",i[0],"  ",i[1]) #报错
    j = goods.index(order)
    order = input("You want...:")
    if order.isdigit():
        order = int(order)
        if order < len(goods) and order > 0:
            item = goods[order]
            if item[1] <= salary:
                break
    elif order=="q":
        break
    if item[1] <= salary:
        buy.append(i)
        salary = salary - item[1]
        print("You have bought:",buy,"\nYour balance:",salary)
    else:
        print("No enough money")

猜你喜欢

转载自blog.csdn.net/weixin_38667944/article/details/87924556