首页技术为王PythonPython基础课程

Python基础课程

分类Python时间2026-08-24 21:36:02发布信义之树浏览111
导读:一、技术通识 1. 计算机基础结构 2. 软件 软件=程序 + 文档 3. Python执行过程 &nbs...

一、技术通识

    1. 计算机基础结构

图片.png


    2. 软件

        软件=程序 + 文档

    3. Python执行过程

        编译之后得到.pyc文件。

图片.png




        源代码  转成 机器码  ==> 编译(程序运行前 编译器)  解释(程序运行时 解释器)

        源代码 --> 中间语言 .pyc  --> 机器码


二、Day2

float3=0.0
print(type(float3))

#在内存中的地址不同
age = 18
print(f"age的值: {age}, 内存地址: {id(age)}")
age = 19
print(f"age的值: {age}, 内存地址: {id(age)}")

#字符串转会报错
#print(int("6.66"))  

#非0就是真
print(bool(-1))

#空值也是值
print(bool("  "))


str2 = "好"
print(str2*10)

#或的关系
print(1>=1)

# 查看unicode码点
print(ord("1"))
print(ord("3"))

# 短路机制:当前一个表达式能够确定整个结果的时候,后方的代码不被执行
# if user and user.is_active:
0 != 0 and print("Hello")
0 == 0 or print("HI")

#方法
number = 1234
# 个
unit1 = number % 10
# 十
unit2 = number // 10 % 10
print(unit1, unit2)


"""
终端中输入一个正整数
奇数输出True 偶数输出False
奇数输出False 偶数输出True
"""
number = int(input("请输入一个正整数:"))
res1 = number % 2 != 0
res2 = number % 2 == 0
print(res1, res2)

#怎么就防御了
res4 = number % 2 == True
print(res4)

#短路写法,2个都执行
0 == 0 and print("HI") or print("Hello")

not True and print("假")

#闰年的一行判断
year = 1986
res = year % 4 == 0 and year % 100 != 0 or year % 400 == 0

if res:
    print(f"{year}是闰年")
else:
    print(f"{year}是平年")


        执行结果:

True
49
51
4 3
请输入一个正整数:25
True False
True
HI
Hello
1986是平年
PS C:\Users\Administrator\Desktop\新达内\Python基础课程> & C:/Users/Administrator/AppData/Local/Programs/Python/Python314/python.exe c:/Users/Administrator/Desktop/新达内/Python基础课程/Day2.py
<class 'float'>
age的值: 18, 内存地址: 140704518227608
age的值: 19, 内存地址: 140704518227640
True
True
好好好好好好好好好好
True
49
51
4 3
请输入一个正整数:99
True False
True
HI
Hello
1986是平年


三、Day3

number = 18

# true_val if 条件 else false_val
print("奇数") if number % 2 else print("偶数")


# range函数可以产生一个可迭代对象,包含开始,不包含结束的整数序列
# range(开始,结束)
for i in range(1, 5):
    print(i)


# range(结束)默认从0开始
for i in range(5):
    print(i)


# range(开始,结束,步长) 步长默认为1
for i in range(1, 10, 2):
    print(i)


# 第二种 排除法
score = float(input("请输入你的成绩:"))
if score < 0 or score > 100:
    print("成绩异常")
elif score == 100:
    print("满分")
elif score >= 90:
    print("优秀")
elif score >= 60:
    print("良好")
elif score >= 0:
    print("需努力")

        执行结果:    

0
1
2
3
4
1
3
5
7
9
PS C:\Users\Administrator\Desktop\新达内\Python基础课程> & C:/Users/Administrator/AppData/Local/Programs/Python/Python314/python.exe c:/Users/Administrator/Desktop/新达内/Python基础课程/Day3.py
偶数
1
2
3
4
0
1
2
3
4
1
3
5
7
9
请输入你的成绩:99.9
优秀


四、Day4

# 1.创建
list_movie = ["749", "昆池岩", "寂静岭", "灰姑娘", "安妮的脸", "带我回家"]

list_movie.remove("昆池岩")

# 同时得到列表的索引和元素
for i in range(5):
    print(i, list_movie[i])


# 新写法
line = 5

