学习资料

Python编程入门教程——从零开始学编程

20 阅读 2026-06-03
内容简介

系统讲解Python编程基础,涵盖变量与数据类型、控制结构、函数、列表与字典、文件操作、面向对象编程等,配合大量编程实例。

Python编程入门教程——从零开始学编程

概述

Python是当今最受欢迎的编程语言之一,以其简洁优雅的语法和强大的功能著称。无论是数据分析、人工智能、Web开发还是自动化脚本,Python都能胜任。本教程将系统讲解Python编程的基础知识,从最基本的变量和数据类型开始,逐步介绍控制结构、函数、列表与字典、文件操作和面向对象编程,配合大量编程实例,帮助零基础的读者快速入门。

Python的设计哲学是"优雅"、"明确"、"简单"。它的语法接近自然语言,使得初学者能够专注于解决问题的逻辑,而不是纠结于复杂的语法规则。


知识点一:变量与数据类型

1.1 变量

变量:用来存储数据的容器。在Python中,变量不需要声明类型,直接赋值即可。

name = "小明"          # 字符串类型
age = 18               # 整数类型
height = 1.75          # 浮点数类型
is_student = True      # 布尔类型

变量命名规则

  • 由字母、数字和下划线组成
  • 不能以数字开头
  • 区分大小写
  • 不能使用Python关键字(如if、for、while等)

推荐命名方式:使用有意义的英文单词,多个单词用下划线连接(snake_case)。

student_name = "小明"     # 推荐
studentName = "小明"      # 也常见(驼峰命名)
x = "小明"                # 不推荐(含义不明确)

1.2 基本数据类型

数据类型 说明 示例
int 整数 42, -10, 0
float 浮点数 3.14, -0.5, 1.0
str 字符串 "hello", 'Python'
bool 布尔值 True, False
NoneType 空值 None

类型转换

# 字符串转整数
age = int("18")           # 18

# 整数转字符串
text = str(42)            # "42"

# 字符串转浮点数
price = float("9.99")     # 9.99

# 判断类型
type(42)                  # <class 'int'>
type("hello")             # <class 'str'>

1.3 字符串操作

# 字符串拼接
greeting = "你好," + "世界!"    # "你好,世界!"

# 字符串格式化
name = "小明"
age = 18
info = f"我叫{name},今年{age}岁"   # f-string格式化

# 字符串常用方法
text = "Hello, Python"
text.lower()          # "hello, python"
text.upper()          # "HELLO, PYTHON"
text.replace("Python", "World")  # "Hello, World"
text.split(",")       # ["Hello", " Python"]
text.strip()          # 去除首尾空格
len(text)             # 字符串长度

1.4 运算符

# 算术运算符
10 + 3      # 13(加)
10 - 3      # 7(减)
10 * 3      # 30(乘)
10 / 3      # 3.3333(除)
10 // 3     # 3(整除)
10 % 3      # 1(取余)
10 ** 3     # 1000(幂)

# 比较运算符
5 == 5      # True(等于)
5 != 3      # True(不等于)
5 > 3       # True(大于)
5 <= 5      # True(小于等于)

# 逻辑运算符
True and False    # False(与)
True or False     # True(或)
not True          # False(非)

知识点二:控制结构

2.1 条件语句

if语句

score = 85

if score >= 90:
    print("优秀")
elif score >= 80:
    print("良好")
elif score >= 60:
    print("及格")
else:
    print("不及格")

三元表达式

age = 20
status = "成年" if age >= 18 else "未成年"

2.2 循环语句

for循环

# 遍历列表
fruits = ["苹果", "香蕉", "橙子"]
for fruit in fruits:
    print(fruit)

# 使用range()
for i in range(5):        # 0, 1, 2, 3, 4
    print(i)

for i in range(1, 11):    # 1到10
    print(i)

for i in range(0, 10, 2): # 0, 2, 4, 6, 8(步长为2)
    print(i)

while循环

