杰瑞科技汇

learning python 代码

太棒了!学习 Python 是一个非常棒的选择,它语法简洁、功能强大,应用领域极广(从网站开发、数据分析到人工智能)。

learning python 代码-图1
(图片来源网络,侵删)

下面我为你整理了一份从零开始、循序渐进的 Python 学习代码指南,包含了从基础语法到实际项目案例的完整路径,你可以跟着这个路线图,一步步敲代码、理解概念。


学习路线图

  1. 第一步:环境准备
  2. 第二步:Python 基础语法
  3. 第三步:数据结构
  4. 第四步:函数
  5. 第五步:面向对象编程
  6. 第六步:模块与包
  7. 第七步:文件操作
  8. 第八步:实战项目

第一步:环境准备

在写代码之前,你需要一个环境。

  1. 安装 Python

    • 访问 Python 官网
    • 下载并安装最新版的 Python。重要:在安装时,勾选 "Add Python to PATH" 选项。
    • 安装完成后,打开终端(Windows 是 cmdPowerShell,macOS/Linux 是 Terminal),输入 python --versionpython3 --version,如果能显示版本号,说明安装成功。
  2. 选择代码编辑器

    learning python 代码-图2
    (图片来源网络,侵删)
    • 强烈推荐 VS Code (Visual Studio Code):免费、强大、插件丰富。
      • 安装 VS Code。
      • 在插件商店搜索并安装 "Python" 插件(由 Microsoft 发布)。
    • 其他选择:PyCharm (专业,有免费版), Sublime Text。

第二步:Python 基础语法

这是编程的基石,打开你的编辑器,新建一个文件 hello.py,然后开始输入。

你的第一行代码:print()

print() 函数用于在屏幕上输出信息。

# 这是一个注释,解释代码,程序会忽略它
print("Hello, World!") 
print("你好,世界!")

变量与数据类型

变量是存储数据的容器,Python 是动态类型语言,你不需要声明变量类型。

# 字符串
name = "Alice"
message = 'Hello, ' + name  # 字符串可以用单引号或双引号
print(message)
# 整数
age = 25
print(f"Next year, I will be {age + 1} years old.") # f-string 是现代 Python 推荐的格式化字符串方式
# 浮点数
price = 19.99
print(f"The price is ${price}")
# 布尔值
is_student = True
print(f"Are you a student? {is_student}")
# 查看变量类型
print(type(name))   # <class 'str'>
print(type(age))    # <class 'int'>

基本运算

