Python 入门教学

安装 Python

前往 Python 官网 下载最新版本并安装。安装时勾选 "Add Python to PATH" 选项,确保命令行可以直接调用 Python。

验证安装是否成功:

python --version

或(适用于 Python 3.x):

python3 --version

基本语法

Python 使用缩进(通常是 4 个空格)表示代码块,不需要分号结尾。
示例:

if 5 > 2:
    print("Five is greater than two!")

变量与数据类型

Python 是动态类型语言,无需声明变量类型:

x = 5          # 整数(int)
y = "Hello"    # 字符串(str)
z = 3.14       # 浮点数(float)
a = True       # 布尔值(bool)

运算符

支持算术、比较和逻辑运算符:

print(10 + 5)   # 加法
print(10 == 5)  # 等于比较
print(10 > 5 and 20 > 10)  # 逻辑与

控制流
  • 条件语句

    if x > 0:
        print("Positive")
    elif x == 0:
        print("Zero")
    else:
        print("Negative")
    

  • 循环

    for i in range(5):  # 输出 0 到 4
        print(i)
    
    while x > 0:
        print(x)
        x -= 1
    

函数

使用 def 定义函数:

def greet(name):
    return "Hello, " + name

print(greet("Alice"))

列表与字典
  • 列表(List):有序可变集合

    fruits = ["apple", "banana", "cherry"]
    print(fruits[1])       # 输出 "banana"
    fruits.append("orange")  # 添加元素
    

  • 字典(Dict):键值对集合

    person = {"name": "John", "age": 30}
    print(person["name"])  # 输出 "John"
    

文件操作

读写文件示例:

# 写入文件
with open("test.txt", "w") as f:
    f.write("Hello, World!")

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

模块与库

使用 import 导入模块:

import math
print(math.sqrt(16))  # 输出 4.0

# 安装第三方库(如 requests)
# 命令行执行:pip install requests

实践建议
  1. 从简单项目入手,如计算器或待办事项列表。
  2. 使用 Jupyter Notebook 或 VS Code 作为开发环境。
  3. 参考官方文档解决具体问题。
学习资源

更多推荐