# 计算1到100的和
total = 0
i = 1
while i <= 100:
    total += i
    i += 1
print(f"1到100的和为:{total}")

循环控制

# break - 跳出循环
for i in range(10):
    if i == 5:
        break
    print(i)  # 输出 0, 1, 2, 3, 4

# continue - 跳过本次循环
for i in range(10):
    if i % 2 == 0:
        continue
    print(i)  # 输出 1, 3, 5, 7, 9

2.3 嵌套循环

# 打印九九乘法表
for i in range(1, 10):
    for j in range(1, i + 1):
        print(f"{j}×{i}={i*j}", end="\t")
    print()  # 换行

知识点三:函数

3.1 函数的定义与调用

# 定义函数
def greet(name):
    """向某人打招呼"""
    print(f"你好,{name}!")

# 调用函数
greet("小明")  # 输出:你好,小明!

3.2 参数类型

# 位置参数
def add(a, b):
    return a + b

# 默认参数
def greet(name, greeting="你好"):
    print(f"{greeting},{name}!")

greet("小明")            # 你好,小明!
greet("小明", "早上好")   # 早上好,小明!

# 可变参数
def calc_sum(*args):
    return sum(args)

calc_sum(1, 2, 3, 4, 5)  # 15

# 关键字参数
def print_info(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

print_info(name="小明", age=18, city="北京")

3.3 返回值

# 返回单个值
def square(x):
    return x ** 2

# 返回多个值
def min_max(numbers):
    return min(numbers), max(numbers)

low, high = min_max([3, 1, 4, 1, 5, 9, 2, 6])
print(f"最小值:{low},最大值:{high}")

3.4 Lambda函数

# Lambda函数(匿名函数)
square = lambda x: x ** 2
print(square(5))  # 25

# 常与高阶函数配合使用
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
sorted_numbers = sorted(numbers, key=lambda x: -x)
print(sorted_numbers)  # [9, 6, 5, 4, 3, 2, 1, 1]

3.5 变量作用域

# 全局变量和局部变量
x = 10  # 全局变量

def func():
    x = 20  # 局部变量,与全局变量无关
    print(f"函数内 x = {x}")

func()      # 函数内 x = 20
print(f"函数外 x = {x}")  # 函数外 x = 10

# 使用global关键字修改全局变量
def func2():
    global x
    x = 20

func2()
print(f"x = {x}")  # x = 20

知识点四:列表与字典

4.1 列表

列表:有序的可变集合,可以存储任意类型的元素。

# 创建列表
fruits = ["苹果", "香蕉", "橙子"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", True, 3.14]

# 访问元素
print(fruits[0])     # "苹果"
print(fruits[-1])    # "橙子"(最后一个元素)

# 切片
print(numbers[1:4])  # [2, 3, 4]
print(numbers[:3])   # [1, 2, 3]
print(numbers[::2])  # [1, 3, 5](步长为2)

# 修改元素
fruits[0] = "草莓"

# 添加元素
fruits.append("葡萄")       # 末尾添加
fruits.insert(1, "西瓜")    # 在指定位置插入

# 删除元素
fruits.remove("香蕉")       # 删除指定元素
del fruits[0]               # 删除指定位置的元素
popped = fruits.pop()       # 弹出末尾元素

# 列表常用方法
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
len(numbers)         # 长度:8
numbers.sort()       # 排序:[1, 1, 2, 3, 4, 5, 6, 9]
numbers.reverse()    # 反转
numbers.count(1)     # 统计元素出现次数:2
numbers.index(4)     # 查找元素位置

列表推导式

# 基本语法:[表达式 for 变量 in 可迭代对象]
squares = [x**2 for x in range(1, 11)]
# [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

# 带条件的列表推导式
even_squares = [x**2 for x in range(1, 11) if x % 2 == 0]
# [4, 16, 36, 64, 100]

4.2 字典

字典:无序的键值对集合,键必须是不可变类型。

# 创建字典
student = {
    "name": "小明",
    "age": 18,
    "grades": [85, 92, 78]
}

# 访问元素
print(student["name"])           # "小明"
print(student.get("gender", "未知"))  # "未知"(键不存在时返回默认值)

# 修改/添加元素
student["age"] = 19              # 修改
student["gender"] = "男"         # 添加

# 删除元素
del student["grades"]
popped = student.pop("age")      # 弹出并返回

# 遍历字典
for key, value in student.items():
    print(f"{key}: {value}")

# 字典常用方法
student.keys()       # 所有键
student.values()     # 所有值
student.items()      # 所有键值对
len(student)         # 键值对数量

字典推导式

# 创建平方数字典
squares = {x: x**2 for x in range(1, 6)}
# {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

4.3 元组与集合

元组:有序的不可变集合。

# 创建元组
point = (3, 4)
colors = ("红", "绿", "蓝")

# 访问元素
print(point[0])  # 3

# 元组解包
x, y = point
print(f"x={x}, y={y}")

集合:无序的不重复元素集合。

# 创建集合
numbers = {1, 2, 3, 4, 5}
unique_numbers = set([1, 2, 2, 3, 3, 3])  # {1, 2, 3}

# 集合运算
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
a | b    # 并集:{1, 2, 3, 4, 5, 6}
a & b    # 交集:{3, 4}
a - b    # 差集:{1, 2}
a ^ b    # 对称差集:{1, 2, 5, 6}

知识点五:文件操作

5.1 文件读写

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

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

# 逐行读取
with open("test.txt", "r", encoding="utf-8") as f:
    for line in f:
        print(line.strip())     # strip()去除换行符

# 追加写入
with open("test.txt", "a", encoding="utf-8") as f:
    f.write("第三行内容\n")

文件打开模式

模式 说明
"r" 只读(默认)
"w" 写入(覆盖原内容)
"a" 追加
"r+" 读写
"b" 二进制模式(如"rb")

5.2 异常处理

try:
    result = 10 / 0
except ZeroDivisionError:
    print("不能除以零!")
except Exception as e:
    print(f"发生错误:{e}")
else:
    print("没有发生错误")
finally:
    print("无论是否发生错误都会执行")

知识点六:面向对象编程

6.1 类与对象

class Dog:
    # 类属性(所有实例共享)
    species = "犬科"
    
    # 构造方法
    def __init__(self, name, age):
        # 实例属性
        self.name = name
        self.age = age
    
    # 实例方法
    def bark(self):
        print(f"{self.name}说:汪汪!")
    
    # 特殊方法(字符串表示)
    def __str__(self):
        return f"Dog(name={self.name}, age={self.age})"

# 创建对象
dog1 = Dog("旺财", 3)
dog2 = Dog("小白", 2)

# 调用方法
dog1.bark()      # 旺财说:汪汪!
print(dog1)      # Dog(name=旺财, age=3)

6.2 继承

class Animal:
    def __init__(self, name):
        self.name = name
    
    def speak(self):
        raise NotImplementedError("子类必须实现此方法")

class Cat(Animal):
    def speak(self):
        return f"{self.name}说:喵喵!"

class Dog(Animal):
    def speak(self):
        return f"{self.name}说:汪汪!"

# 多态
animals = [Cat("小花"), Dog("旺财"), Cat("小白")]
for animal in animals:
    print(animal.speak())

6.3 封装

class BankAccount:
    def __init__(self, owner, balance=0):
        self.owner = owner
        self.__balance = balance  # 私有属性(双下划线开头)
    
    def deposit(self, amount):
        if amount > 0:
            self.__balance += amount
            print(f"存入{amount}元,余额{self.__balance}元")
        else:
            print("存款金额必须大于0")
    
    def withdraw(self, amount):
        if 0 < amount <= self.__balance:
            self.__balance -= amount
            print(f"取出{amount}元,余额{self.__balance}元")
        else:
            print("余额不足或金额无效")
    
    def get_balance(self):
        return self.__balance

account = BankAccount("小明", 1000)
account.deposit(500)       # 存入500元,余额1500元
account.withdraw(200)      # 取出200元,余额1300元
# account.__balance         # 无法直接访问私有属性
print(account.get_balance())  # 通过方法访问:1300

练习题

练习一:基础计算

编写一个程序,输入一个整数,判断它是奇数还是偶数,并输出结果。

答案

num = int(input("请输入一个整数:"))
if num % 2 == 0:
    print(f"{num}是偶数")
else:
    print(f"{num}是奇数")

练习二:列表操作

编写一个函数,接收一个数字列表,返回其中所有偶数的平方和。

答案

def even_square_sum(numbers):
    return sum(x**2 for x in numbers if x % 2 == 0)

# 测试
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
result = even_square_sum(data)
print(f"偶数平方和:{result}")  # 4+16+36+64+100 = 220

练习三:字典应用

编写一个程序,统计一段英文文本中每个单词出现的次数(不区分大小写)。

答案

def count_words(text):
    words = text.lower().split()
    word_count = {}
    for word in words:
        word = word.strip(".,!?;:'\"")
        if word:
            word_count[word] = word_count.get(word, 0) + 1
    return word_count

# 测试
text = "The quick brown fox jumps over the lazy dog. The dog barked at the fox."
result = count_words(text)
for word, count in sorted(result.items(), key=lambda x: -x[1]):
    print(f"{word}: {count}")

练习四:文件处理

编写一个程序,读取一个文本文件,统计其中的行数、单词数和字符数。

答案

def file_stats(filename):
    lines = 0
    words = 0
    chars = 0
    try:
        with open(filename, "r", encoding="utf-8") as f:
            for line in f:
                lines += 1
                words += len(line.split())
                chars += len(line)
        print(f"行数:{lines}")
        print(f"单词数:{words}")
        print(f"字符数:{chars}")
    except FileNotFoundError:
        print(f"文件 {filename} 不存在")

# 使用
file_stats("test.txt")

练习五:面向对象编程

设计一个"学生"类,包含姓名、年龄和成绩列表三个属性。要求能够添加成绩、计算平均分、显示学生信息。

答案

class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age
        self.scores = []
    
    def add_score(self, score):
        if 0 <= score <= 100:
            self.scores.append(score)
            print(f"添加成绩:{score}分")
        else:
            print("成绩应在0-100之间")
    
    def average_score(self):
        if not self.scores:
            return 0
        return sum(self.scores) / len(self.scores)
    
    def __str__(self):
        avg = self.average_score()
        return (f"学生信息:\n"
                f"  姓名:{self.name}\n"
                f"  年龄:{self.age}\n"
                f"  成绩:{self.scores}\n"
                f"  平均分:{avg:.1f}")

# 测试
student = Student("小明", 18)
student.add_score(85)
student.add_score(92)
student.add_score(78)
student.add_score(95)
print(student)

# 输出:
# 学生信息:
#   姓名:小明
#   年龄:18
#   成绩:[85, 92, 78, 95]
#   平均分:87.5

总结

Python编程入门教程涵盖了以下核心知识:

  1. 变量与数据类型:理解Python的基本数据类型和类型转换
  2. 控制结构:掌握条件语句和循环语句的使用
  3. 函数:学会定义和调用函数,理解参数类型和作用域
  4. 列表与字典:掌握Python最常用的两种数据结构
  5. 文件操作:学会读写文件和异常处理
  6. 面向对象编程:理解类、对象、继承和封装的概念

学习Python编程的关键是多动手实践。建议同学们在学习每个知识点后,尝试编写小程序来巩固理解。Python的社区非常活跃,遇到问题时可以查阅官方文档或在技术论坛上寻求帮助。

编程是一项需要不断练习的技能,不要害怕犯错。每一个错误都是学习的机会。保持好奇心和耐心,你一定能掌握Python编程!

文章声明

本文仅供学习和参考,不构成任何投资建议。如有侵权,请联系删除。

目录