for i in range(1, line + 1):
    for _ in range(line - i):
        print(" ", end="")

    for _ in range(i * 2 - 1):
        print("*", end="")

    print()



# 1.赋值 还是同一个盒子 互相影响  原来还能这样?
list_movie = ["昆池岩", ["门铃", "娃娃"]]
list_new1 = list_movie
list_new1[0] = "寂静岭"
list_new1[1][0] = "深瞳"
list_new1[1][0] = "你大爷"
print(list_movie)  # ['寂静岭', ['深瞳', '娃娃']]
print(list_new1)  # ['寂静岭', ['深瞳', '娃娃']]



# 2.先切片再赋值
# 浅拷贝:浅层(第一层)数据2份 互不影响  深层数据1份(共享) 互相影响
list_movie = ["昆池岩", ["门铃", "娃娃"]]
list_new2 = list_movie[:]
list_new2[0] = "寂静岭"
list_new2[1][0] = "深瞳"
print(list_movie)  # ['昆池岩', ['深瞳', '娃娃']]
print(list_new2)  # ['寂静岭', ['深瞳', '娃娃']]


# 3.深拷贝 所有层的数据都是独立的
import copy
list_movie = ["昆池岩", ["门铃", "娃娃"]]
list_new3 = copy.deepcopy(list_movie)
list_new3[0] = "寂静岭"
list_new3[1][0] = "深瞳"
print(list_movie)  # ["昆池岩", ["门铃", "娃娃"]]
print(list_new3)  # ['寂静岭', ['深瞳', '娃娃']]


# 列表推导式
list_number = [66, 23, 15, 78, 22]
list_new = [item for item in list_number if item % 2 == 0]
print(list_new)


#列表取值
city_list = ["北京", "天津", "杭州", "广州", "山西", "山东"]

print(city_list[1])
print(city_list[4:5]) #这里取出的是一个列表,而不是一个元素

print(city_list[::2])
print(city_list[-6:-1:2])

print(city_list[2:5])
print(city_list[-4:-1])


"""
使用列表推导式
找出1到20之间所有偶数,并使用偶数的平方组成列表
"""
list_new = [
    i ** 2 
    for i in range(1, 21)
    if not i % 2  #为什么要用这种方式
]
print(list_new)


"""
画出以下代码内存图
"""
list_region = ["湾湾", "山西", "杭州"]  #region 区域

list1 = list_region
list2 = list_region[-2:]

print("ee",list2)

list2[0] = "天津"
list1[0] = "河北"

print(list_region)
print(list1)
print(list2)


list_planet = ["水星", "金星", "火星", "木星", "土星", "天王星", "海王星"]
list_planet.insert(2, "地球")
del list_planet[3]

for item in list_planet[::-1]:  # 反向遍历
    print(item)


        执行结果:

0 749
1 寂静岭  
2 灰姑娘  
3 安妮的脸
4 带我回家
    *     
   ***    
  *****   
 *******
*********
['寂静岭', ['你大爷', '娃娃']]
['寂静岭', ['你大爷', '娃娃']]
['昆池岩', ['深瞳', '娃娃']]
['寂静岭', ['深瞳', '娃娃']]
['昆池岩', ['门铃', '娃娃']]
['寂静岭', ['深瞳', '娃娃']]
[66, 78, 22]
天津
['山西']
['北京', '杭州', '山西']
['北京', '杭州', '山西']
['杭州', '广州', '山西']
['杭州', '广州', '山西']
[4, 16, 36, 64, 100, 144, 196, 256, 324, 400]
ee ['山西', '杭州']
['河北', '山西', '杭州']
['河北', '山西', '杭州']
['天津', '杭州']
海王星
天王星
土星
木星
地球
金星
水星

五、Day5

list1 = [1, 6, 11, 2, 3] #容器

for i in range(len(list1)):
    print(list1[i])
# 最大值最小值(元素为数值)
print(max(list1), min(list1))
# 求和(元素为数值)
print(sum(list1))

list1 = [1, 2, 3, "a", "A"]
print("a" in list1)  # True in的用法
print(6 in list1)  # False

# 创建单个元素的元组,必须有逗号
tuple2 = ("爱情",)
# 小括号可以省略(不建议)
tuple3 = "爱情",

