Python 基础的教程 Python 的基本语法和常用功能。

Python 基础的教程

1. Python 简介与环境搭建

Python 是一种高级、解释型、面向对象的编程语言,因其简洁易读的语法而广受欢迎。

首先,你需要安装 Python 环境。可以从 [Python 官方网站] 下载并安装最新版本(推荐 Python 3.9 及以上)。安装完成后,可以通过命令行验证是否安装成功:

python --version

2. 基本语法与变量

Python 使用缩进来表示代码块,而不是使用大括号。下面是 Python 的基本语法示例:

# 这是一个注释
print("Hello, World!")  # 输出 Hello, World!

# 变量赋值不需要声明类型
x = 5
y = "John"
print(x)  # 输出 5
print(y)  # 输出 John

# 变量类型可以动态改变
x = "Hello"
print(x)  # 输出 Hello

3. 数据类型

Python 有多种内置数据类型,包括:

  • 数值类型:整数(int)、浮点数(float)、复数(complex)
  • 字符串(str)
  • 布尔值(bool):True 或 False
  • 列表(list):有序且可修改的集合
  • 元组(tuple):有序且不可修改的集合
  • 集合(set):无序且无重复元素的集合
  • 字典(dict):无序的键值对集合

下面是一些示例:

# 数值类型
a = 10        # 整数
b = 3.14      # 浮点数
c = 1 + 2j    # 复数

# 字符串
s1 = 'Hello'
s2 = "World"
print(s1 + " " + s2)  # 输出 Hello World

# 布尔值
is_valid = True
is_empty = False

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

# 元组
coordinates = (10, 20)
# coordinates[0] = 30  # 错误:元组不可修改

# 集合
numbers = {1, 2, 3, 3}  # 集合会自动去重
print(numbers)  # 输出 {1, 2, 3}

# 字典
person = {"name": "John", "age": 36, "city": "New York"}
print(person["name"])  # 输出 John

4. 条件语句

Python 使用 ifelifelse 来实现条件判断:

x = 20
if x > 30:
    print("x 大于 30")
elif x < 30:
    print("x 小于 30")
else:
    print("x 等于 30")

5. 循环语句

Python 支持 forwhile 循环:

# for 循环
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

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

# 循环控制
for i in range(10):
    if i == 5:
        break  # 跳出循环
    print(i)

for i in range(10):
    if i % 2 == 0:
        continue  # 跳过当前循环
    print(i)

6. 函数

函数是组织好的、可重复使用的代码块:

def greet(name):
    """这是一个问候函数"""
    return "Hello, " + name

# 调用函数
message = greet("Alice")
print(message)  # 输出 Hello, Alice

# 带默认参数的函数
def multiply(a, b=2):
    return a * b

print(multiply(5))      # 输出 10
print(multiply(5, 3))   # 输出 15

7. 类与对象

Python 是面向对象的编程语言,支持类和对象:

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

    def greet(self):
        return f"Hello, my name is {self.name} and I am {self.age} years old."

# 创建对象
p1 = Person("John", 36)
print(p1.greet())  # 输出 Hello, my name is John and I am 36 years old.

8. 文件操作

Python 提供了内置的文件操作功能:

# 写入文件
with open("test.txt", "w") as file:
    file.write("Hello, World!\n")
    file.write("This is a test file.\n")

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

9. 异常处理

使用 tryexceptfinally 来处理异常:

try:
    result = 10 / 0  # 会引发 ZeroDivisionError
except ZeroDivisionError:
    print("Error: division by zero")
finally:
    print("This code will run no matter what")

10. 模块与包

Python 允许将代码组织成模块和包:

# 创建一个模块(例如:math_operations.py)
def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

# 在另一个文件中导入模块
import math_operations

result = math_operations.add(5, 3)
print(result)  # 输出 8

以上就是 Python 的基础教程。通过学习这些内容,你可以掌握 Python 的基本语法和常用功能,为进一步学习 Python 的高级特性和应用打下基础。

posted @ 2025-11-05 15:20  恰逢其时2008  阅读(14)  评论(0)    收藏  举报