Python 语法基础
变量和数据类型
变量
在 Python 中,变量不需要声明类型,直接赋值即可:
python
x = 5
y = "Hello"变量名必须以字母或下划线开头,不能以数字开头,且区分大小写。
数据类型
Python 支持多种数据类型:
- 整数(int):如
1,2,3 - 浮点数(float):如
1.0,2.5,3.14 - 字符串(str):如
"Hello",'World' - 布尔值(bool):
True或False - 列表(list):如
[1, 2, 3],["a", "b", "c"] - 元组(tuple):如
(1, 2, 3),("a", "b", "c") - 字典(dict):如
{"name": "Alice", "age": 20} - 集合(set):如
{1, 2, 3},{"a", "b", "c"}
类型转换
Python 提供了多种类型转换函数:
python
# 转换为整数
int("123") # 123
int(123.45) # 123
# 转换为浮点数
float("123.45") # 123.45
float(123) # 123.0
# 转换为字符串
str(123) # "123"
str(123.45) # "123.45"
# 转换为列表
list("Hello") # ["H", "e", "l", "l", "o"]
list((1, 2, 3)) # [1, 2, 3]
# 转换为元组
tuple([1, 2, 3]) # (1, 2, 3)
tuple("Hello") # ("H", "e", "l", "l", "o")
# 转换为集合
set([1, 2, 3, 3]) # {1, 2, 3}
set((1, 2, 3)) # {1, 2, 3}运算符
算术运算符
| 运算符 | 描述 | 示例 |
|---|---|---|
+ | 加法 | x + y |
- | 减法 | x - y |
* | 乘法 | x * y |
/ | 除法 | x / y |
% | 取余 | x % y |
** | 幂运算 | x ** y |
// | 整除 | x // y |
比较运算符
| 运算符 | 描述 | 示例 |
|---|---|---|
== | 等于 | x == y |
!= | 不等于 | x != y |
> | 大于 | x > y |
< | 小于 | x < y |
>= | 大于等于 | x >= y |
<= | 小于等于 | x <= y |
逻辑运算符
| 运算符 | 描述 | 示例 |
|---|---|---|
and | 逻辑与 | x and y |
or | 逻辑或 | x or y |
not | 逻辑非 | not x |
赋值运算符
| 运算符 | 描述 | 示例 |
|---|---|---|
= | 赋值 | x = 5 |
+= | 加法赋值 | x += 5 |
-= | 减法赋值 | x -= 5 |
*= | 乘法赋值 | x *= 5 |
/= | 除法赋值 | x /= 5 |
%= | 取余赋值 | x %= 5 |
**= | 幂运算赋值 | x **= 5 |
//= | 整除赋值 | x //= 5 |
控制流
条件语句
python
x = 5
if x > 10:
print("x is greater than 10")
elif x > 5:
print("x is greater than 5 but less than or equal to 10")
else:
print("x is less than or equal to 5")循环语句
for 循环
python
# 遍历列表
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# 遍历字符串
for char in "Hello":
print(char)
# 遍历字典
person = {"name": "Alice", "age": 20, "city": "New York"}
for key, value in person.items():
print(f"{key}: {value}")
# 使用 range() 函数
for i in range(5):
print(i) # 0, 1, 2, 3, 4
for i in range(2, 5):
print(i) # 2, 3, 4
for i in range(0, 10, 2):
print(i) # 0, 2, 4, 6, 8while 循环
python
x = 0
while x < 5:
print(x)
x += 1
# 无限循环
while True:
print("This is an infinite loop")
break # 退出循环循环控制语句
break:退出循环continue:跳过当前循环,继续下一次循环pass:占位符,什么都不做
python
# break 示例
for i in range(10):
if i == 5:
break
print(i) # 0, 1, 2, 3, 4
# continue 示例
for i in range(10):
if i % 2 == 0:
continue
print(i) # 1, 3, 5, 7, 9
# pass 示例
for i in range(5):
if i == 3:
pass # 占位符,什么都不做
print(i) # 0, 1, 2, 3, 4函数
定义函数
python
def greet(name):
"""这是一个打招呼的函数"""
print(f"Hello, {name}!")
# 调用函数
greet("Alice") # Hello, Alice!
# 查看函数文档
print(greet.__doc__) # 这是一个打招呼的函数函数参数
位置参数
python
def add(x, y):
return x + y
print(add(3, 5)) # 8默认参数
python
def greet(name, message="Hello"):
print(f"{message}, {name}!")
greet("Alice") # Hello, Alice!
greet("Bob", "Hi") # Hi, Bob!关键字参数
python
def greet(name, message):
print(f"{message}, {name}!")
greet(message="Hello", name="Alice") # Hello, Alice!可变参数
python
def add(*args):
total = 0
for num in args:
total += num
return total
print(add(1, 2, 3)) # 6
print(add(1, 2, 3, 4, 5)) # 15关键字可变参数
python
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print_info(name="Alice", age=20, city="New York")
# name: Alice
# age: 20
# city: New York返回值
python
def add(x, y):
return x + y
result = add(3, 5)
print(result) # 8
# 返回多个值
def calculate(x, y):
return x + y, x - y, x * y, x / y
add, sub, mul, div = calculate(5, 3)
print(add, sub, mul, div) # 8 2 15 1.6666666666666667列表
创建列表
python
# 创建空列表
empty_list = []
empty_list = list()
# 创建包含元素的列表
numbers = [1, 2, 3, 4, 5]
fruits = ["apple", "banana", "cherry"]
mixed = [1, "apple", 3.14, True]访问列表元素
python
fruits = ["apple", "banana", "cherry"]
# 访问第一个元素
print(fruits[0]) # apple
# 访问最后一个元素
print(fruits[-1]) # cherry
# 访问倒数第二个元素
print(fruits[-2]) # banana
# 切片操作
print(fruits[1:3]) # ["banana", "cherry"]
print(fruits[:2]) # ["apple", "banana"]
print(fruits[1:]) # ["banana", "cherry"]
print(fruits[::2]) # ["apple", "cherry"]修改列表元素
python
fruits = ["apple", "banana", "cherry"]
# 修改第一个元素
fruits[0] = "orange"
print(fruits) # ["orange", "banana", "cherry"]
# 修改多个元素
fruits[1:] = ["grape", "melon"]
print(fruits) # ["orange", "grape", "melon"]列表方法
| 方法 | 描述 | 示例 |
|---|---|---|
append() | 在列表末尾添加元素 | fruits.append("apple") |
insert() | 在指定位置插入元素 | fruits.insert(1, "banana") |
extend() | 扩展列表 | fruits.extend(["cherry", "date"]) |
remove() | 移除指定元素 | fruits.remove("apple") |
pop() | 移除指定位置的元素 | fruits.pop(1) |
clear() | 清空列表 | fruits.clear() |
index() | 返回指定元素的索引 | fruits.index("apple") |
count() | 返回指定元素的出现次数 | fruits.count("apple") |
sort() | 对列表进行排序 | fruits.sort() |
reverse() | 反转列表 | fruits.reverse() |
copy() | 复制列表 | new_fruits = fruits.copy() |
字典
创建字典
python
# 创建空字典
empty_dict = {}
empty_dict = dict()
# 创建包含元素的字典
person = {"name": "Alice", "age": 20, "city": "New York"}
person = dict(name="Alice", age=20, city="New York")
person = dict([("name", "Alice"), ("age", 20), ("city", "New York")])访问字典元素
python
person = {"name": "Alice", "age": 20, "city": "New York"}
# 访问元素
print(person["name"]) # Alice
print(person.get("age")) # 20
# 访问不存在的元素
# print(person["gender"]) # KeyError: 'gender'
print(person.get("gender")) # None
print(person.get("gender", "Unknown")) # Unknown修改字典元素
python
person = {"name": "Alice", "age": 20, "city": "New York"}
# 修改元素
person["age"] = 21
print(person) # {"name": "Alice", "age": 21, "city": "New York"}
# 添加元素
person["gender"] = "Female"
print(person) # {"name": "Alice", "age": 21, "city": "New York", "gender": "Female"}
# 删除元素
del person["city"]
print(person) # {"name": "Alice", "age": 21, "gender": "Female"}
# 清空字典
person.clear()
print(person) # {}字典方法
| 方法 | 描述 | 示例 |
|---|---|---|
keys() | 返回所有键 | person.keys() |
values() | 返回所有值 | person.values() |
items() | 返回所有键值对 | person.items() |
get() | 返回指定键的值 | person.get("name") |
update() | 更新字典 | person.update({"age": 21}) |
pop() | 移除指定键的元素 | person.pop("age") |
popitem() | 移除最后一个键值对 | person.popitem() |
clear() | 清空字典 | person.clear() |
copy() | 复制字典 | new_person = person.copy() |
fromkeys() | 创建新字典 | dict.fromkeys(["name", "age"], "Unknown") |
字符串
创建字符串
python
# 使用单引号
str1 = 'Hello'
# 使用双引号
str2 = "World"
# 使用三引号(多行字符串)
str3 = '''Hello
World
Python'''
str4 = """Hello
World
Python"""访问字符串字符
python
str = "Hello, World!"
# 访问单个字符
print(str[0]) # H
print(str[-1]) # !
# 切片操作
print(str[7:12]) # World
print(str[:5]) # Hello
print(str[7:]) # World!
print(str[::2]) # Hlo ol!字符串方法
| 方法 | 描述 | 示例 |
|---|---|---|
upper() | 转换为大写 | str.upper() |
lower() | 转换为小写 | str.lower() |
capitalize() | 首字母大写 | str.capitalize() |
title() | 每个单词首字母大写 | str.title() |
strip() | 去除首尾空格 | str.strip() |
lstrip() | 去除左侧空格 | str.lstrip() |
rstrip() | 去除右侧空格 | str.rstrip() |
split() | 分割字符串 | str.split(",") |
join() | 连接字符串 | ",".join(["a", "b", "c"]) |
replace() | 替换字符串 | str.replace("Hello", "Hi") |
find() | 查找子字符串 | str.find("World") |
index() | 查找子字符串(找不到抛出异常) | str.index("World") |
count() | 计算子字符串出现次数 | str.count("l") |
startswith() | 检查是否以指定字符串开头 | str.startswith("Hello") |
endswith() | 检查是否以指定字符串结尾 | str.endswith("!") |
isdigit() | 检查是否全为数字 | str.isdigit() |
isalpha() | 检查是否全为字母 | str.isalpha() |
isalnum() | 检查是否全为字母或数字 | str.isalnum() |
异常处理
try-except 语句
python
try:
x = 10 / 0
except ZeroDivisionError:
print("除数不能为零")
except Exception as e:
print(f"发生了异常: {e}")try-except-else 语句
python
try:
x = 10 / 2
except ZeroDivisionError:
print("除数不能为零")
else:
print(f"结果: {x}") # 结果: 5.0try-except-finally 语句
python
try:
x = 10 / 2
except ZeroDivisionError:
print("除数不能为零")
finally:
print("无论是否发生异常,都会执行这条语句")抛出异常
python
def divide(x, y):
if y == 0:
raise ZeroDivisionError("除数不能为零")
return x / y
try:
result = divide(10, 0)
except ZeroDivisionError as e:
print(f"发生了异常: {e}")模块和包
导入模块
python
# 导入整个模块
import math
print(math.pi) # 3.141592653589793
print(math.sqrt(16)) # 4.0
# 导入模块中的特定函数
from math import pi, sqrt
print(pi) # 3.141592653589793
print(sqrt(16)) # 4.0
# 导入模块中的所有函数
from math import *
print(pi) # 3.141592653589793
print(sqrt(16)) # 4.0
# 给模块起别名
import math as m
print(m.pi) # 3.141592653589793
# 给函数起别名
from math import sqrt as square_root
print(square_root(16)) # 4.0创建和使用包
包是一个包含多个模块的目录,目录下必须有一个 __init__.py 文件(可以为空)。
my_package/
├── __init__.py
├── module1.py
└── module2.py导入包中的模块:
python
# 导入包中的模块
import my_package.module1
from my_package import module2
from my_package.module1 import function1面向对象编程
类和对象
python
# 定义类
class Person:
# 类属性
species = "Human"
# 初始化方法
def __init__(self, name, age):
# 实例属性
self.name = name
self.age = age
# 实例方法
def greet(self):
print(f"Hello, my name is {self.name} and I am {self.age} years old.")
# 类方法
@classmethod
def change_species(cls, new_species):
cls.species = new_species
# 静态方法
@staticmethod
def is_adult(age):
return age >= 18
# 创建对象
person1 = Person("Alice", 20)
person2 = Person("Bob", 15)
# 访问实例属性
print(person1.name) # Alice
print(person1.age) # 20
# 调用实例方法
person1.greet() # Hello, my name is Alice and I am 20 years old.
# 访问类属性
print(Person.species) # Human
print(person1.species) # Human
# 调用类方法
Person.change_species("Homosapiens")
print(Person.species) # Homosapiens
print(person1.species) # Homosapiens
# 调用静态方法
print(Person.is_adult(20)) # True
print(Person.is_adult(15)) # False继承
python
# 父类
class Animal:
def __init__(self, name):
self.name = name
def eat(self):
print(f"{self.name} is eating.")
# 子类
class Dog(Animal):
def __init__(self, name, breed):
# 调用父类的初始化方法
super().__init__(name)
self.breed = breed
def bark(self):
print(f"{self.name} is barking.")
# 子类
class Cat(Animal):
def __init__(self, name, color):
super().__init__(name)
self.color = color
def meow(self):
print(f"{self.name} is meowing.")
# 创建对象
dog = Dog("Buddy", "Labrador")
cat = Cat("Kitty", "White")
# 调用父类方法
dog.eat() # Buddy is eating.
cat.eat() # Kitty is eating.
# 调用子类方法
dog.bark() # Buddy is barking.
cat.meow() # Kitty is meowing.多态
python
class Animal:
def __init__(self, name):
self.name = name
def make_sound(self):
pass
class Dog(Animal):
def make_sound(self):
return "Woof!"
class Cat(Animal):
def make_sound(self):
return "Meow!"
class Cow(Animal):
def make_sound(self):
return "Moo!"
# 多态演示
def animal_sound(animal):
print(f"{animal.name} says {animal.make_sound()}")
dog = Dog("Buddy")
cat = Cat("Kitty")
cow = Cow("Bessie")
animal_sound(dog) # Buddy says Woof!
animal_sound(cat) # Kitty says Meow!
animal_sound(cow) # Bessie says Moo!封装
python
class Person:
def __init__(self, name, age):
self.__name = name # 私有属性
self.__age = age # 私有属性
# getter 方法
def get_name(self):
return self.__name
def get_age(self):
return self.__age
# setter 方法
def set_age(self, age):
if age > 0:
self.__age = age
else:
print("年龄必须大于 0")
person = Person("Alice", 20)
# 无法直接访问私有属性
# print(person.__name) # AttributeError: 'Person' object has no attribute '__name'
# 使用 getter 方法访问私有属性
print(person.get_name()) # Alice
print(person.get_age()) # 20
# 使用 setter 方法修改私有属性
person.set_age(21)
print(person.get_age()) # 21
person.set_age(-5) # 年龄必须大于 0
print(person.get_age()) # 21总结
Python 语法基础包括变量和数据类型、运算符、控制流、函数、列表、字典、字符串、异常处理、模块和包以及面向对象编程等内容。掌握这些基础语法是学习 Python 的第一步,也是后续学习更高级内容的基础。
