Python 速查表

2025-05-28

Python 速查表

当你想要复习一些概念时,备忘单很有用,但它并不是开始学习的闲散方式。

我建议你深入学习这门课程:Udemy 课程。

如果你可以自学,那么你可以参考这个存储库:Github

指数

理论

  • Python 是一种脚本语言。
  • 脚本 vs 编译? ——像 C++/Java 这样的语言,其代码需要经过编译器编译,编译后就只是机器码了。而脚本语言的解释器则会一次一行地执行代码。

VSCODE 扩展:

  • Python
  • vscode 中的 Python
  • 魔法 Python
  • 阿雷普尔

创建虚拟环境:

为什么要使用虚拟环境?

因为管理 python 依赖项很混乱,所以这将仅为该项目安装依赖项,而不是全局安装。

  • python -m venv venv这将在您的目录中创建一个 venv 文件夹。
  • source ./venv/bin/activate这将激活这个虚拟环境。

Python 中的注释

  • 单线使用#
# single line comments
Enter fullscreen mode Exit fullscreen mode
  • 多行使用'''。通常称为文档字符串,因为它只是用于记录函数/类。
'''
This is a example of 
Multiline comment.
'''
Enter fullscreen mode Exit fullscreen mode

数据类型:

  • int # 整数
  • float # 带有小数的数字。
  • str # 字符串
  • 列表 # 对象的有序序列
  • dict # 无序的键值对。
  • tup # 对象的有序不可变序列。
  • 设置# 唯一对象的无序集合。
  • bool # 逻辑值 True / False。
  • None #无值

命名约定:

  • 对变量使用下划线。
  • 变量不能以数字开头。
  • 避免使用具有特殊含义的关键词。
  • 使用蛇形命名法来表示函数。
  • 使用 CamelCase 作为类名。

使用 Python 打印:

print("")
Enter fullscreen mode Exit fullscreen mode

Python 中的数字:

print(1+2) # Addition
print(3-2) # Subtraction
print(3*2) # Multiplication
print(3/2) # Division
print(3%2) # Mod.
print(3**2) # Power
print((3 + 10) * 15) # Using Braces.
Enter fullscreen mode Exit fullscreen mode

使用变量:

a = 10
print(a)
# TO check the type:
print(type(a))
Enter fullscreen mode Exit fullscreen mode

变量使得代码变得容易理解。

my_income = 100
tax_rate = 0.1
my_taxes = my_income*tax_rate
print("My income tax is",my_taxes)
Enter fullscreen mode Exit fullscreen mode

Python 中的字符串:

字符串只是字符的有序序列。
注意:字符串是不可变的

直接使用打印:

print("Simple String")
print('Add quotes inside the  "string" by using single quote.')
print("concat string "+"like this")
Enter fullscreen mode Exit fullscreen mode

接受输入

greeting = "Hello"
name = input("Enter your name: ")
print(greeting + ' ' + name)
Enter fullscreen mode Exit fullscreen mode

使用,而不是+这将自动用空格分隔它们。

print(greeting,name)
Enter fullscreen mode Exit fullscreen mode

python 中的转义字符:

print("Hello\nWorld")
# or
print("""
 ---
Hello
world\
Yeahh!!
"Quotes"
'Single quote'
 ---
""")
Enter fullscreen mode Exit fullscreen mode

检查字符串的长度:

print(len("Hey"))
Enter fullscreen mode Exit fullscreen mode

字符串索引

a = "Hello"
a[0] Will return H
Enter fullscreen mode Exit fullscreen mode

字符串切片

a[start:end:step]
a[0:2] # Start from 0th index till 2(excluding)
a[::2] # Step will be 2.
# We can use this to print a string backwards
s[::-1]
Enter fullscreen mode Exit fullscreen mode

字符串方法:

# Multiply Strings
a = 'H' * 10
Enter fullscreen mode Exit fullscreen mode
# Upper Case a string
s.upper()
Enter fullscreen mode Exit fullscreen mode
# Lower case
s.lower()
Enter fullscreen mode Exit fullscreen mode
# Splitting
s.split('W')
s.split() # split via whitespace.
Enter fullscreen mode Exit fullscreen mode

格式化字符串:

  • .format()
  • f""F 弦
print('The {2} {1} {0}'.format('fox','brown','quick'))
print('First Object: {a}, Second Object: {b}, Third Object: {c}'.format(a=1,b='Two',c=12.3))
num = 23.45
print("My 10 character, four decimal number is:{0:10.4f}".format(num))
print(f"My 10 character, four decimal number is:{num:10.4f}")
Enter fullscreen mode Exit fullscreen mode

字符串打印对齐

left_alignment = "Left Text"
center_alignment = "Centered Text"
right_alignment = "Right Text"
print(f"{left_alignment : <20}|{center_alignment : ^15}|{right_alignment : >20}")
More about this: https://pyformat.info/
Enter fullscreen mode Exit fullscreen mode

Python 中的列表:

基本用法

# Supports dynamic types, as it is python :)
my_list = [100,2.5,"Mohit"]
# len(my_list) for length
# Change objs:
my_list[0]=1000
Enter fullscreen mode Exit fullscreen mode

切片与字符串切片相同

康卡特

a = [1,2,3]
b = [4,5]
c = a + b
Enter fullscreen mode Exit fullscreen mode

附加列表

my_list.append(10.8)
Enter fullscreen mode Exit fullscreen mode

弹出对象

my_list.pop(index) # default index is -1, returns popped element.
Enter fullscreen mode Exit fullscreen mode

排序

a = [1,2,3]
a.sort() # in-place sort, it will modify the list, returns None
# Tip: use sorted(a) it will return the value instead of in-place
Enter fullscreen mode Exit fullscreen mode

撤销

a = [1,2,3]
a.reverse() # also in-place
Enter fullscreen mode Exit fullscreen mode

嵌套列表

a = [1, 2, 3, [4,5,]]
print(a[3][1]) # Returns 5.
Enter fullscreen mode Exit fullscreen mode

Python 中的字典

无序键值映射,基本上你可以自定义键。
想想看,你可以用它来创建动态变量,其中键是变量名。
像列表一样,值可以是任何数据类型。

基本用法

prices = {"apple":10, "orange":20.5}
print(prices)
print(prices["apple"])
print(prices.keys()) # get keys
print(prices.values()) # get values
print(prices.items()) # get items, return tuples with keys and values
print(prices.pop("apple")) # Pop the object
print(prices)
print(prices.clear()) # Clear All
print(prices)
print(prices.get("banana")) # it will check if it is present, return None if not.
print(prices.__contains__("apple")) # Returns true/false
Enter fullscreen mode Exit fullscreen mode

Python中的元组

与列表相同,但不可变。

基本用法

a = (1,2,2,4)
print(a)
# Interesting Fact: tuple supports only two methods:
a.count(2) # This can be use with list as well.
a.index(3) # This can be use with list as well.
Enter fullscreen mode Exit fullscreen mode

Python 中的集合

集合是唯一元素的无序集合。

a = set()
a.add(1)
a.add(1)
a.add(1)
print(a) # {1}
Enter fullscreen mode Exit fullscreen mode

将列表转换为集合

a = [1,1,2,2,2,3,3,3]
a = set(a)
Enter fullscreen mode Exit fullscreen mode

使用 Python 进行文件 IO

初始化文件 obj

file = open("file.txt")
Enter fullscreen mode Exit fullscreen mode

阅读内容

contents = file.read()
print(contents)
Enter fullscreen mode Exit fullscreen mode

移动光标/指针

file.seek(0)
Enter fullscreen mode Exit fullscreen mode

逐行阅读

contents = file.readlines() # returns list of lines.
Enter fullscreen mode Exit fullscreen mode

关闭文件

file.close()
Enter fullscreen mode Exit fullscreen mode

使用上下文管理器

with open("file.txt") as file:
    print(file.read())
Enter fullscreen mode Exit fullscreen mode

文件的不同模式

  • r: 读
  • r+:阅读和写作
  • w:写入(将覆盖文件)
  • w+:写入 + 读取(将覆盖文件)
  • a:附加文件

链接比较运算符:

为了链接==, != <, >, >=, <= and is这些运算符,我们有这些逻辑运算符

  • 或者
  • 不是
if 2 > 3 and 2 > 5:
    print("I am inevitable")
if "hello" is "world" or "india" is "country":
    print("Yeah!!")
if not 10 == 10:
    print("Tough luck!" )
Enter fullscreen mode Exit fullscreen mode

Python语句:

缩进在 Python 中很重要。

如果,否则

loc = 'Bank'

if loc == 'Auto Shop':
    print('Welcome to the Auto Shop!')
elif loc == 'Bank':
    print('Welcome to the bank!')
else:
    print('Where are you?')
Enter fullscreen mode Exit fullscreen mode

for 循环

# iterate list/string/tuple
l = [1,2,3]
for item in l:
    print(item)
# extraction made easy
list2 = [(2,4),(6,8),(10,12)]
for t1,t2 in list2: # Same as dict. t1 will be key, t2 will be value.
    print(t1) # will print 2,6,10
# Protip about dict: use .value() and .keys() for looping Values/keys.
Enter fullscreen mode Exit fullscreen mode

while 循环

在 python 中我们可以使用带有 else 语句的 python。

x = 1
while x < 3:
    print(f"x is {x}")
    x = x + 1
else:
    print("Uhhoo! x > 3")
Enter fullscreen mode Exit fullscreen mode

Python中的语句

  • break:跳出当前最近的封闭循环。
  • continue:转到最近的封闭循环的顶部。
  • pass:什么也不做,程序员使用它作为占位符。
def future_method():
    # Todo: implement it later.
    pass
while True:
    break
for i in range(10):
    if i == 5:
        #omit
        continue 
    print(i)
Enter fullscreen mode Exit fullscreen mode

一些有用的运算符

范围()

range 是一个生成器。

语法range(start,end,step)


直接与循环一起使用进行迭代。

a = list(range(0,11,2)) # returns 0,2,4,..10
Enter fullscreen mode Exit fullscreen mode

枚举()

借助它,我们可以跟踪索引和值。

a = [20,100,5,3,6]
for index,value in enumerate(a):
    print(f"{index}\t{value}")
Enter fullscreen mode Exit fullscreen mode

拉链()

zip multiple lists.
a = [1,2,3]
b = [4,5,6]
for item in zip(a,b):
    print(item)
Enter fullscreen mode Exit fullscreen mode

在运算符中:

a = [1,2,3]
print(3 in a) # True
Enter fullscreen mode Exit fullscreen mode

最小值和最大值:

a = [1,2,3]
print(min(a)) # 1
print(max(a)) # 3
Enter fullscreen mode Exit fullscreen mode

列表推导

创建列表的更快、更独特的方法。

# Grab every letter in string
lst = [x for x in 'word']

# Square numbers in range and turn into list
lst = [x**2 for x in range(0,11)]

# Check for even numbers in a range
lst = [x for x in range(11) if x % 2 == 0]
Enter fullscreen mode Exit fullscreen mode

Python中的帮助函数

如果你像我一样懒,想通过终端了解有关特定内置方法的文档,你可以使用 help()

a = [1,2,3]
help(a.insert) # will print info about this method
Enter fullscreen mode Exit fullscreen mode

Python中的函数

具有参数和默认值的基本函数

# def keyword to define functions.
def say_hello(name="world"):
    print(f"Hello {name}!")
    # or return f"Hello {name}!" if you want to return it.
Enter fullscreen mode Exit fullscreen mode

*args 和 **kwargs

  • *args:N 个参数,返回元组。
  • **kwargs:N 个关键字参数,返回字典。
def total_income(*args, **kwargs):
    print(f"Income for month, {kwargs['month']} is : {sum(args)}")
total_income(10,20,300,month="July")
Enter fullscreen mode Exit fullscreen mode

lamda、filter 和 map

#map
def square(num):
    return num**2
my_nums = [1,2,3,4,5]
map(square,my_nums) # 1, 4, 9, 16, 25

# filter
def check_even(num):
    return num % 2 == 0
nums = [0,1,2,3,4,5,6,7,8,9,10]
filter(check_even, nums) # 0, 2, 4, 6, 8, 10

# lets convert each of the above function to lambda.
map(lambda num:num**2,my_nums)
filter(lambda num:num%2==0, nums) 
Enter fullscreen mode Exit fullscreen mode

Python 中的类

基本实现

class Circle:
    pi = 3.14

    # Circle gets instantiated with a radius (default is 1)
    def __init__(self, radius=1):
        self.radius = radius 
        self.area = radius * radius * Circle.pi

    # Method for resetting Radius
    def setRadius(self, new_radius):
        self.radius = new_radius
        self.area = new_radius * new_radius * self.pi

    # Method for getting Circumference
    def getCircumference(self):
        return self.radius * self.pi * 2


c = Circle()

print('Radius is: ',c.radius)
print('Area is: ',c.area)
print('Circumference is: ',c.getCircumference())

Enter fullscreen mode Exit fullscreen mode

遗产

class Animal:
    def __init__(self):
        print("Animal created")

    def whoAmI(self):
        print("Animal")

    def eat(self):
        print("Eating")


class Dog(Animal):
    def __init__(self):
        Animal.__init__(self)
        print("Dog created")

    def whoAmI(self):
        print("Dog")

    def bark(self):
        print("Woof!")
Enter fullscreen mode Exit fullscreen mode

多态性

class Animal:
    def __init__(self, name):    # Constructor of the class
        self.name = name

    def speak(self):              # Abstract method, defined by convention only
        raise NotImplementedError("Subclass must implement abstract method")


class Dog(Animal):

    def speak(self):
        return self.name+' says Woof!'

class Cat(Animal):

    def speak(self):
        return self.name+' says Meow!'

fido = Dog('Fido')
isis = Cat('Isis')

print(fido.speak())
print(isis.speak())
Enter fullscreen mode Exit fullscreen mode

使用特殊方法

就像__init__我们有更多的特殊方法一样。

class Book:
    def __init__(self, title, author, pages):
        print("A book is created")
        self.title = title
        self.author = author
        self.pages = pages

    def __str__(self):
        return "Title: %s, author: %s, pages: %s" %(self.title, self.author, self.pages)

    def __len__(self):
        return self.pages

    def __del__(self):
        print("A book is destroyed")


book = Book("Python Rocks!", "Jose Portilla", 159)

#Special Methods
print(book)
print(len(book))
del book
Enter fullscreen mode Exit fullscreen mode

异常处理

尝试、除外、最后和其他。

def askint():
    while True:
        try:
            val = int(input("Please enter an integer: "))
        except:
            # You can also expect specific error like TypeError or generic type Exception
            print("Looks like you did not enter an integer!")
            continue
        else:
            print("Yep that's an integer!")
            break
        finally:
            print("Finally, I executed!")
        print(val)
Enter fullscreen mode Exit fullscreen mode

装饰器

def new_decorator(func):

    def wrap_func():
        print("Code would be here, before executing the func")

        func()

        print("Code here will execute after the func()")

    return wrap_func

@new_decorator
def func_needs_decorator():
    print("This function is in need of a Decorator")

func_needs_decorator()
# Code would be here, before executing the func
# This function is in need of a Decorator
# Code here will execute after the func()
Enter fullscreen mode Exit fullscreen mode

生成器

# Without generator
def get_me_cubes(n):
    output_list = []
    for i in range(n):
        output_list.append(i**3)
    return output_list

print(get_me_cubes(10))
# With generator
def generate_cubes(n):
    for i in range(n):
        yield i**3

print(generate_cubes(10))
Enter fullscreen mode Exit fullscreen mode

您应该查看一些有用的 Python 模块。

  • 收藏品
  • 操作系统
  • 舒蒂尔
  • 日期时间
  • 数学
  • 随机的
  • 蛋白质组学
  • 关于
  • 时间
  • 压缩文件

在 Python 中使用 CSV

# don't forget to install csv
import csv
data = open('example.csv',encoding="utf-8")
# passing encoding is important otherwise you will get the Unicode error.
csv_data = csv.reader(data)
# reading
data_lines = list(csv_data)
# writing 
file_to_output = open('to_save_file.csv','w',newline='')
# use 'a' for append
csv_writer = csv.writer(file_to_output,delimiter=',')
csv_writer.writerow(['a','b','c'])
file_to_output.close()
Enter fullscreen mode Exit fullscreen mode

使用 Python 处理 PDF

# don't forget to use PyPDF2
import PyPDF2
f = open('Working_Business_Proposal.pdf','rb')
# we need to pass rb for binary files.
pdf_text = []

pdf_reader = PyPDF2.PdfFileReader(f)

for p in range(pdf_reader.numPages):
    page = pdf_reader.getPage(p)
    pdf_text.append(page.extractText())
Enter fullscreen mode Exit fullscreen mode

使用python发送电子邮件

import smtplib
smtp_object = smtplib.SMTP('smtp.gmail.com',587)
email = "youremail@email.com"
password = "yourpassword"
# Tip: search about how you generate app passwords.
smtp_object.login(email,password)
from_address = "fromemail@email.com"
to_address = "toemail@email.com"
subject = "Subject"
message = "Message"
msg = "Subject: " + subject + '\n' + message
smtp_object.sendmail(from_address,to_address,msg)
smtp_object.quit()
Enter fullscreen mode Exit fullscreen mode
文章来源:https://dev.to/tanwanimohit/python-cheatsheet-25a3
PREV
每个开发人员都需要的 5 种 AI 工具,成为专业的 Vibe Coder⚡⚡⚡
NEXT
我的自由职业工作流程:从冷门线索到付费发票