找回密码
 立即注册
搜索
热搜: 活动 交友
查看: 17|回复: 0

Python 学习笔记

[复制链接]
发表于 2025-3-22 00:21:47 | 显示全部楼层 |阅读模式
1. Python 简介

Python 是一种高级编程语言,以其简洁的语法和强大的库而受到广泛欢迎。它支持多种编程范式,包括面向对象、命令式和功能性编程。

2. 安装 Python
- 官网下载安装:
  访问 [Python 官网](https://www.python.org/) 下载适合你操作系统的版本。

- 安装步骤:
  1. 下载并运行安装程序。
  2. 勾选“Add Python to PATH”选项。
  3. 按照提示完成安装。

3. 基础语法
3.1 打印输出
```python
print("Hello, World!")
```

3.2 变量和数据类型
```python
name = "Alice"   # 字符串
age = 25         # 整数
height = 1.65    # 浮点数
is_student = True # 布尔值
```

3.3 数据结构
- 列表:
  ```python
  fruits = ["apple", "banana", "cherry"]
  ```

- 元组:
```python
  coordinates = (10, 20)
  ```

- 字典:
  ```python
  student = {"name": "Alice", "age": 25}
  ```

4. 控制结构
4.1 条件语句
```python
if age >= 18:
    print("成年人")
else:
    print("未成年人")
```

4.2 循环结构
- for 循环:
```python
  for fruit in fruits:
      print(fruit)
  ```

- while 循环:
  ```python
  count = 0
  while count < 5:
      print(count)
      count += 1
  ```

5. 函数
5.1 定义函数
```python
def greet(name):
    return f"Hello, {name}!"
```

5.2 调用函数
```python
print(greet("Alice"))
```

6. 常用模块
- math:提供数学函数。
  ```python
  import math
  print(math.sqrt(16))
  ```

- datetime:处理日期和时间。
  ```python
  import datetime
  now = datetime.datetime.now()
  print(now)
  ```

7. 文件操作
7.1 读取文件
```python
with open("example.txt", "r") as file:
    contents = file.read()
    print(contents)
```

7.2 写入文件
```python
with open("example.txt", "w") as file:
    file.write("Hello, World!")
```

8. 异常处理
```python
try:
    result = 10 / 0
except ZeroDivisionError:
    print("除以零错误!")
finally:
    print("执行完毕。")
```

9. 面向对象编程
9.1 定义类
```python
class Dog:
    def __init__(self, name):
        self.name = name


    def bark(self):
        return f"{self.name} says woof!"
```

9.2 创建对象
```python
dog = Dog("Buddy")
print(dog.bark())
```

10. 总结
Python 是一门易于学习和使用的编程语言,适合于各种应用开发。掌握其基本语法和常用功能后,可以进一步探索数据分析、机器学习、Web 开发等领域。


您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|星星学习网

GMT+8, 2025-4-22 08:23 , Processed in 0.100055 second(s), 15 queries .

Powered by Discuz! X3.5

© 2001-2025 Discuz! Team.

快速回复 返回顶部 返回列表