python第二课

import sys
print(sys.path)  # 打印环境变量
print(sys.argv[2])  # 打印相对路径

import os
os.system("dir")  # 执行命令,不保存结果
cmd_res = os.popen("dir").read()
print("-->", cmd_res)
os.mkdir("new_dir")  # 创建当前路径目录

将写好的程序放入site-packages即可直接用其他程序调用。

.pyc 是什么?

python和java/c#一样,也是一门基于虚拟机的语言。

当我们在命令行中输入python hello.py时,其实是激活了python的“解释器”,告诉“解释器”:你要开始工作了。

可是在“解释”之前,其实执行的第一项工作和java一样,是编译。我们在用eclipse之类的IDE时,将这两部给融合成了一部而已。其实python也一样,当我们执行python hello.py时,他也一样执行了这么一个过程,所以我们应该这样来描述python,python是一门先编译后解释的语言。

 

数据类型

1、数字

int(整型) long(长整型,python3里没这个类型)float(浮点型)complex(复数)

2、布尔值 1或0(真或假)

3、字符串

三元运算

a,b,c = 1,3,5

d = a if a >b else c

进制

二进制、八进制、十进制、十六进制

二转十六 取四合一,不够前部位整数,后补位小数。BH表示11,H表示16进制。或者0xB也表示16进制。

编码转换

msg = '我爱北京天安门'
print(msg)
print(msg.encode(encoding='utf-8').decode(encoding="utf-8"))

列表

names = ["ZhangYang", "Guyun", "ChenRonghua", "Xiangpeng", "XuLiangChen"]
print(names)
print(names[0], names[2])
print(names[1:3])  # 切片
print(names[0:3])  # 切片
print(names[:3])  # 切片
print(names[-1])
print(names[-3:-1])  # 切片
print(names[-3:])  # 切片
names.append("LeiHaidong")  # 插入
names.insert(1, "ChenRonghua")  # 插入
names.insert(3, "Xinzhiyu")  # 插入
names[2] = "XieDi"  # 修改
names.remove("ChenRonghua")  # 删除
del names[1]  # 删除
names.pop()  # 删除最后一个
names.pop(0)  # 删除第一个
print(names.index("XieDi"))  # index返回在列表的位置
print(names[names.index("XieDi")])
print(names.count("ChenRonghua"))
names.clear()  # 清空列表
names.reverse()  # 反转列表
names.sort()  # 排序 按照ASCII码的顺序来排

names2 = [1, 2, 3, 4]
names.extend(names2)  # 合并列表

import copy
names = ["4ZhangYang", "#!Guyun", "xXiangpeng", ["alex", "jack"], "XuLiangChen"]
name2 = names.copy()  # 复制列表仅仅复制第一层列表
name3 = copy.deepcopy(names)
names[2] = "向鹏"
names[3][0] = "ALEXANDER"
print(names)
print(name2)
print(name3)

for i in names:  # 列表循环
    print(i)

print(names[0:-1:2])  # 步长切片
print(names[::2])     # 步长切片

#  创建联合账号

import copy
person = ['name', ['saving', 100]]
# p1 = copy.copy(person)
# p2 = person[:]
# p3 = list(person)
p1 = person[:]
p2 = person[:]
p1[0] = 'alex'
p2[0] = 'fengjie'
p1[1][1] = 50
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(product_list.index(item), item)
            print(index, item)
        user_choice = input("选择要买嘛?>>>:")
        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("Adden %s into shopping cart, your current balance is \033[31;1m%s\033[0m" % (p_item, salary))
                else:
                    print("\033[41;1m你的余额只剩[%s]啦,还买个毛线\033[0m" %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")

字符串的操作

name = 'my \tname is {name} and i am {year} old'
print(name.capitalize())
print(name.count("a"))
print(name.center(50, "-"))
print(name.endswith("ex"))
print(name.expandtabs(tabsize=30))
print(name[name.find("name"):])  # 字符串可以切片
print(name.format(name='alex', year=23))
print(name.format_map({'name': 'alex', 'year': 12}))
print('ab23'.isalnum())  # 判断是不是阿拉伯数字和字母
print('abA'.isalpha())
print('1A'.isdecimal())  # 判断十进制
print('1A'.isdigit())
print('a 1A'.isidentifier())  # 判断是不是合法变量名
print('33.33'.isnumeric())   # 判断是不是纯数字
print('My Name Is '.istitle())   # 判断是不是空格
print('My Name Is '.isprintable())  # tty file ,drive file
print('My Name Is '.isupper())
print('+'.join(['1', '2', '3', '4']))
print(name.ljust(50, '*'))
print(name.rjust(50, '*'))
print('Alex'.lower())
print('Alex'.upper())
print('\nAlex'.lstrip())
print('Alex\n'.rstrip())
print('\n  Alex\n'.strip())
p = str.maketrans("abcdef", '123456')
print("alex li".translate(p))
print('alex li'.replace('l', 'L', 1))
print('alex li'.rfind("l"))
print('1+2+3+4'.split("+"))
print('1+2\n+3+4'.splitlines())
print('Alex Li'.swapcase())
print('Alex Li'.title())
print('Alex Li'.zfill(50))

字典

# key-value
info = {
    'stu1101': "TL",
    'stu1102': "LZ",
    'stu1103': "XZ",
}

info.update()

info.items()

c = dict.formkeys([6,7,8],"A","B","C")

print(info.get('stu1103'))
print('sut1103' in info)  
print(info)
print(info["stu1101"])
info["stu1101"] = "武"
info["stu1104"] = "CJ"
del info["stu1101"]
info.pop("stu1101")
info.popitem()  # 随机删一个

info.values()  #打印所有的值

info.keys()  # 打印所有的key

for i in info:

  print(i,info[i])

for k,v in info.items():

  print(k,v)

多级菜单

data = {
    '北京': {
        "昌平": {
            "沙河": ["oldboy", "test"],
            "天通苑": ["链家地产", "我爱我家"]
        },
        "朝阳": {
            "望京": ["奔驰", "陌陌"],
            "国贸": {"CICC", "HP"},
            "东直门": {"Advent", "飞信"},
        },
        "海淀": {},
    },
    "山东": {
        "德州": {},
        "青岛": {},
        "济南": {}
    },
    "广东": {
        "东莞": {},
        "常熟": {},
        "佛山": {},
    },
}
exit_flag = False
while not exit_flag:
    for i in data:
        print(i)
    choice = input("选择进入>>:")
    if choice in data:
        while not exit_flag:
            for i2 in data[choice]:
                print("\t", i2)
            choice2 = input("选择进入>>:")
            if choice2 in data[choice]:
                while not exit_flag:
                    for i3 in data[choice][choice2]:
                        print("\t\t", i3)
                    choice3 = input("选择进入>>:")
                    if choice3 in data[choice]:
                        for i4 in data[choice][choice2][choice3]:
                            print("\t\t", i4)
                        choice4 = input("最后一层,按b返回>>:")
                        if choice4 == "b":
                            pass
                        elif choice4 == "q":
                            exit_flag = True
                    if choice3 == "b":
                        break
                    elif choice3 == "q":
                        exit_flag = True
            if choice2 == "b":
                break
            elif choice2 == "q":
                exit_flag = True

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值