Python 入门

本贴最后更新于 275 天前,其中的信息可能已经东海扬尘

1. 环境搭建

1.1 安装 Python

  • 官网下载:https://www.python.org/downloads/

  • image

  • 下载完成以后打开 exe 文件,一定要勾选**Add Python to PATH**,点击“Install Now”开始安装就行。

  • 安装完成后,按下 Win + R 组合键,打开“运行”窗口,输入 cmd 并回车,打开命令提示符。

    在命令提示符中输入 python --version 并回车,如果显示出你安装的 Python 版本号,说明安装成功。‌

    python --version
    

1.2 安装开发工具

  • IDLE(Python 自带)
  • VS Code
  • PyCharm (推荐使用)
  • Jupyter Notebook (数据分析常用)
  • Cursor (AI 编辑器)

2. 基础语法

2.1 第一个程序

print("Hello, World!")

2.2 变量与数据类型

# 基本类型
name = "Alice"      # 字符串
age = 25            # 整数
height = 1.75       # 浮点数
is_student = True   # 布尔值

2.3 输入输出

name = input("请输入你的名字:")
print(f"你好,{name}!")

3. 控制流

3.1 条件语句

score = 85
if score >= 90:
    print("优秀")
elif score >= 60:
    print("合格")
else:
    print("不及格")

3.2 循环结构

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

# while循环
count = 0
while count < 3:
    print("循环中...")
    count += 1

3.3 循环控制语句

# break语句:跳出整个循环
for num in range(1, 10):
    if num > 5:
        break
    print(num)  # 输出1-5

# continue语句:跳过当前迭代
for num in range(10):
    if num % 2 == 0:
        continue
    print(num)  # 输出所有奇数

# else子句:循环正常结束时执行
for n in range(2, 5):
    if n % 3 == 0:
        break
else:
    print("循环完整执行完毕")

3.4 异常处理

try:
    age = int(input("请输入年龄:"))
    print(f"你的年龄是{age}")
except ValueError:
    print("输入的不是有效数字!")
except:
    print("发生未知错误")
else:
    print("输入验证成功")
finally:
    print("---输入流程结束---")

4. 常用数据结构

4.1 列表(List)

fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
print(fruits[0])  # 输出第一个元素

4.2 字典(Dict)

person = {
    "name": "Bob",
    "age": 30,
    "city": "New York"
}
print(person["name"])

4.3 元组(Tuple,不常用,知道有就行)

# 不可变序列
colors = ("red", "green", "blue")
print(colors[1])     # green
# colors[1] = "yellow"  # 会报错

# 解包赋值
x, y, z = (10, 20, 30)
print(y)  # 20

4.3 集合(Set,不常用,知道有就行)

# 唯一元素的无序集合
unique_nums = {1, 2, 2, 3, 3, 3}
print(unique_nums)  # {1, 2, 3}

# 集合运算
A = {1,2,3}
B = {3,4,5}
print(A | B)  # 并集 {1,2,3,4,5}
print(A & B)  # 交集 {3}

5. 函数

5.1 函数定义与调用

# 定义函数
def greet(name):
    """这是一个问候函数"""  # 文档字符串
    print(f"Hello, {name}!")

# 调用函数
greet("Alice")  # 输出:Hello, Alice!

5.2 参数传递

# 默认参数
def power(base, exponent=2):
    return base ** exponent

print(power(3))     # 输出 9(3^2)
print(power(2, 3))  # 输出 8(2^3)

# 关键字参数
def person_info(name, age, city):
    print(f"{name}, {age}岁, 来自{city}")

person_info(city="北京", name="李雷", age=25)

5.3 变量作用域

global_var = "全局变量"

def test_scope():
    local_var = "局部变量"
    print(global_var)  # 可以访问全局变量
    print(local_var)   # 可以访问局部变量

test_scope()
# print(local_var)  # 这里会报错(局部变量外部不可访问)

5.4 Lambda 表达式(不太常用,容易让代码变复杂,知道就行)

