Python 基础入门教程
2026/8/24大约 6 分钟
Python 基础入门教程
从 Hello World 到面向对象,一篇走完 Python 核心语法。每个知识点都配可直接运行的示例,适合零基础快速上手。
一、Hello World 与运行方式
Python 的起点,一行就够:
print("Hello World Python!")运行方式:
python helloworld.py # 运行脚本文件
python -i # 进入交互式 REPL💡 写 Python 不需要编译,解释执行,写完就能跑——这是它上手快的关键。
二、变量与常量
2.1 变量
Python 是动态类型语言,定义变量不用声明类型,直接赋值即可:
x = 10 # int
y = 3.14 # float
name = "Alice" # str
is_active = True # bool
print(x, type(x)) # 输出: 10 <class 'int'>
print(y, type(y)) # 输出: 3.14 <class 'float'>用 type() 可以随时查看变量的类型。变量可以参与运算、传给函数、用于条件判断:
result = x + y # 13.14
def greet(person):
return f"Hello, {person}!"
message = greet(name) # Hello, Alice!
if is_active:
print("The user is active.")命名规则(重要,踩坑必看):
| ✅ 合法 | ❌ 非法 | 原因 |
|---|---|---|
my_var | 2myVar | 不能数字开头 |
_my_var | my-var | 不能含连字符 |
myVar2 | my var | 不能含空格 |
2.2 常量
Python 没有真正意义的常量,靠命名约定——全大写表示"请勿修改":
PI = 3.14159
GRAVITY = 9.81
MAX_CONNECTIONS = 100
# 用常量算圆面积
radius = 5
area = PI * (radius**2) # 78.53975三、数据类型
Python 内置六大常用类型,逐个过一遍。
3.1 数字:int / float / complex
a = 10 # 整数
d = 3.14 # 浮点数
f = 1 + 2j # 复数
print(a / 2) # 5.0 ← 注意!除法结果一定是 float
print(a // 3) # 3 ← 整除
print(a % 3) # 1 ← 取余
print(a**2) # 100 ← 幂运算3.2 字符串 str
str1 = "Hello, Python"
# 拼接
greeting = str1 + " " + "Hello, World"
# 切片(左闭右开)
print(greeting[0:5]) # Hello
# 查找子串
print("Python" in greeting) # True
# 大小写
print(str1.upper()) # HELLO, PYTHON
# f-string 格式化(最常用,推荐)
name = "Alice"
print(f"Hello, {name}!") # Hello, Alice!3.3 列表 list(可变,最常用)
my_list = [1, 2, 3, "Python", 3.14]
my_list[0] # 访问: 1
my_list[1] = "Changed" # 修改
my_list.append("New Element") # 追加
my_list.remove("Python") # 删除
len(my_list) # 长度: 5
my_list[1:4] # 切片: ['Changed', 3, 3.14]3.4 元组 tuple(不可变)
my_tuple = (1, 2, 3, "Python", 3.14)
my_tuple[0] # 访问: 1
len(my_tuple) # 5
# 解包(超好用)
a, b, c, d, e = my_tuple # a=1, b=2, c=3, d='Python', e=3.14
# my_tuple[1] = 'Changed' # ❌ 报错!元组不可变3.5 字典 dict(键值对)
my_dict = {"name": "Python", "version": 3.9}
my_dict["name"] # 访问: Python
my_dict["version"] = 3.10 # 修改
my_dict["creator"] = "Guido van Rossum" # 新增
del my_dict["version"] # 删除
my_dict.keys() # 所有键
my_dict.values() # 所有值
my_dict.items() # 所有键值对3.6 集合 set(自动去重)
my_set = {1, 2, 3, 4, 5}
another_set = set([3, 4, 5, 6, 7])
my_set.add(6) # 添加
my_set.add(3) # 重复添加无效 → 去重特性
my_set.remove(4) # 删除
my_set & another_set # 交集 {3, 5, 6}
my_set | another_set # 并集 {1, 2, 3, 5, 6, 7}
my_set - another_set # 差集 {1, 2}
my_set ^ another_set # 对称差 {1, 2, 7}3.7 八大类型一图流
| 类型 | 写法 | 可变 | 有序 | 用途 |
|---|---|---|---|---|
| int | 10 | — | — | 整数 |
| float | 3.14 | — | — | 小数 |
| complex | 1+2j | — | — | 复数 |
| str | "abc" | ❌ | ✅ | 文本 |
| list | [1,2,3] | ✅ | ✅ | 可变序列 |
| tuple | (1,2,3) | ❌ | ✅ | 不可变序列 |
| dict | {"k":1} | ✅ | ✅(3.7+) | 键值映射 |
| set | {1,2,3} | ✅ | ❌ | 去重/集合运算 |
四、运算符
a, b = 10, 3
# 算术
a + b # 13
a - b # 7
a * b # 30
a / b # 3.333... ← 真除法
a // b # 3 ← 整除
a % b # 1 ← 取余
a**b # 1000 ← 幂
# 比较(结果都是 bool)
a == b # False
a != b # True
a > b # True
# 逻辑
True and False # False
True or False # True
not True # False
# 赋值(复合)
a += b # 等价 a = a + b
a //= b
a **= b
# 位运算
a & b # 按位与
a | b # 按位或
a ^ b # 按位异或
a << 2 # 左移
a >> 2 # 右移五、条件判断
# if
x = 10
if x > 5:
print("x is greater than 5")
# if-else
x = 3
if x > 5:
print("x is greater than 5")
else:
print("x is less than or equal to 5")
# if-elif-else
x = 7
if x > 10:
print("x is greater than 10")
elif x > 5:
print("x is greater than 5 but <= 10")
else:
print("x is 5 or less")
# 嵌套 if
x = 15
if x > 10:
if x > 20:
print("also greater than 20")
else:
print("not greater than 20")
# 三目表达式(一行 if-else)
x = 8
result = "greater than 5" if x > 5 else "<= 5"💡 Python 用缩进(通常 4 空格)表示代码块,没有
{}。缩进错了直接语法错误。
六、循环
# for + range(最常用)
for i in range(5): # 0,1,2,3,4
print(i)
for i in range(2, 7): # 指定起止
print(i)
for i in range(1, 10, 2): # 指定步长: 1,3,5,7,9
print(i)
# 遍历列表
for num in [1, 2, 3, 4, 5]:
print(num)
# while
count = 0
while count < 5:
print(count)
count += 1
# 嵌套循环(注意别无限循环)
for i in range(3):
for j in range(2):
print(f"i={i}, j={j}")
# break / continue / pass
for i in range(5):
if i == 3:
break # 提前终止整个循环
print(i) # 0 1 2
for i in range(5):
if i == 3:
continue # 跳过本次
print(i) # 0 1 2 4
for i in range(5):
if i == 3:
pass # 占位,什么都不做
print(i)七、函数
# 无参
def greet():
print("Hello, welcome to Python programming!")
# 带参
def greet_user(name):
print(f"Hello, {name}, welcome!")
# 带返回值
def add(a, b):
return a + b
result = add(3, 5) # 8八、面向对象(类)
8.1 类属性 vs 实例属性
class Person:
species = "Homo sapiens" # 类属性(所有实例共享)
def __init__(self, name, age):
self.name = name # 实例属性(每个实例独立)
self.age = age
def greet(self):
return f"Hello, my name is {self.name}, I am {self.age}."
person1 = Person("Alice", 30)
print(Person.species) # 通过类访问
print(person1.species) # 通过实例访问
person1.greet() # 调用方法8.2 封装(私有属性)
Python 用双下划线前缀 __name 表示私有属性,外部不能直接访问,通过方法读写:
class Person:
def __init__(self, name, age):
self.__name = name # 私有属性
self.__age = age
def get_age(self):
return self.__age
def set_age(self, age):
if age > 0:
self.__age = age
else:
raise ValueError("Age must be positive")
person = Person("Alice", 30)
person.set_age(35)
print(person.get_age()) # 35
# person.__age # ❌ AttributeError,不能直接访问8.3 常用魔法方法
class Person:
def __init__(self, name, age):
self.name, self.age = name, age
def __str__(self): # print() 调用,给人看
return f"Person(name={self.name}, age={self.age})"
def __repr__(self): # 交互式/调试用,更精确
return f"Person(name='{self.name}', age={self.age})"
person = Person("Alice", 30)
print(person) # 走 __str__
repr(person) # 走 __repr__
person.__dict__ # {'name': 'Alice', 'age': 30}
person.__class__ # <class '__main__.Person'>
isinstance(person, Person) # True九、综合实战:计算器
把前面的知识串起来——输入、函数、四则运算、大小比较、异常处理:
def calculate_and_compare(a, b):
print(f"{a} + {b} = {a + b}")
print(f"{a} - {b} = {a - b}")
print(f"{a} * {b} = {a * b}")
if b != 0:
print(f"{a} / {b} = {a / b}")
else:
print("除数不能为零")
if a > b:
print(f"{a} 大于 {b}")
elif a < b:
print(f"{a} 小于 {b}")
else:
print(f"{a} 等于 {b}")
try:
num1 = float(input("请输入第一个数字: "))
num2 = float(input("请输入第二个数字: "))
calculate_and_compare(num1, num2)
except ValueError:
print("请输入有效的数字")十、知识点速查表
| 主题 | 一句话记住 |
|---|---|
| 变量 | 动态类型,直接赋值,type() 查类型 |
| 常量 | 全大写命名约定,Python 无真常量 |
| 字符串 | f"{var}" 格式化,切片 [左:右) 左闭右开 |
| 列表 | append/remove/[a:b],可变有序 |
| 元组 | 不可变,支持解包 |
| 字典 | dict[key] 增删改查,items() 遍历 |
| 集合 | 自动去重,交并差对称差 |
| 条件 | if/elif/else,缩进即代码块,三目 a if cond else b |
| 循环 | for + range 最常用,break/continue/pass |
| 函数 | def 定义,return 返回值 |
| 类 | __init__ 构造,__name 私有,__str__/__repr__ 魔法方法 |
🎯 一句话总结:语法(变量/类型/运算符)→ 控制流(if/for/while)→ 抽象(函数/类)→ 实战(计算器),这条线走完,Python 就算入门了。