Skip to content

Python 基础语法入门

上一篇我们完成了 Python 的安装与环境配置,本篇来学习 Python 最基础的语法。掌握这些内容后,你就能写出简单的 Python 程序了。

第一个 Python 程序

创建一个文件 hello.py,写入以下内容:

python
print("Hello, Python!")

在终端运行:

bash
python hello.py    # Windows
python3 hello.py   # macOS

看到输出 Hello, Python! 就说明环境一切正常。

变量与数据类型

变量定义

Python 不需要声明变量类型,直接赋值即可:

python
name = "张三"        # 字符串 (str)
age = 25             # 整数 (int)
height = 1.75        # 浮点数 (float)
is_student = True    # 布尔值 (bool)

查看变量类型

python
print(type(name))       # <class 'str'>
print(type(age))        # <class 'int'>
print(type(height))     # <class 'float'>
print(type(is_student)) # <class 'bool'>

常用数据类型

类型示例说明
int42, -10, 0整数,没有大小限制
float3.14, -0.5浮点数(小数)
str"hello", 'world'字符串,单/双引号均可
boolTrue, False布尔值,注意首字母大写
list[1, 2, 3]列表,有序可变
dict{"name": "张三"}字典,键值对

字符串操作

字符串拼接

python
first_name = "小"
last_name = "明"
full_name = first_name + last_name
print(full_name)  # 小明

f-string 格式化(推荐)

python
name = "张三"
age = 25
print(f"我叫{name},今年{age}岁")  # 我叫张三,今年25岁

常用字符串方法

python
text = " Hello, Python! "

print(text.strip())       # "Hello, Python!"  — 去除首尾空格
print(text.lower())       # " hello, python! " — 转小写
print(text.upper())       # " HELLO, PYTHON! " — 转大写
print(text.replace("Python", "World"))  # " Hello, World! "
print(text.split(","))    # [' Hello', ' Python! '] — 按逗号分割
print(len(text))          # 17 — 字符串长度

条件判断

if-elif-else

python
score = 85

if score >= 90:
    print("优秀")
elif score >= 80:
    print("良好")
elif score >= 60:
    print("及格")
else:
    print("不及格")
# 输出:良好

比较运算符

运算符含义示例
==等于a == b
!=不等于a != b
>大于a > b
<小于a < b
>=大于等于a >= b
<=小于等于a <= b

逻辑运算符

python
age = 25
has_id = True

# and — 两个条件都满足
if age >= 18 and has_id:
    print("允许进入")

# or — 满足一个即可
if age < 12 or age > 60:
    print("免费入场")

# not — 取反
if not has_id:
    print("请出示证件")

循环

for 循环

python
# 遍历列表
fruits = ["苹果", "香蕉", "橙子"]
for fruit in fruits:
    print(fruit)

# 使用 range 生成数字序列
for i in range(5):        # 0, 1, 2, 3, 4
    print(i)

for i in range(1, 6):     # 1, 2, 3, 4, 5
    print(i)

while 循环

python
count = 0
while count < 5:
    print(f"第 {count + 1} 次循环")
    count += 1

break 和 continue

python
# break — 立即退出循环
for i in range(10):
    if i == 3:
        break
    print(i)  # 输出 0, 1, 2

# continue — 跳过本次,继续下一次
for i in range(5):
    if i == 2:
        continue
    print(i)  # 输出 0, 1, 3, 4

列表(List)

列表是 Python 中最常用的数据结构,可以存储任意类型的元素。

python
# 创建列表
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", True, 3.14]

# 访问元素(索引从 0 开始)
print(numbers[0])    # 1
print(numbers[-1])   # 5(最后一个元素)

# 添加元素
numbers.append(6)       # 末尾添加 → [1, 2, 3, 4, 5, 6]
numbers.insert(0, 0)    # 指定位置插入 → [0, 1, 2, 3, 4, 5, 6]

# 删除元素
numbers.remove(3)       # 删除值为 3 的元素
popped = numbers.pop()  # 弹出最后一个元素

# 列表切片
print(numbers[1:3])     # 取索引 1 到 2(不含 3)
print(numbers[:3])      # 取前 3 个
print(numbers[::2])     # 每隔一个取一个

# 列表长度
print(len(numbers))     # 元素个数

字典(Dict)

字典用键值对存储数据,适合表示结构化信息。

python
# 创建字典
person = {
    "name": "张三",
    "age": 25,
    "city": "北京"
}

# 访问值
print(person["name"])           # 张三
print(person.get("email", "无"))  # 无(键不存在时返回默认值)

# 添加/修改
person["email"] = "zhangsan@example.com"  # 添加新键值对
person["age"] = 26                         # 修改已有值

# 删除
del person["city"]

# 遍历
for key, value in person.items():
    print(f"{key}: {value}")

函数

定义和调用

python
def greet(name):
    """打招呼函数"""
    return f"你好,{name}!"

message = greet("张三")
print(message)  # 你好,张三!

默认参数

python
def power(base, exponent=2):
    return base ** exponent

print(power(3))      # 9(使用默认值 2)
print(power(3, 3))   # 27

多返回值

python
def divide(a, b):
    quotient = a // b    # 整除
    remainder = a % b    # 取余
    return quotient, remainder

q, r = divide(17, 5)
print(f"商={q}, 余={r}")  # 商=3, 余=2

类和对象

Python 是面向对象的语言,用 class 定义类。

python
class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def introduce(self):
        return f"我叫{self.name},今年{self.age}岁"

# 创建对象
student = Student("张三", 20)
print(student.introduce())  # 我叫张三,今年20岁

导入模块

python
# 导入整个模块
import math
print(math.sqrt(16))  # 4.0

# 导入指定函数
from random import randint
print(randint(1, 100))  # 1 到 100 的随机整数

# 导入并重命名
import datetime as dt
now = dt.datetime.now()
print(now.strftime("%Y-%m-%d"))

异常处理

python
try:
    num = int(input("请输入一个数字:"))
    result = 100 / num
    print(f"结果是 {result}")
except ValueError:
    print("输入的不是有效数字!")
except ZeroDivisionError:
    print("不能除以零!")
finally:
    print("程序结束")

文件读写

python
# 写入文件
with open("test.txt", "w", encoding="utf-8") as f:
    f.write("Hello, Python!\n")
    f.write("这是第二行")

# 读取文件
with open("test.txt", "r", encoding="utf-8") as f:
    content = f.read()
    print(content)

使用 with 语句

with 语句会自动关闭文件,即使发生异常也能正确释放资源。这是 Python 推荐的文件操作方式。

常用内置函数

函数用途示例
print()输出到控制台print("hello")
len()获取长度len([1,2,3]) → 3
type()查看类型type(42) → int
int() / float() / str()类型转换int("42") → 42
range()生成数字序列range(5) → 0-4
sorted()排序sorted([3,1,2]) → [1,2,3]
input()用户输入name = input("名字:")
max() / min()最大/最小值max(1,2,3) → 3

下一步

掌握了以上基础语法后,你可以:

  • 用 Python 写一些小工具(文件批量处理、数据统计)
  • 学习常用第三方库(requests、pandas、flask)
  • 尝试做一些小项目(爬虫、Web 应用、数据分析)

学习建议

编程最好的学习方式是动手写代码。不要只是看,把上面的每个例子都敲一遍运行一下,遇到报错不要怕,读懂错误信息本身就是一种学习。


本文为 Python 基础语法入门,后续会继续更新面向对象进阶、常用标准库、第三方库使用等内容。

用心记录代码与生活