tuple1 = ("剧情", "科幻")
print(tuple1[::-1])


# 基础解包
tuple1 = (1, 2, 3)
# 逐一获取元素,依次赋值给变量 变量个数和元素的个数一致
a, b, c = tuple1
print(a, b, c)

# *号解包
# 长度不确定的时候,把多余的元素收集起来,放在列表里
#a, *b = (1, 2, 3, 4, 5)  # a = 1, b = [2, 3, 4, 5]
#*a, b = (1, 2, 3, 4, 5) #a=[1,2,3,4], b=5
*a, b = (1, 2) #a=[1], b=2
print(a, b)


# 不借助第三方变量交换2个变量的值
a = 2
b = 1
a, b = b, a
print(a, b)  # 1 2


# 5.格式化
class_name = "AID2505"
count = 5
price = 6.666666
# %s字符串  %d整数  %f浮点数
print(
    "现在%s课堂玩手机,人数:%d人,平均价格%.2f"
    %
    (class_name, count, price)
)
# F-string
print(f"现在{class_name}课堂玩手机人数:{count}人,平均价格{price:.2f}")


# 首字母大写
str1 = " HeLlo wOrLd XiaoYi "
print(str1.title())
# 去除开头和结尾的字符
print(str1.strip())
# 替换
print(str1.replace(" ", ""))
print(str1.replace(" ", "", 2))  # 指定替换次数
# 寻找字符第一次出现的位置,找到返回索引,找不到返回-1
print(str1.find("L"))
print(str1.find("p"))
# 最后一次出现的位置
print(str1.rfind("i"))

# 列表推导式 怎么这么别扭
list1 = [[1, 2, 3], [4, 5, 6]]
print([sub_item for item in list1 for sub_item in item])


"""
遍历时分离头元素和剩余元素
探索是否可以在for循环中使用 *号解包操作
"""
list1 = [(1, 2, 3), (4, 5), (6,)]
for item in list1:
    a, *b = item

    # if not len(b):
    # if len(b) == 0:
    if not b:
        b = "无"

    print(f"头:{a},剩余 {b}")

for a, *b in list1:
    # 空列表,空元组,空字典,空字符串  false
    print(f"头:{a},剩余: {b if b else '无'}")

        执行结果:

1
6
11
2
3
11 1
23
True
False
('科幻', '剧情')
1 2 3
[1] 2
1 2
现在AID2505课堂玩手机,人数:5人,平均价格6.67
现在AID2505课堂玩手机人数:5人,平均价格6.67
 Hello World Xiaoyi
HeLlo wOrLd XiaoYi
HeLlowOrLdXiaoYi
HeLlowOrLd XiaoYi
3
-1
18
[1, 2, 3, 4, 5, 6]
头:1,剩余 [2, 3]
头:4,剩余 [5]
头:6,剩余 无
头:1,剩余: [2, 3]
头:4,剩余: [5]
头:6,剩余: 无

六、Day6

# 拼接 把可迭代对象中的元素用指定符号链接形成新的字符串
list1 = ["1", "2", "3", "4"]
print("-".join(list1))


# 判断相关
str1 = "Hi"
str2 = "666"
str3 = "99hI"
# 只包含数字
print("str1:",str1.isdigit())
print("str2:",str2.isdigit())
print("str3:",str3.isdigit())
# 只包含字母
print("str1:",str1.isalpha())
print("str3:",str3.isalpha())
# 只包含字母,数字
print("str1:",str1.isalnum())
print("str2:",str2.isalnum())
print("str3:",str3.isalnum())
print("1qw_|'0", "1qw_|'0".isalnum())




# 1.创建
dict_movie = {
    "name": 749,
    "type": ("动画", "剧情"),
    "actor": ["王俊凯", "李梦", "李晨"],
}
# 2.访问 字典[键]
print(dict_movie["type"])
print(dict_movie.get("type2")) #不会报错,而是安静地返回一个 None

dict_movie.update({"index": 10010, "city": "china"})
print(dict_movie)

del dict_movie["city"]
dict_movie.pop("index")
print(dict_movie)

# 删除最后一个键
dict_movie.popitem()
print(dict_movie)


# items() 键值对组成一个个元组
# [('name', '娃娃'), ('type', ('动画', '剧情'))]
for key, val in dict_movie.items():
    print(key, val)

