Python 基础语法非常简洁易懂,是入门编程的绝佳选择!以下是 Python 基础语法的核心知识点:
1. 注释
- 单行注释:
# - 多行注释:用三个引号(
'''或""")
# 这是单行注释
"""
这是多行注释
可以写很多内容
"""
2. 变量和数据类型
- Python 是动态类型语言,变量不需要声明类型。
# 数字类型
a = 10 # 整数
b = 3.14 # 浮点数
# 字符串类型
name = "Python" # 字符串
# 布尔类型
is_active = True # 布尔值
# None(类似于 null)
x = None
3. 输入与输出
- 输出:使用
print()函数 - 输入:使用
input()函数
# 输出
print("你好, Python!")
# 输入
name = input("请输入你的名字: ")
print(f"你好, {name}!")
4. 条件判断
age = int(input("请输入你的年龄: "))
if age >= 18:
print("你是成年人")
elif age > 12:
print("你是青少年")
else:
print("你是儿童")
5. 循环
- for 循环:适合迭代序列或范围
- while 循环:基于条件循环
# for 循环
for i in range(5): # 0 到 4
print(f"循环次数: {i + 1}")
# while 循环
count = 0
while count < 5:
print(f"Count = {count}")
count += 1
6. 函数
函数是可重复使用的代码块,使用 def 定义:
def greet(name):
return f"你好, {name}!"
print(greet("Python"))
7. 数据结构
Python 提供了丰富的数据结构:
列表(List)
- 有序、可变
fruits = ["苹果", "香蕉", "橙子"]
print(fruits[0]) # 输出第一个元素
fruits.append("梨") # 添加元素
元组(Tuple)
- 有序、不可变
colors = ("红", "绿", "蓝")
print(colors[1]) # 访问元素
字典(Dictionary)
- 键值对
person = {"姓名": "张三", "年龄": 25}
print(person["姓名"]) # 访问值
集合(Set)
- 无序、唯一
nums = {1, 2, 3, 3}
print(nums) # 输出: {1, 2, 3}
8. 文件操作
# 写入文件
with open("example.txt", "w") as f:
f.write("这是第一行内容!")
# 读取文件
with open("example.txt", "r") as f:
content = f.read()
print(content)
9. 异常处理
使用 try...except 捕获异常:
try:
num = int(input("请输入一个数字: "))
print(10 / num)
except ValueError:
print("请输入正确的数字!")
except ZeroDivisionError:
print("除数不能为 0!")
10. 模块和库
- 使用
import引入模块
import math
print(math.sqrt(16)) # 求平方根

被折叠的 条评论
为什么被折叠?



