侧边栏壁纸
博主头像
可乐没气的猫博主等级

四分之一的职业法师|二次元的分享家

  • 累计撰写 16 篇文章
  • 累计创建 6 个标签
  • 累计收到 19 条评论

目 录CONTENT

文章目录

20241230 Python3 快速入门指南 - 核心语法一张表

可乐没气的猫
2024-12-30 / 0 评论 / 0 点赞 / 78 阅读 / 3,701 字

Python3 快速入门指南 - 核心语法一张表

10 分钟掌握 Python 核心语法,快速上手编程

Python 是一门简洁优雅的编程语言,适合初学者和快速开发。本文精选最常用的语法,助你快速入门。

一、基础语法

变量与数据类型

# 变量无需声明类型
age = 18           # 整数 int
name = "John"      # 字符串 str
price = 19.99      # 浮点数 float
is_valid = True    # 布尔值 bool

# 查看类型
print(type(age))   # <class 'int'>

字符串操作

text = "Hello, World!"

# 切片
print(text[0:5])   # Hello
print(text[-6:-1]) # World

# f-字符串(Python 3.6+)
name = "Alice"
print(f"Hello, {name}!")  # Hello, Alice!

# 常用方法
print(text.lower())       # hello, world!
print(text.split(", "))   # ['Hello', 'World!']

列表(List)

# 创建列表
fruits = ["apple", "banana", "cherry"]

# 增删改查
fruits.append("orange")      # 添加
fruits.insert(1, "grape")    # 插入
fruits.remove("banana")      # 删除
item = fruits.pop()          # 弹出最后一个

# 遍历
for fruit in fruits:
    print(fruit)

# 列表推导式
squares = [x**2 for x in range(10)]

字典(Dict)

# 创建字典
person = {"name": "Alice", "age": 25}

# 访问
print(person["name"])        # Alice
print(person.get("age"))     # 25

# 修改
person["age"] = 26
person["city"] = "Beijing"   # 添加新键

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

二、流程控制

条件判断

score = 85

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

循环

# for 循环
for i in range(5):
    print(i)  # 0 1 2 3 4

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

# break 和 continue
for i in range(10):
    if i == 3:
        continue  # 跳过本次
    if i == 7:
        break     # 终止循环
    print(i)

三、函数

定义函数

def greet(name, greeting="Hello"):
    """函数文档字符串"""
    return f"{greeting}, {name}!"

# 调用
print(greet("Alice"))              # Hello, Alice!
print(greet("Bob", "Hi"))          # Hi, Bob!

参数类型

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

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

print(sum_all(1, 2, 3, 4))  # 10

# 关键字参数
def create_user(**kwargs):
    return kwargs

user = create_user(name="Alice", age=25)

四、文件操作

# 写入文件
with open("test.txt", "w", encoding="utf-8") as f:
    f.write("Hello, File!")

# 读取文件
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())

五、异常处理

try:
    result = 10 / 0
except ZeroDivisionError:
    print("不能除以零!")
except Exception as e:
    print(f"其他错误:{e}")
finally:
    print("总是执行")

六、常用内置函数

# 类型转换
int("123")        # 123
float("3.14")     # 3.14
str(123)          # "123"
list("abc")       # ['a', 'b', 'c']

# 数学运算
abs(-10)          # 10
round(3.14159, 2) # 3.14
pow(2, 3)         # 8

# 序列操作
len([1, 2, 3])    # 3
max([1, 5, 3])    # 5
min([1, 5, 3])    # 1
sum([1, 2, 3])    # 6
sorted([3, 1, 2]) # [1, 2, 3]

七、实用技巧

列表操作

nums = [1, 2, 3, 4, 5]

# 切片
nums[1:4]      # [2, 3, 4]
nums[::-1]     # [5, 4, 3, 2, 1] 反转

# 推导式
evens = [x for x in nums if x % 2 == 0]  # [2, 4]

# 解包
a, b, *rest = nums
print(a, b, rest)  # 1 2 [3, 4, 5]

字典技巧

d = {"a": 1, "b": 2}

# 合并字典
d2 = {"c": 3}
d.update(d2)  # {'a': 1, 'b': 2, 'c': 3}

# 安全获取
value = d.get("x", "默认值")

# 字典推导式
squares = {x: x**2 for x in range(5)}

字符串技巧

text = "  Hello, World!  "

text.strip()           # "Hello, World!"
text.replace("!", "?") # "  Hello, World?  "
"text".join(["A", "B"]) # "AtextB"

八、模块导入

# 导入整个模块
import math
print(math.sqrt(16))  # 4.0

# 导入特定函数
from datetime import datetime
print(datetime.now())

# 导入并重命名
import numpy as np

九、面向对象(基础)

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def greet(self):
        return f"Hi, I'm {self.name}"

# 创建实例
p = Person("Alice", 25)
print(p.greet())  # Hi, I'm Alice

十、下一步学习

  • 📚 官方文档: https://docs.python.org/zh-cn/3/
  • 🎯 实战练习: LeetCode、HackerRank
  • 📦 常用库: requests, pandas, numpy, flask
  • 🚀 进阶方向: Web 开发、数据分析、机器学习

快速参考表:

类型 示例 可变性
list [1, 2, 3] ✅ 可变
tuple (1, 2, 3) ❌ 不可变
dict {"a": 1} ✅ 可变
set {1, 2, 3} ✅ 可变
str "hello" ❌ 不可变

#Python #编程 #入门 #教程 #快速上手

0

评论区