# 6.in not in 运算符  看的是键
print("a" in dict_movie)
print("name" in dict_movie)


# 7.推导式
# 字典名 = {键:值 for 变量 in 可迭代对象}
# 字典名 = {键:值 for 变量 in 可迭代对象 if 条件}
dict_city = {
    "101": "北京",
    "102": "天津",
    "103": "河北",
}

dict_new = {
    value: key #为什么要这么写
    for key, value in dict_city.items()}
print("dict_new:",dict_new)


list_movie = [
    {
        "name": "封神",
        "index": 10086,
        "type": ("动画", "科幻"),
        "actor": ["子牙", "申公豹"]
    },
    {
        "name": "昆池岩",
        "index": 10000,
        "type": ("爱情", "剧情"),
        "actor": ["媛媛", "智贤"]
    }
]

# 1.打印 智贤
print(list_movie[1]['actor'][1])
# 2.打印所有电影的类型
for item in list_movie:
    print("是啥:",item)

#一句话写法
[print(sub_item) for item in list_movie for sub_item in item["type"]]


"""
字符串中的每个单词,反转输出
Just do it  ==> Tsuj Od Ti
2种写法 列表推导式写法
"""
str1 = "Just do it"
list_new = []
# 1. 遍历 split得到的列表
for item in str1.split(" "):
    # 2.把每个元素反转后添加到新列表
    list_new.append(item[::-1])
# 3.join + 空格拼接元素得到新字符串,首字母大写
print(" ".join(list_new).title())

# 推导式
print([item[::-1] for item in str1.split(" ")])
print(" ".join([item[::-1] for item in str1.split(" ")]).title())
str4="tsuj od ti"
print(str4.title())


"""
创建字典存储 湾湾地区的名字, 新增感染人数,现有感染人数
增加 累计感染人数, 治愈人数
给湾湾地区 感染人数新增100人, 治愈人数新增20人
删除 新增感染人数
"""
dict_area = {
    "region": "湾湾",
    "new": 26,
    "now": 100
}

dict_area.update({"total": 1000})
print(dict_area)
dict_area["cure"] = 300
dict_area["new"] += 100
dict_area["cure"] += 20
print(dict_area)
dict_area.pop("new")
print(dict_area)


"""
字典的键和值互换
"""
dict_city = {
    "101": "北京",
    "102": "天津",
    "103": "河北",
}

dict_new = {}
for key, value in dict_city.items():
    dict_new[value] = key #问千问懂了,for这一步是拿到值,到这一步才赋值

print(dict_new)


"""
把下列2个列表组合成一个字典
"""
list1 = ["封神", "昆池岩", "碟中谍8"]
list2 = [10010, 10000, 10086, 1000]

dict_movie = {list1[i]: list2[i] for i in range(len(list1))}
print(dict_movie)

dict_movie = {}
for i in range(len(list1)):
    dict_movie.update({list1[i]: list2[i]})
print(dict_movie)

        执行结果:

1-2-3-4
str1: False
str2: True
str3: False
str1: True
str3: False
str1: True
str2: True
str3: True
1qw_|'0 False
('动画', '剧情')
None
{'name': 749, 'type': ('动画', '剧情'), 'actor': ['王俊凯', '李梦', '李晨'], 'index': 10010, 'city': 'china'}
{'name': 749, 'type': ('动画', '剧情'), 'actor': ['王俊凯', '李梦', '李晨']}
{'name': 749, 'type': ('动画', '剧情')}
name 749
type ('动画', '剧情')
False
True
dict_new: {'北京': '101', '天津': '102', '河北': '103'}
智贤
是啥: {'name': '封神', 'index': 10086, 'type': ('动画', '科幻'), 'actor': ['子牙', '申公豹']}
是啥: {'name': '昆池岩', 'index': 10000, 'type': ('爱情', '剧情'), 'actor': ['媛媛', '智贤']}
动画
科幻
爱情
剧情
Tsuj Od Ti
['tsuJ', 'od', 'ti']
Tsuj Od Ti
Tsuj Od Ti
{'region': '湾湾', 'new': 26, 'now': 100, 'total': 1000}
{'region': '湾湾', 'new': 126, 'now': 100, 'total': 1000, 'cure': 320}
{'region': '湾湾', 'now': 100, 'total': 1000, 'cure': 320}
{'北京': '101', '天津': '102', '河北': '103'}
{'封神': 10010, '昆池岩': 10000, '碟中谍8': 10086}
{'封神': 10010, '昆池岩': 10000, '碟中谍8': 10086}