# 匿名函数示例
square = lambda x: x ** 2
print(square(5))  # 输出 25

# 结合map使用
numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x**2, numbers))
print(squared)  # 输出 [1, 4, 9, 16]

5.5 递归函数(不常用,知道有就行)

# 计算阶乘
def factorial(n):
    if n == 1:
        return 1
    else:
        return n * factorial(n-1)

print(factorial(5))  # 输出 120

注意:递归需要有终止条件,否则会导致栈溢出

6. 文件操作

6.1 文件读写基础

# 写入文件
with open("demo.txt", "w", encoding="utf-8") as f:
    f.write("这是第一行\n")
    f.write("这是第二行")

# 读取文件
with open("demo.txt", "r", encoding="utf-8") as f:
    content = f.read()
    print(content)

6.2 文件模式说明

模式 描述
r 只读(默认)
w 写入(覆盖原有内容)
a 追加写入
b 二进制模式(如:rb
+ 读写模式(如:r+

6.3 异常处理

try:
    with open("non_exist.txt", "r") as f:
        print(f.read())
except FileNotFoundError:
    print("文件不存在!")
except Exception as e:
    print(f"发生错误:{str(e)}")
finally:
    print("操作结束")

7. 进阶主题

# 导入标准库
import math
print(math.sqrt(16))  # 输出 4.0

# 导入自定义模块
# (假设存在 my_module.py)
# from my_module import my_function

7.2 面向对象编程

class Dog:
    # 类属性
    species = "Canis familiaris"

    def __init__(self, name, age):
        # 实例属性
        self.name = name
        self.age = age

    def bark(self):
        print(f"{self.name} 在汪汪叫!")

# 创建实例
my_dog = Dog("Buddy", 3)
my_dog.bark()  # 输出:Buddy 在汪汪叫!

8. 实战项目

8.1 简易计算器

while True:
    num1 = float(input("输入第一个数字: "))
    num2 = float(input("输入第二个数字: "))
  
    if operator == "+":
        result = num1 + num2
    elif operator == "-":
        result = num1 - num2
    # ...其他运算符处理
  
    print(f"结果: {result}")

8.2 待办事项列表

todos = []
while True:
    task = input("输入任务(或输入q退出): ")
    if task == "q":
        break
    todos.append(task)
  
print("\n你的待办事项:")
for index, task in enumerate(todos, 1):
    print(f"{index}. {task}")

8.3 天气查询工具

import requests

city = input("请输入要查询的城市:")
url = f"http://wttr.in/{city}?format=3"
response = requests.get(url)
print(response.text)  # 示例输出:北京: 🌦 +22°C

8.4 密码管理器

import json

passwords = {}

def add_password():
    website = input("网站名称:")
    username = input("用户名:")
    password = input("密码:")
    passwords[website] = {"username": username, "password": password}

def save_data():
    with open("passwords.json", "w") as f:
        json.dump(passwords, f)

# 主程序入口
if __name__ == '__main__':
	# 函数调用
	add_password()
	save_data()

# 主程序循环...

9. 模块与包

9.1 常用标准库

模块 用途
math 数学运算
random 生成随机数
datetime 日期时间处理
os 操作系统接口
json JSON 数据处理
# 使用datetime模块示例
from datetime import datetime
now = datetime.now()
print(f"当前时间:{now:%Y-%m-%d %H:%M}")

  • Python

    Python 是一种面向对象、直译式电脑编程语言,具有近二十年的发展历史,成熟且稳定。它包含了一组完善而且容易理解的标准库,能够轻松完成很多常见的任务。它的语法简捷和清晰,尽量使用无异义的英语单词,与其它大多数程序设计语言使用大括号不一样,它使用缩进来定义语句块。

    561 引用 • 677 回帖 • 1 关注
2 操作
xiansui 在 2025-03-22 13:50:14 更新了该帖
xiansui 在 2025-03-22 12:36:00 更新了该帖

相关帖子

回帖

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...