# 算术运算
a = 10
b = 3
print(a + b)  # 加法: 13
print(a - b)  # 减法: 7
print(a * b)  # 乘法: 30
print(a / b)  # 除法: 3.333...
print(a // b) # 整除: 3
print(a % b)  # 取余: 1
print(a ** b) # 幂运算: 1000
# 比较运算
print(a > b)  # True
print(a == b) # False
print(a != b) # True
# 逻辑运算
x = True
y = False
print(x and y) # 与: False
print(x or y)  # 或: True
print(not x)   # 非: False

用户输入

使用 input() 函数获取用户的键盘输入。

# input() 函数返回的永远是字符串
user_name = input("Please enter your name: ")
user_age_str = input("Please enter your age: ")
# 如果需要进行数学运算,需要将字符串转换为整数
user_age = int(user_age_str)
print(f"Welcome, {user_name}!")
print(f"In 5 years, you will be {user_age + 5} years old.")

第三步:数据结构

数据结构是用来组织和存储数据的集合。

列表 - List

列表是一个有序、可变(可以修改)的集合。

# 创建列表
fruits = ["apple", "banana", "cherry"]
print(fruits)
# 访问元素 (索引从 0 开始)
print(fruits[0])      # apple
print(fruits[-1])     # cherry (负数索引表示从后往前)
# 修改元素
fruits[1] = "blueberry"
print(fruits)
# 添加元素
fruits.append("orange") # 添加到末尾
fruits.insert(0, "mango") # 插入到指定位置
print(fruits)
# 删除元素
fruits.remove("cherry") # 删除指定值的元素
popped_fruit = fruits.pop() # 删除并返回最后一个元素
print(f"Popped fruit: {popped_fruit}")
print(fruits)
# 列表长度
print(len(fruits))

元组 - Tuple

元组是一个有序、不可变(创建后不能修改)的集合,通常用于存储不应改变的数据。

# 创建元组
coordinates = (10.0, 20.0)
print(coordinates)
# 访问元素
print(coordinates[0])
# 尝试修改会报错
# coordinates[0] = 15.0 # TypeError: 'tuple' object does not support item assignment

字典 - Dictionary

字典是一个无序的键值对集合,键必须是唯一的且不可变。

# 创建字典
student = {
    "name": "Bob",
    "age": 21,
    "courses": ["Math", "History"]
}
print(student)
# 访问值
print(student["name"])
print(student.get("age")) # 使用 get 方法更安全,如果键不存在会返回 None 而不是报错
# 修改和添加值
student["age"] = 22
student["major"] = "Computer Science"
print(student)
# 删除键值对
del student["courses"]
print(student)

集合 - Set

集合是一个无序、不包含重复元素的集合,常用于去重和数学运算(如交集、并集)。

# 创建集合
numbers = {1, 2, 2, 3, 4, 4, 5}
print(numbers) # 输出: {1, 2, 3, 4, 5} (重复的 2 和 4 被去除了)
# 添加元素
numbers.add(6)
print(numbers)
# 移除元素
numbers.discard(2) # 如果元素不存在,不会报错
print(numbers)

第四步:函数

函数是组织好的、可重复使用的、用来实现单一或相关联功能的代码块。

# 定义一个简单的函数
def greet(name):
    """这是一个文档字符串,用来解释函数的功能"""
    return f"Hello, {name}!"
# 调用函数
message = greet("Charlie")
print(message)
# 带有默认参数的函数
def power(base, exponent=2):
    """计算 base 的 exponent 次方"""
    return base ** exponent
print(power(3))      # 使用默认 exponent=2,结果为 9
print(power(3, 3))   # 指定 exponent=3,结果为 27

第五步:面向对象编程

OOP 是一种编程思想,它将数据和处理数据的方法封装在“对象”中。

类和对象

  • :创建对象的“蓝图”或“模板”。
  • 对象:类的具体实例。
# 定义一个 Dog 类
class Dog:
    # __init__ 是构造函数,当创建对象时自动调用
    def __init__(self, name, age):
        self.name = name  # self.name 是实例属性
        self.age = age
    # 定义一个方法(函数)
    def bark(self):
        return f"{self.name} says: Woof!"
    def celebrate_birthday(self):
        self.age += 1
        return f"Happy birthday, {self.name}! You are now {self.age}."
# 创建 Dog 类的对象(实例)
my_dog = Dog("Rex", 5)
your_dog = Dog("Buddy", 3)
# 访问对象的属性
print(f"{my_dog.name} is {my_dog.age} years old.")
print(f"{your_dog.name} is {your_dog.age} years old.")
# 调用对象的方法
print(my_dog.bark())
print(your_dog.bark())
print(my_dog.celebrate_birthday())
print(f"Now, {my_dog.name} is {my_dog.age} years old.")

第六步:模块与包

模块是一个 .py 文件,包是一个包含多个模块的文件夹,它们能让你的代码更有条理,并且可以复用别人的代码。

使用内置模块

Python 自带了很多强大的模块。

# 使用 random 模块生成随机数
import random
print(random.randint(1, 10)) # 生成 1 到 10 之间的一个随机整数
print(random.choice(['apple', 'banana', 'cherry'])) # 从列表中随机选择一个元素
# 使用 math 模块进行数学计算
import math
print(math.pi)
print(math.sqrt(16)) # 16 的平方根

安装和使用第三方包

使用 pip (Python 的包安装器) 来安装第三方包。

  1. 打开终端。

  2. 安装一个流行的数据处理库 pandas

    pip install pandas
  3. 在你的代码中导入并使用它:

    import pandas as pd
    # 创建一个简单的数据框
    data = {'Name': ['Tom', 'Nick', 'John'], 'Age': [28, 34, 29]}
    df = pd.DataFrame(data)
    print(df)

    输出:

      Name  Age
    0    Tom   28
    1   Nick   34
    2   John   29

第七步:文件操作

Python 可以轻松地读写文件。

写入文件

# 使用 'w' 模式写入,如果文件不存在则创建,如果存在则覆盖
with open("my_file.txt", "w", encoding="utf-8") as f:
    f.write("Hello, this is the first line.\n")
    f.write("This is the second line.\n")
print("File written successfully.")

读取文件

# 使用 'r' 模式读取
with open("my_file.txt", "r", encoding="utf-8") as f:
    # 读取全部内容
    content = f.read()
    print("--- Reading all content ---")
    print(content)
    # 逐行读取
    print("\n--- Reading line by line ---")
    f.seek(0) # 将文件指针移回开头
    for line in f:
        print(line.strip()) # strip() 用于去除行首尾的空白字符

第八步:实战项目

理论知识学完后,通过项目来巩固是最好的方式。

简单的猜数字游戏

这个游戏能让你练习 random, input, 循环, 条件判断

import random
def guess_the_number():
    print("欢迎来到猜数字游戏!")
    secret_number = random.randint(1, 100)
    attempts = 0
    while True:
        try:
            guess_str = input("请猜一个 1 到 100 之间的数字: ")
            guess = int(guess_str)
            attempts += 1
            if guess < secret_number:
                print("太小了!")
            elif guess > secret_number:
                print("太大了!")
            else:
                print(f"恭喜你!你猜对了!数字就是 {secret_number}。")
                print(f"你总共猜了 {attempts} 次。")
                break
        except ValueError:
            print("无效输入,请输入一个整数。")
# 运行游戏
if __name__ == "__main__":
    guess_the_number()

简易待办事项列表

这个项目可以让你练习 列表, 函数, 循环, 文件操作

# todo_list.py
TODO_FILE = "todos.txt"
def load_todos():
    try:
        with open(TODO_FILE, "r", encoding="utf-8") as f:
            return f.read().splitlines()
    except FileNotFoundError:
        return []
def save_todos(todos):
    with open(TODO_FILE, "w", encoding="utf-8") as f:
        f.write("\n".join(todos))
def show_todos(todos):
    if not todos:
        print("你的待办事项列表是空的。")
    else:
        print("\n--- 你的待办事项 ---")
        for i, todo in enumerate(todos, 1):
            print(f"{i}. {todo}")
        print("--------------------\n")
def add_todo(todos):
    todo = input("请输入新的待办事项: ")
    todos.append(todo)
    save_todos(todos)
    print("待办事项已添加!")
def main():
    todos = load_todos()
    while True:
        print("请选择操作:")
        print("1. 查看待办事项")
        print("2. 添加待办事项")
        print("3. 退出")
        choice = input("请输入你的选择 (1/2/3): ")
        if choice == '1':
            show_todos(todos)
        elif choice == '2':
            add_todo(todos)
        elif choice == '3':
            print("再见!")
            break
        else:
            print("无效的选择,请重试。")
if __name__ == "__main__":
    main()

推荐资源

祝你学习愉快,早日成为 Python 高手!编程最重要的就是多动手、多思考、多练习

分享:
扫描分享到社交APP
上一篇
下一篇