七、Day7

# 序列传参:实参使用 *序列拆解后与形参的位置依次对应
def fn3(p1, p2, p3):
    print(p1)
    print(p2)
    print(p3)


fn3(*[1, 2, 3])
fn3(*(1, 2, 3))

# 默认是键
dict1 = {'cn': 100, 'en': 110, 'ma': 120}
fn3(*dict1)
fn3(*dict1.values())  # 等价与 fn3(*[100,110,120])
fn3(*dict1.items())  # 等价与 fn3(*[('cn',100),('en',110),('ma',120)])

print("="*20)
# 可变数量的位置参数 *号元组形参
# 把实参打包成一个元组
# args 名字是约定俗成的,可以改,但是一般不改
def fn2(*args):
    print(args)

fn2()
fn2(1)
fn2(1, 2, 3, 4, 5, 6)

# 可变数量的关键字参数 **字典形参
# 把实参打包成一个字典
# kwargs 名字是约定俗成的,可以改,但是一般不改
def fn3(**kwargs):
    print(kwargs)


fn3()
fn3(name="xiaorui", age="18", sex="男")


"""
作用域
变量或者函数起作用的范围

L 局部  函数的内部
E 嵌套  函数嵌套
G 全局  模块(.py)的内部
B 内置  builtins
# 查找规则: L --> E --> G --> B --> 报错
"""


"""
定义一个函数,
计算所有位置参数的和
计算所有关键字参数的乘积
返回元组
"""


def sum_and_product(*args, **kwargs):
    arg_sum = sum(args)

    if not kwargs:
        return arg_sum,
    else:
        kwargs_product = 1
        for value in kwargs.values():
            kwargs_product *= value

        return arg_sum, kwargs_product

print("="*20)
print(sum_and_product(1, 2))  # (3,)
print(sum_and_product(1, 2, a=4))  
print(sum_and_product(1, 2, a=4, b=5, c=6))  # (3,120)







"""
数瞰商智运营系统V1

运行文件 显示数字服务菜单
    1.添加商品信息
    2.显示商品信息
    3.修改商品信息
    4.删除商品信息
    5.退出系统

用户在终端中输入(1~5)数字触发对应的操作
   按1键添加商品信息
        商品id、标题、价格
   按2键显示所有商品信息
        ID:1的商品标题是苹果18,价格为100
   按3键修改商品信息
        根据输入的ID修改商品
        标题、价格
   按4键删除商品信息
        根据输入的ID删除商品
   按5键退出系统
"""
# \033 是八进制写法,代表 ASCII 码里的 ESC(Escape)键    \033[ 固定起手式 34蓝色 m结束序列
BLUE = "\033[34m"
GREEN = "\033[32m"
RED = "\033[31m"
# 重置颜色
RESET = "\033[0m"

