30个Python基础知识点和实用技巧

news/2025/3/31 12:44:30/文章来源:https://www.cnblogs.com/zhangruipeng/p/18797789

Python作为一门易学易用的编程语言,受到了众多初学者的喜爱。本文介绍30个Python基础知识点和实用技巧,帮助你快速掌握Python编程的核心概念。

一、基本数据类型

1. 数字与运算

# 整数和浮点数
x = 10          # 整数
y = 3.14        # 浮点数
​
# 基本运算
print(x + y)    # 加法: 13.14
print(x - y)    # 减法: 6.86
print(x * y)    # 乘法: 31.4
print(x / y)    # 除法: 3.184713375796178
print(x // y)   # 整除: 3.0
print(x % y)    # 取余: 0.5800000000000001
print(x ** 2)   # 幂运算: 100

2. 字符串基础

# 创建字符串
name = "Python编程"
message = '学习Python很有趣'
​
# 字符串连接
greeting = "你好," + name + "!"
print(greeting)  # 你好,Python编程!
​
# 字符串格式化
age = 30
info = f"{name}已经{age}岁了"
print(info)  # Python编程已经30岁了

3. 布尔值与比较

# 布尔值
is_valid = True
is_complete = False
​
# 比较运算符
x = 10
y = 20
print(x > y)    # False
print(x < y)    # True
print(x == y)   # False
print(x != y)   # True
print(x >= 10)  # True

4. 类型转换

# 字符串转数字
num_str = "123"
num_int = int(num_str)    # 123 (整数)
num_float = float(num_str)  # 123.0 (浮点数)
​
# 数字转字符串
price = 19.99
price_str = str(price)  # "19.99"
​
# 转换为布尔值
print(bool(0))      # False
print(bool(1))      # True
print(bool(""))     # False
print(bool("text")) # True

5. 变量与常量

# 变量命名
user_name = "admin"  # 推荐使用下划线命名法
count = 0
​
# 多变量赋值
x, y, z = 1, 2, 3
print(x, y, z)  # 1 2 3
​
# 交换变量值
a, b = 5, 10
a, b = b, a
print(a, b)  # 10 5
​
# 常量约定(Python没有真正的常量)
MAX_USERS = 100  # 全大写表示常量,不应被修改

二、数据结构

6. 列表基础

# 创建列表
fruits = ["苹果", "香蕉", "橙子"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "文本", True, 3.14]
​
# 访问元素
first_fruit = fruits[0]  # "苹果"
last_number = numbers[-1]  # 5
​
# 修改元素
fruits[1] = "梨"
print(fruits)  # ["苹果", "梨", "橙子"]
​
# 添加和删除元素
fruits.append("葡萄")     # 添加到末尾
fruits.insert(1, "香蕉")  # 在指定位置插入
removed = fruits.pop(0)   # 移除并返回指定位置元素
fruits.remove("橙子")     # 移除特定值的元素

7. 列表切片

numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
​
# 基本切片 [开始:结束:步长]
first_three = numbers[0:3]      # [0, 1, 2]
middle = numbers[3:7]           # [3, 4, 5, 6]
last_three = numbers[-3:]       # [7, 8, 9]
every_second = numbers[::2]     # [0, 2, 4, 6, 8]
reversed_list = numbers[::-1]   # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

8. 字典使用

# 创建字典
user = {"name": "张三","age": 25,"is_active": True
}
​
# 访问值
print(user["name"])    # 张三
​
# 使用get安全访问(避免键不存在时出错)
email = user.get("email", "未设置")  # "未设置"
​
# 添加和修改
user["email"] = "zhangsan@example.com"
user["age"] = 26
​
# 删除键值对
del user["is_active"]

9. 元组

# 创建元组(不可修改的列表)
coordinates = (10, 20)
rgb = (255, 0, 0)# 访问元素
x = coordinates[0]  # 10
y = coordinates[1]  # 20# 元组解包
r, g, b = rgb
print(r, g, b)  # 255 0 0# 单元素元组需要逗号
single_item = (42,)  # 这是一个元组
not_tuple = (42)     # 这是一个整数

10. 集合

# 创建集合(无序且元素唯一)
fruits = {"苹果", "香蕉", "橙子"}
numbers = {1, 2, 3, 3, 4, 4, 5}  # 重复元素会被删除
print(numbers)  # {1, 2, 3, 4, 5}# 添加和删除元素
fruits.add("葡萄")
fruits.remove("香蕉")  # 如果元素不存在会报错
fruits.discard("梨")   # 如果元素不存在不会报错# 集合操作
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
print(set1 & set2)  # 交集: {3, 4}
print(set1 | set2)  # 并集: {1, 2, 3, 4, 5, 6}
print(set1 - set2)  # 差集: {1, 2}

三、控制流

11. 条件语句

# if语句
age = 18
if age < 18:print("未成年")
elif age == 18:print("刚好成年")
else:print("成年人")# 条件表达式(三元运算符)
status = "成年" if age >= 18 else "未成年"
print(status)  # "成年"# 逻辑运算符
if age >= 18 and age <= 65:print("工作年龄")# 真值判断
name = ""
if name:  # 空字符串视为Falseprint("名字已设置")

12. 循环

# for循环遍历列表
fruits = ["苹果", "香蕉", "橙子"]
for fruit in fruits:print(f"我喜欢吃{fruit}")# for循环遍历字典
user = {"name": "张三", "age": 25}
for key in user:print(f"{key}: {user[key]}")# for循环更多方式
for key, value in user.items():print(f"{key}: {value}")# range函数生成数字序列
for i in range(5):  # 0到4print(i)# while循环
count = 0
while count < 5:print(count)count += 1

13. 循环控制

# break语句提前结束循环
for i in range(10):if i == 5:breakprint(i)  # 打印0到4# continue语句跳过当前迭代
for i in range(10):if i % 2 == 0:  # 如果是偶数continueprint(i)  # 只打印奇数# else子句(循环正常完成时执行)
for i in range(3):print(i)
else:print("循环正常完成")

14. 列表推导式

# 基本列表推导式
numbers = [1, 2, 3, 4, 5]
squares = [n**2 for n in numbers]  # [1, 4, 9, 16, 25]# 带条件的列表推导式
even_squares = [n**2 for n in numbers if n % 2 == 0]  # [4, 16]# 嵌套列表转为平面列表
matrix = [[1, 2], [3, 4], [5, 6]]
flattened = [num for row in matrix for num in row]  # [1, 2, 3, 4, 5, 6]

15. 字典推导式

# 创建字典
names = ["apple", "banana", "cherry"]
fruit_dict = {name: len(name) for name in names}
# {"apple": 5, "banana": 6, "cherry": 6}# 条件字典推导式
numbers = [1, 2, 3, 4, 5]
square_dict = {n: n**2 for n in numbers if n % 2 == 0}
# {2: 4, 4: 16}

四、函数

16. 函数定义与调用

# 定义简单函数
def greet(name):"""向指定的人问好"""  # 文档字符串return f"你好,{name}!"# 调用函数
message = greet("张三")
print(message)  # 你好,张三!# 多返回值
def get_dimensions(width, height):area = width * heightperimeter = 2 * (width + height)return area, perimeterarea, perimeter = get_dimensions(5, 3)
print(f"面积: {area}, 周长: {perimeter}")  # 面积: 15, 周长: 16

17. 函数参数

# 位置参数
def greet(first_name, last_name):return f"你好,{first_name} {last_name}!"print(greet("张", "三"))  # 你好,张 三!# 关键字参数
print(greet(last_name="三", first_name="张"))  # 你好,张 三!# 默认参数值
def greet_with_title(name, title="先生"):return f"你好,{name}{title}!"print(greet_with_title("张三"))        # 你好,张三先生!
print(greet_with_title("李四", "女士"))  # 你好,李四女士!

18. 可变参数

# *args(收集位置参数)
def sum_numbers(*numbers):return sum(numbers)print(sum_numbers(1, 2, 3, 4))  # 10# **kwargs(收集关键字参数)
def create_profile(**user_info):return user_infoprofile = create_profile(name="张三", age=25, city="北京")
print(profile)  # {'name': '张三', 'age': 25, 'city': '北京'}

19. 作用域

# 局部作用域和全局作用域
x = 10  # 全局变量def test_scope():y = 20  # 局部变量print(x)  # 可以访问全局变量print(y)test_scope()
# print(y)  # 错误!不能访问局部变量# 使用global关键字
def modify_global():global xx = 50  # 修改全局变量modify_global()
print(x)  # 50

20. 匿名函数

# lambda函数(一行匿名函数)
add = lambda a, b: a + b
print(add(5, 3))  # 8# 结合函数式编程
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
print(squared)  # [1, 4, 9, 16, 25]# 使用lambda排序
users = [{"name": "张三", "age": 30},{"name": "李四", "age": 25},{"name": "王五", "age": 40}
]
sorted_users = sorted(users, key=lambda user: user["age"])
print([user["name"] for user in sorted_users])  # ['李四', '张三', '王五']

五、文件处理

21. 读写文本文件

# 写入文件
with open("example.txt", "w", encoding="utf-8") as file:file.write("第一行内容\n")file.write("第二行内容\n")# 读取整个文件
with open("example.txt", "r", encoding="utf-8") as file:content = file.read()print(content)# 逐行读取
with open("example.txt", "r", encoding="utf-8") as file:for line in file:print(line.strip())  # strip()移除行尾的换行符

22. 文件路径处理

from pathlib import Path# 创建路径对象
path = Path("data") / "users.txt"
print(path)  # data/users.txt (Windows上是data\users.txt)# 检查路径
data_dir = Path("data")
if not data_dir.exists():data_dir.mkdir()print("data目录已创建")# 获取文件信息
if path.exists():print(f"文件大小: {path.stat().st_size} 字节")print(f"修改时间: {path.stat().st_mtime}")

23. CSV文件处理

import csv# 写入CSV文件
with open("users.csv", "w", newline="", encoding="utf-8") as file:writer = csv.writer(file)writer.writerow(["姓名", "年龄", "城市"])  # 写入标题行writer.writerow(["张三", 25, "北京"])writer.writerow(["李四", 30, "上海"])# 读取CSV文件
with open("users.csv", "r", encoding="utf-8") as file:reader = csv.reader(file)for row in reader:print(row)  # 每行是一个列表# 使用DictReader/DictWriter处理CSV
with open("users.csv", "r", encoding="utf-8") as file:reader = csv.DictReader(file)for row in reader:print(f"{row['姓名']}来自{row['城市']}")

六、错误和异常处理

24. 基本异常处理

# try-except语句
try:number = int(input("请输入一个数字: "))result = 10 / numberprint(f"结果是: {result}")
except ValueError:print("输入不是有效的数字")
except ZeroDivisionError:print("不能除以零")
except:print("发生了其他错误")
finally:print("无论是否发生异常,都会执行这里的代码")

25. 抛出异常

# 使用raise抛出异常
def validate_age(age):if age < 0:raise ValueError("年龄不能为负数")if age > 150:raise ValueError("年龄值不现实")return age# 处理自定义异常
try:user_age = validate_age(-5)
except ValueError as error:print(f"错误: {error}")

七、模块和包

26. 导入模块

# 导入标准库模块
import math
print(math.sqrt(16))  # 4.0# 导入特定函数
from random import randint
print(randint(1, 10))  # 1到10之间的随机整数# 使用别名
import datetime as dt
now = dt.datetime.now()
print(now)# 导入多个函数
from math import sin, cos, tan

27. 创建自定义模块

# 假设我们有文件 mymodule.py
"""
这是一个示例模块
"""
def greet(name):return f"你好,{name}!"PI = 3.14159# 在另一个文件中使用
import mymodule
print(mymodule.greet("张三"))
print(mymodule.PI)

28. 常用标准库

# 日期时间处理
from datetime import datetime, timedelta
now = datetime.now()
yesterday = now - timedelta(days=1)
print(now.strftime("%Y-%m-%d %H:%M:%S"))# 随机数
import random
print(random.choice(["苹果", "香蕉", "橙子"]))  # 随机选择一个元素
print(random.sample(range(1, 50), 6))  # 随机选择6个不重复的数字# 系统操作
import os
current_dir = os.getcwd()  # 获取当前工作目录
files = os.listdir(".")    # 列出当前目录的文件

八、面向对象编程基础

29. 类和对象

# 定义类
class Person:def __init__(self, name, age):self.name = nameself.age = agedef greet(self):return f"你好,我是{self.name},今年{self.age}岁"def have_birthday(self):self.age += 1return f"{self.name}现在{self.age}岁了"# 创建对象
person1 = Person("张三", 25)
person2 = Person("李四", 30)# 调用方法
print(person1.greet())
print(person2.have_birthday())

30. 继承

# 基类
class Animal:def __init__(self, name):self.name = namedef make_sound(self):return "某种声音"# 子类
class Dog(Animal):def make_sound(self):return "汪汪!"class Cat(Animal):def make_sound(self):return "喵喵~"# 使用继承
dog = Dog("旺财")
cat = Cat("咪咪")
print(f"{dog.name}说:{dog.make_sound()}")
print(f"{cat.name}说:{cat.make_sound()}")# 检查类型
print(isinstance(dog, Dog))     # True
print(isinstance(dog, Animal))  # True
print(isinstance(dog, Cat))     # False

以上30个基础知识点涵盖了Python的核心概念,包括数据类型、控制流、函数、文件处理、错误处理、模块使用和面向对象编程。掌握这些基础知识,将使你能够编写出功能完善的Python程序。

作为初学者,建议你先专注于理解这些基础概念,然后通过实际项目来巩固学习成果。Python的学习曲线相对平缓,只要持续练习,你很快就能熟练掌握这门语言。

祝你学习愉快!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/907088.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【日记】感觉沉着冷静是很难得的品质(1200 字)

正文今天不太忙。居然看了一半时间的书,而且居然从零看了一半多了。昨天晚上,一个偶然的原因,看了六层楼跟别人聊天的视频。其实上班之后已经蛮久都没有看他了,时间真的很稀缺。视频中提到了他写的书。他本身表达能力就很好,我想着书应该也不差,就下了一本电子版。刚开始…

Supergateway:MCP服务器的远程调试与集成工具

Supergateway 是一款专为 MCP(Model Context Protocol)服务器设计的远程调试与集成工具,通过 SSE(Server-Sent Events)或 WebSocket(WS)协议实现基于 stdio 的服务器与客户端的高效通信。以下是其核心功能及使用场景的详细解析:核心功能多协议支持支持 SSE 和 WebSocke…

怎么办?听说Windows远程桌面要撤销?解决办法还真有!

3月11日微软正式宣布,将在2025年5月27日关闭并从Microsoft Store中移除Windows远程桌面应用程序,用户将无法通过旧版远程桌面访问这些功能。微软公司此次决定下架Microsoft远程桌面应用,主要是为了推广功能更为强大的Windows App,这种23年上线的解决方案提供了更加统一的界…

电脑文件同步软件,想要备份电脑文方法有哪些?

备份电脑文件的方法有多种,可根据需求选择适合的方案。以下是常见的备份方式及工具推荐,涵盖不同场景:一、使用系统内置工具 Windows 文件历史记录 方法: 连接外部硬盘或网络驱动器。 搜索「文件历史记录」→ 选择驱动器 → 开启自动备份。 可设置备份频率(如每小时)。 二…

我的家庭实验室服务器集群硬件清单

概述 之前有热心读者想要了解我的家庭实验室服务器集群的硬件配置清单. 所以有这篇文章.📝声明: 不是广告, 不是推广, 不是软广.先放2张照片:📝声明: 确实没有理线天赋, 这已经是我理线的极限了, 求轻喷.😂硬件包括:网络一图左下亮绿光的: 瑞莎 Radxa E20C 一图中下: 兮克…

python+pytest+loguru+allure日志封装

一、日志类封装from io import StringIO import sys import os from loguru import logger sys.path.append((os.path.abspath(os.path.join(os.path.dirname(__file__), ../)))) project_path = os.path.dirname(os.path.join(os.path.dirname(__file__))) log_path = os.path…

瑞芯微嵌入式方案概述

瑞芯微(Rockchip)是一家专注于高性能、低功耗芯片设计的中国半导体公司,其嵌入式解决方案广泛应用于智能终端、物联网、工业控制、多媒体处理等领域。以下是瑞芯微嵌入式方案的核心特点、典型应用及开发资源的总结: 一、瑞芯微嵌入式处理器系列 瑞芯微的芯片基于ARM架构,覆…

ggplot2中绘制渐变色的散点图

001、library(ggplot2)data <- data.frame(x = rnorm(100), y = rnorm(100) )ggplot(data, aes(x = x, y = y, color = y)) +geom_point(size = 3) +scale_color_gradient(low = "blue", high = "red") 。

raid级别、存储连接方式

硬盘越大,一搬转速越慢。还有看高速缓存 磁盘阵列能够容纳多少块硬盘 绝对磁盘存储柜的最大存储空间 raid提高吞吐量,保护数据 磁盘阵列柜支持哪些raid级别 raid卡上有缓存 数据先写到磁盘阵列的控制卡,再写到硬盘上 所以如果磁盘阵列卡如果断掉会导致数据丢失,一般磁盘阵列…

根据 2025 年全国青少年信息素养大赛官方通知:算法创意实践挑战赛(C++ 语言)小学组

根据 2025 年全国青少年信息素养大赛官方通知,算法创意实践挑战赛(C++ 语言)小学组的报名时间和考试时间安排如下: 报名时间 2025 年 1 月 10 日至 2025 年 4 月 22 日(具体截止时间以官方报名平台显示为准)。 考试时间初赛:2025 年 5 月(具体日期待定,需关注赛前通知…

众为兴机器人常用技巧

管理员密码 26722719 干涉空间信号设置系统信号配置

R语言中ggplot绘图去除灰色背景并保留外围框线

001、R语言中ggplot绘图去除灰色背景并保留外围框线library(ggplot2)data <- data.frame(x = rnorm(10),y = rnorm(10) )ggplot(data, aes(x = x, y = y)) +geom_point() +theme(panel.background = element_blank(), ## 去除灰色背景axis.line = element_line(colou…