DukeDuke
主页
文档转换
关于我们
主页
文档转换
关于我们
  • 什么是Python
  • Python简介
  • Python安装
  • Python基础语法
  • Python数据类型
  • Python数字
  • Python字符串
  • Python列表
  • Python元组
  • Python字典
  • Python日期时间
  • Python文件操作
  • Python异常处理
  • Python函数
  • Python类
  • Python模块
  • Python包
  • Python多线程
  • Python面向对象
  • Python爬虫
  • Django web框架

Python 基础语法

1. 变量和数据类型

1.1 变量

  • Python 是动态类型语言,变量不需要预先声明类型
  • 变量名区分大小写
  • 命名规则:字母、数字、下划线组成,不能以数字开头
name = "张三"  # 字符串
age = 25      # 整数
height = 1.75 # 浮点数
is_student = True  # 布尔值

1.2 基本数据类型

  • 数字(Numbers):整数(int)、浮点数(float)、复数(complex)
  • 字符串(String):使用单引号或双引号
  • 布尔值(Boolean):True 或 False
  • 列表(List):有序、可变
  • 元组(Tuple):有序、不可变
  • 字典(Dictionary):键值对
  • 集合(Set):无序、不重复
# 数字
x = 10
y = 3.14
z = 1 + 2j

# 字符串
s1 = 'Hello'
s2 = "World"

# 列表
fruits = ['apple', 'banana', 'orange']

# 元组
coordinates = (10, 20)

# 字典
person = {'name': '张三', 'age': 25}

# 集合
unique_numbers = {1, 2, 3, 4, 5}

2. 运算符

2.1 算术运算符

  • +:加法
  • -:减法
  • *:乘法
  • /:除法
  • //:整除
  • %:取余
  • **:幂运算

2.2 比较运算符

  • ==:等于
  • !=:不等于
  • >:大于
  • <:小于
  • >=:大于等于
  • <=:小于等于

2.3 逻辑运算符

  • and:与
  • or:或
  • not:非

3. 控制流

3.1 条件语句

if condition:
    # 代码块
elif another_condition:
    # 代码块
else:
    # 代码块

3.2 循环语句

# for 循环
for i in range(5):
    print(i)

# while 循环
count = 0
while count < 5:
    print(count)
    count += 1

4. 函数

4.1 函数定义

def function_name(parameters):
    """
    函数文档字符串
    """
    # 函数体
    return result

4.2 函数调用

def greet(name):
    return f"Hello, {name}!"

message = greet("张三")

5. 模块和包

5.1 导入模块

import math
from datetime import datetime
import numpy as np

5.2 创建模块

# mymodule.py
def my_function():
    pass

# 在其他文件中使用
import mymodule
mymodule.my_function()

6. 异常处理

try:
    # 可能发生异常的代码
    result = 10 / 0
except ZeroDivisionError:
    # 处理特定异常
    print("除数不能为零")
except Exception as e:
    # 处理其他异常
    print(f"发生错误:{e}")
finally:
    # 无论是否发生异常都会执行
    print("清理工作")

7. 文件操作

7.1 读取文件

with open('file.txt', 'r', encoding='utf-8') as f:
    content = f.read()

7.2 写入文件

with open('file.txt', 'w', encoding='utf-8') as f:
    f.write('Hello, World!')

8. 面向对象编程

8.1 类定义

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

    def greet(self):
        return f"你好,我是{self.name},今年{self.age}岁"

8.2 对象创建和使用

person = Person("张三", 25)
print(person.greet())
最近更新:: 2026/4/17 13:21
Contributors: Duke
Prev
Python安装
Next
Python数据类型