list_prd = []
while True:

    # 1.显示菜单
    print(f"{BLUE}按1键添加商品信息")
    print("按2键显示商品信息")
    print("按3键修改商品信息")
    print("按4键删除商品信息")
    print("按5键退出系统")

    # 2.选择菜单
    choose_numer = input("请输入服务数字:")
    if choose_numer == "1":
        while True:
            # 空格替换
            id = input("请输入ID:").replace(" ", "")
            # id只能是整数
            if id.isdigit():
                id = int(id)
            else:
                print(f"{RED}ID必须是数字!{RESET}")
                continue

            title = input("请输入标题:").replace(" ", "")
            price = input("请输入价格:").replace(" ", "")

            if not id or not title or not price:
                print(f"{RED}内容不能为空{RESET}")
                continue

            # 价格可以是小数,可以是整数(先不考虑负数)
            if price.replace(".", '', 1).isdigit():
                price = float(price)
                break
            else:
                print(f"{RED}价格必须是数字!")
                continue

        dict_prd = {
            "id": id,
            "title": title,
            "price": price
        }

        list_prd.append(dict_prd)
        print(f"{GREEN}添加成功~")
    elif choose_numer == "2":
        if list_prd:
            for item in list_prd:
                print(f"ID:{item['id']}的商品标题是{item['title']},价格为{item['price']}")
        else:
            print("暂无商品信息")
    elif choose_numer == "3":
        id = int(input("请输入要修改商品的ID").replace(" ", ""))
        for item in list_prd:
            if item['id'] == id:
                while True:
                    new_title = input("新标题:").replace(" ", "")
                    new_price = input("新价格:").replace(" ", "")

                    if not new_title or not new_price:
                        print("内容不能为空!")
                        continue

                    if new_price.replace(".", '', 1).isdigit():
                        new_price = float(new_price)
                        break
                    else:
                        print("价格必须是数字!")
                        continue

                item["title"] = new_title
                item["price"] = new_price
                print("修改成功~")
                break
        else:
            print("商品不存在")
    elif choose_numer == "4":
        id = int(input("请输入要删除商品的ID:").replace(" ", ""))
        for item in list_prd:
            if item['id'] == id:
                list_prd.remove(item)
                print("删除成功")
                break
        else:
            print("商品不存在")
    elif choose_numer == "5":
        print("Bye~")
        break
    else:
        print("不是儿~你有病吧")

        执行结果:

1
2
3
1
2
3
cn
en
ma
100
110
120
('cn', 100)
('en', 110)
('ma', 120)
====================
()
(1,)
(1, 2, 3, 4, 5, 6)
{}
{'name': 'xiaorui', 'age': '18', 'sex': '男'}
====================
(3,)
(3, 4)
(3, 120)
按1键添加商品信息
按2键显示商品信息
按3键修改商品信息
按4键删除商品信息
按5键退出系统
请输入服务数字:1
请输入ID:111
请输入标题:www
请输入价格:22
添加成功~        
按1键添加商品信息
按2键显示商品信息
按3键修改商品信息
按4键删除商品信息
按5键退出系统    
请输入服务数字:1 
请输入ID:222
请输入标题:qqq
请输入价格:33
添加成功~
按1键添加商品信息
按2键显示商品信息
按3键修改商品信息
按4键删除商品信息
按5键退出系统
请输入服务数字:2
ID:111的商品标题是www,价格为22.0
ID:222的商品标题是qqq,价格为33.0
按1键添加商品信息
按2键显示商品信息
按3键修改商品信息
按4键删除商品信息
按5键退出系统
请输入服务数字:5
Bye~

八、Day8

# 好的设计
def filter_scores(scores: list,
                  include_highest: bool = True,
                  include_lowest: bool = True) -> list:
    """
    过滤分数, True保留最高/低分 False去掉最高/低分
    :param scores:成绩 list
    :param include_highest: 最高分 bool
    :param include_lowest: 最低分 bool
    :return: 过滤后的成绩 list  下课休息+练习 11:35继续
    """
    print()
    if not scores:
        return []

    if not include_highest:
        scores.remove(max(scores))

    if not include_lowest:
        scores.remove(min(scores))

    return scores


def calc_avg(scores: list, round_digits: int = 2) -> float:
    """
    计算成绩的平均分,并保留指定小数位数,默认2位
    :param scores: 成绩
    :param round_digits: 保留小数位数
    :return: 平均分
    """
    if not scores:
        return 0

    # 如何浮点保留2位小数? ==> .2f
    # ==> 字符串格式化 ==> f"{avg_score.2f}"
    # ==> float()
    avg_score = float(f"{(sum(scores) / len(scores)):.{round_digits}f}") #第一个f表示格式化字符串,最后的f表示保留2位小数
    avg_score = round((sum(scores) / len(scores)), round_digits)

    return avg_score


# 成绩列表
scores = [139, 125, 7, 240]
# 先调用过滤函数,过滤成绩
filted_scores = filter_scores(scores, include_highest=False)
print(filted_scores)
# 再调用计算函数计算过滤后的成绩平均分
print(calc_avg(filted_scores, round_digits=3))

        执行结果:

[139, 125, 7]
90.333





















影刀高级-JavaScript 面向对象程序设计

游客 回复需填写必要信息
↑