本文详解Python基础知识:覆盖基础语法 函数与模块 数据结构和文件操作的基础知识和实战操作。

Python基础语法

变量与数据类型

创建变量

name = "wangt"
age = 20
is_student  = True

print(f"{name} is {age} years old")
  • 这里,nameageis_student就是变量,它们分别存储了不同的 数据

字符串

  • str = "hello world"
  • 字符串必须用引号(单引号'或双引号")括起来。

整数

  • 用于存储没有小数部分的数字,就像“魔法能量”的数量。
  • age = 21

浮点数

  • 用于存储带小数部分的数字,就像“魔法能量”的精确计量。
  • pi = 3.14159

布尔值

  • 用于存储真或假,就像“魔法开关”,只有开和关两种状态。
  • is_student = True
    is_teacher = False

列表

  • 用于存储有序的元素集合,就像“魔法口袋”里的一组物品。
  • list = ["apple", "banana", "cherry"]

字典

  • 用于存储键值对,就像“魔法钥匙”和“魔法锁”的一一对应。
  • person = {"name": "Alice", "age": 25}

元组

  • 用于存储不可变的元素集合,就像“魔法封印”,一旦设置就不能更改。
  • coordinates = (10.0, 20.0)

集合

  • 用于存储不重复的元素,就像“魔法过滤器”,去除重复项。
  • unique_numbers = {1, 2, 3, 4, 5}

变量的命名规则

  1. 只能包含字母、数字和下划线:例如,user_name、age_1、_private都是有效的变量名。
  2. 不能以数字开头:例如,1st_place是无效的变量名。
  3. 区分大小写:Name和name是两个不同的变量。
  4. 不能使用Python的保留字:例如,for、while、if等都是保留字,不能用作变量名。

运算符和表达式

基本的数学运算

  • +(加):a + b
  • -(减):a - b
  • *(乘):a * b
  • /(除):a / b
  • //(整除):a // b(返回商的整数部分)
  • %(取余):a % b(返回除法的余数)
  • **(幂):a ** b(返回a的b次方)

示例:

a = 2
b = 8
c = 9
d = 2.5
e = 12.5
print(f"+ = {a+b} - = {a-b} * = {a*b} / = {e/d} // = {e//a} % = {e%a} ** = {b**a}")

比较运算符

用于比较两个值,返回布尔值(True或False),就像施展“魔法比较”。

  • ==(等于):a == b
  • !=(不等于):a != b
  • >(大于):a > b
  • <(小于):a < b
  • >=(大于等于):a >= b
  • <=(小于等于):a <= b

示例:

is_equal = 5 == 5        # is_equal = True
is_not_equal = 5 != 5    # is_not_equal = False
is_greater = 10 > 5      # is_greater = True

逻辑运算符

用于组合多个条件表达式,返回布尔值,就像施展“魔法逻辑”。

  • and(与):a and b
  • or(或):a or b
  • not(非):not a

示例:

result = (5 > 3) and (10 < 20)  # result = True
result = (5 > 3) or (10 > 20)   # result = True
result = not (5 > 3)            # result = False

赋值运算符

用于给变量赋值,就像给“魔法口袋”装入物品。

  • =(简单赋值):a = b
  • +=(加赋值):a += b(等同于a = a + b
  • -=(减赋值):a -= b
  • *=(乘赋值):a *= b
  • /=(除赋值):a /= b
  • 其他类似

示例:

a = 10
a += 5    # a = 15
a *= 2    # a = 30

成员运算符

用于判断一个元素是否存在于一个序列中,就像施展“魔法探测”。

  • in:判断元素是否在序列中
  • not in:判断元素是否不在序列中

fruits = ["apple", "banana", "cherry"]
is_in = "banana" in fruits    # is_in = True
is_not_in = "orange" not in fruits  # is_not_in = True

控制结构

if elif else条件语句

age = 20
if age >= 18:
    print("你已经成年了!")

age = 16
if age >= 18:
    print("你已经成年了!")
else:
    print("你还未成年。")

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

循环语句

for 循环:用于遍历序列(如列表、元组、字符串等)中的元素

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

while循环:用于在满足某个条件时重复执行代码块。

count = 0
while count < 5:
    print(count)
    count += 1

函数与模块

定义与调用函数

定义函数:

def function():
    print("Hello World")

调用函数:

def function():
    print("Hello World")
function()

带参数的函数:

def function2(name):
    print("Hello " + name)
function2("wangt")

带返回值的函数:

def function3(a,b):
    return a+b
print(function3(5,6))

参数与返回值

位置参数:

def greet(name, age):
    print(f"你好,{name}!你{age}岁了。")
greet("Alice", 25)

关键字参数:

def describe_pet(animal_type, pet_name):
    print(f"我有一只{animal_type},它的名字叫{pet_name}。")
describe_pet(pet_name="Buddy", animal_type="狗")

默认参数:

def make_sandwich(bread, filling="火腿"):
    print(f"制作一个{bread}面包的{filling}三明治。")
make_sandwich("全麦")
make_sandwich("白面包", filling="鸡肉")
制作一个全麦面包的火腿三明治。
制作一个白面包的鸡肉三明治。

可变参数:

def make_pizza(size, *toppings, **options):
    print(f"制作一个{size}寸的披萨,配料有:")
    for topping in toppings:
        print(f"- {topping}")
    for option, value in options.items():
        print(f"{option}: {value}")
make_pizza(12, "蘑菇", "香肠", "洋葱", 配料="丰富", 口味="辣")

制作一个12寸的披萨,配料有:
- 蘑菇
- 香肠
- 洋葱
配料: 丰富
口味: 辣

模块与包

创建模块
你可以创建一个以.py结尾的Python文件,这就是一个模块。
示例
创建一个名为greetings.py的模块:

# greetings.py
def greet(name):
    print(f"你好,{name}!")

在另一个文件中导入并使用这个模块:

import greetings
greetings.greet("Alice")  # 输出:你好,Alice!

导入模块
使用import语句导入整个模块:

import math
print(math.sqrt(16))  # 输出:4.0

使用from ... import ...语句导入模块中的特定函数或类:

from math import sqrt
print(sqrt(25))  # 输出:5.0

import math as m
print(m.pi)  # 输出:3.141592653589793
from math import sqrt as square_root
print(square_root(36))  # 输出:6.0

创建包
创建一个目录,并在其中添加一个__init__.py文件。

示例
创建一个名为my_magic的包:

my_magic/
├── __init__.py
├── spells.py
└── utils.py

spells.py中定义一些函数:

# spells.py
def fireball():
    print("火球术!")

utils.py中定义一些工具函数:

# utils.py
def cast_spell(spell):
    print(f"施放{spell}!")

在主程序中导入并使用包中的模块:

from my_magic import spells, utils
spells.fireball()          # 输出:火球术!
utils.cast_spell("冰冻术")  # 输出:施放冰冻术!

数据结构

列表

fruits = ["苹果", "香蕉", "樱桃"]

这里,我们创建了一个名为fruits的列表,里面包含了三种水果。
访问元素
你可以通过索引来访问列表中的元素。

print(fruits[0])  # 输出:苹果
print(fruits[2])  # 输出:樱桃

添加元素
使用append()方法可以向列表末尾添加元素。

fruits.append("橙子")
print(fruits)  # 输出:["苹果", "蓝莓", "樱桃", "橙子"]

使用insert()方法可以在指定位置插入元素。

fruits.insert(1, "葡萄")
print(fruits)  # 输出:["苹果", "葡萄", "蓝莓", "樱桃", "橙子"]

删除元素
使用remove()方法可以删除指定的元素。

fruits.remove("蓝莓")
print(fruits)  # 输出:["苹果", "葡萄", "樱桃", "橙子"]

使用pop()方法可以删除指定索引位置的元素。

fruits.pop(2)
print(fruits)  # 输出:["苹果", "葡萄", "橙子"]

列表的其他操作
你可以对列表进行切片、遍历、排序等操作。

# 切片
print(fruits[0:2])  # 输出:["苹果", "葡萄"]
# 遍历
for fruit in fruits:
    print(fruit)
# 排序
fruits.sort()
print(fruits)  # 输出:["橙子", "葡萄", "苹果"]

元组

创建元组

coordinates = (10.0, 20.0)

访问元素
同样可以通过索引来访问元组中的元素。

print(coordinates[0])  # 输出:10.0
print(coordinates[1])  # 输出:20.0

元组的不可变性
你不能修改元组中的元素。

coordinates[0] = 15.0  # 这将引发错误

如果需要修改,可以将元组转换为列表,修改后再转换回元组。

coordinates_list = list(coordinates)
coordinates_list[0] = 15.0
coordinates = tuple(coordinates_list)
print(coordinates)  # 输出:(15.0, 20.0)

元组的其他操作
元组支持大多数列表的操作,但不支持修改操作。

# 切片
print(coordinates[0:1])  # 输出:(15.0,)
# 遍历
for coord in coordinates:
    print(coord)
# 长度
print(len(coordinates))  # 输出:2

字典

创建字典

person = {
    "姓名": "张三",
    "年龄": 28,
    "职业": "魔法师"
}

访问值
你可以通过键来访问对应的值。

print(person["姓名"])  # 输出:张三
print(person["年龄"])  # 输出:28

添加或修改键值对
直接通过键来添加或修改值。

person["年龄"] = 29  # 修改年龄
person["魔法等级"] = "高级"  # 添加新的键值对
print(person)
# 输出:{'姓名': '张三', '年龄': 29, '职业': '魔法师', '魔法等级': '高级'}

删除键值对
使用del语句删除指定的键值对。

del person["职业"]
print(person)
# 输出:{'姓名': '张三', '年龄': 29, '魔法等级': '高级'}

使用pop()方法也可以删除并返回指定键的值。

magic_level = person.pop("魔法等级")
print(magic_level)  # 输出:高级
print(person)
# 输出:{'姓名': '张三', '年龄': 29}

字典的其他操作
你可以遍历字典的键、值或键值对。

for key, value in person.items():
    print(f"{key}: {value}")
# 输出:
# 姓名: 张三
# 年龄: 29

集合

创建集合

magic_items = {"魔杖", "魔法书", "水晶球"}

这里,我们创建了一个名为magic_items的集合,里面包含了三种魔法物品。
添加元素
使用add()方法可以向集合中添加元素

magic_items.add("魔法药水")
print(magic_items)
# 输出:{'魔杖', '魔法书', '水晶球', '魔法药水'}

删除元素
使用remove()方法可以删除指定的元素。

magic_items.remove("魔法书")
print(magic_items)
# 输出:{'魔杖', '水晶球', '魔法药水'}

集合的其他操作
你可以对集合进行交集、并集、差集等操作。

set1 = {1, 2, 3}
set2 = {3, 4, 5}
print(set1 & set2)  # 输出:{3}
print(set1 | set2)  # 输出:{1, 2, 3, 4, 5}
print(set1 - set2)  # 输出:{1, 2}

列表推导式

numbers = [1, 2, 3, 4, 5]
squares = [x**2 for x in numbers]
print(squares)  # 输出:[1, 4, 9, 16, 25]

文件操作

读写文件

基本语法

file = open('文件名', '模式')

文件名:你要打开的文件的名称或路径。
模式:指定你打算如何与文件进行交互。常见的模式包括:
'r':读取模式(默认值),用于读取文件内容。
'w':写入模式,用于写入文件内容。如果文件已存在,其内容会被覆盖;如果文件不存在,则会创建一个新文件。
'a':追加模式,用于在文件末尾追加内容。
'b':二进制模式,用于处理二进制文件(如图片、音频等)。

# 以读取模式打开文件
file = open('example.txt', 'r')
# 以写入模式打开文件
file = open('example.txt', 'w')
# 以追加模式打开文件
file = open('example.txt', 'a')

使用read()方法:

file = open('example.txt', 'r')
content = file.read()
print(content)
file.close()

使用with语句(上下文管理器):with语句可以自动管理文件的打开和关闭,即使在读取过程中发生错误,文件也会被正确关闭。

with open('example.txt', 'r') as file:
    content = file.read()
    print(content)

使用write()方法:

lines = ["第一行/n", "第二行/n", "第三行/n"]
with open('example.txt', 'w') as file:
    file.writelines(lines)

writelines()方法接受一个字符串列表,并将每个字符串写入文件。

处理文件路径

绝对路径:绝对路径是从根目录开始的完整路径,就像从“魔法迷宫”的入口开始,精确地指明文件的位置。

file_path = "C://Users//Alice//Documents//example.txt"

相对路径:相对路径是相对于当前工作目录的路径,就像从“魔法迷宫”中的某个位置开始,指明文件的方向。

file_path = "documents/example.txt"

获取当前工作目录

import os
current_dir = os.getcwd()
print(current_dir)

更改当前工作目录

os.chdir("documents")

构建文件路径

directory = "documents"
filename = "example.txt"
file_path = os.path.join(directory, filename)
print(file_path)

拆分路径

path = "/home/alice/documents/example.txt"
directory, filename = os.path.split(path)
print(directory)  # 输出:/home/alice/documents
print(filename)  # 输出:example.txt

获取文件扩展名

extension = os.path.splitext(filename)[1]
print(extension)  # 输出:.txt

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