Python是一种广泛使用的高级编程语言,以其简洁易读的语法而闻名。无论你是初学者还是有经验的开发者,掌握Python的基本语法都是非常重要的。本文将为你总结100个Python语法要点,帮助你快速上手和巩固知识。
-
整数:
a = 10 -
浮点数:
b = 3.14 -
字符串:
s = "Hello, World!" -
布尔值:
flag = True -
列表:
my_list = [1, 2, 3] -
元组:
my_tuple = (1, 2, 3) -
字典:
my_dict = {'name': 'Alice', 'age': 25} -
集合:
my_set = {1, 2, 3} -
条件语句:
if a > b: print("a is greater") elif a < b: print("b is greater") else: print("a and b are equal") -
循环:
- for循环:
for i in range(5): print(i) - while循环:
while a < 5: a += 1
- for循环:
-
定义函数:
def my_function(param): return param * 2 -
匿名函数:
lambda x: x * 2 -
定义类:
class MyClass: def __init__(self, value): self.value = value -
创建对象:
obj = MyClass(10) -
try-except:
try: result = 10 / 0 except ZeroDivisionError: print("Cannot divide by zero") -
打开文件:
with open('file.txt', 'r') as f: content = f.read() -
写入文件:
with open('file.txt', 'w') as f: f.write("Hello, World!") -
导入模块:
import math -
使用模块:
math.sqrt(16) -
基本用法:
squares = [x**2 for x in range(10)] -
基本用法:
square_dict = {x: x**2 for x in range(5)} -
生成器函数:
def my_generator(): yield 1 yield 2 -
使用生成器:
gen = my_generator() for value in gen: print(value) -
基本装饰器:
def my_decorator(func): def wrapper(): print("Something is happening before the function is called.") func() print("Something is happening after the function is called.") return wrapper -
map:
list(map(str, [1, 2, 3])) -
filter:
list(filter(lambda x: x > 0, [-1, 0, 1, 2])) -
reduce:
from functools import reduce; reduce(lambda x, y: x + y, [1, 2, 3]) -
NumPy:用于科学计算
-
Pandas:用于数据分析
-
Matplotlib:用于数据可视化
-
字符串格式化:
name = "Alice" greeting = f"Hello, {name}!" -
多行字符串:
multi_line = """This is a multi-line string.""" -
列表切片:
my_list = [1, 2, 3, 4, 5] sub_list = my_list[1:4] # [2, 3, 4] -
字典访问:
age = my_dict.get('age', 0) # 默认值为0 -
集合操作:
my_set.add(4) my_set.remove(1) -
上下文管理器:
class MyContext: def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): pass -
类型注解:
def add(x: int, y: int) -> int: return x + y -
类型检查:
from typing import List def process_items(items: List[str]) -> None: pass -
交换变量:
a, b = b, a -
列表连接:
combined = my_list + [6, 7] -
字符串连接:
full_string = "Hello" + " " + "World" -
检查子串:
if "Hello" in full_string: print("Found!") -
获取长度:
length = len(my_list) -
排序:
sorted_list = sorted(my_list) -
反转:
reversed_list = my_list[::-1] -
列表去重:
unique_list = list(set(my_list)) -
合并字典:
new_dict = {**my_dict, **{'city': 'New York'}} -
获取字典键值:
keys = my_dict.keys() values = my_dict.values() -
遍历字典:
for key, value in my_dict.items(): print(key, value) -
字符串分割与连接:
words = "Hello World".split() joined = " ".join(words) -
时间模块:
import time current_time = time.time() -
随机模块:
import random random_number = random.randint(1, 10) -
正则表达式:
import re match = re.search(r'\d+', 'abc123') -
JSON处理:
import json json_data = json.dumps(my_dict) -
请求模块:
import requests response = requests.get('https://api.example.com') -
print函数:
print("Hello, World!") -
整数除法:
result = 7 / 2 # 3.5 int_result = 7 // 2 # 3 -
Unicode支持:
unicode_string = "你好" -
f-字符串:
name = "Alice" greeting = f"Hello, {name}!" -
类型提示:
def greet(name: str) -> None: print(f"Hello, {name}") -
列表推导式的条件:
even_numbers = [x for x in range(10) if x % 2 == 0] -
字典推导式的条件:
even_square_dict = {x: x**2 for x in range(10) if x % 2 == 0} -
集合推导式:
unique_squares = {x**2 for x in [1, 2, 2, 3]} -
使用zip函数:
names = ['Alice', 'Bob'] ages = [25, 30] combined = dict(zip(names, ages)) -
使用enumerate:
for index, value in enumerate(my_list): print(index, value) -
使用all和any:
all_positive = all(x > 0 for x in my_list) any_positive = any(x > 0 for x in my_list) -
使用Counter:
from collections import Counter count = Counter(my_list) -
使用defaultdict:
from collections import defaultdict dd = defaultdict(int) dd['key'] += 1 -
使用namedtuple:
from collections import namedtuple Point = namedtuple('Point', ['x', 'y']) p = Point(10, 20) -
使用deque:
from collections import deque d = deque([1, 2, 3]) d.append(4) -
多线程:
import threading def worker(): print("Worker thread") t = threading.Thread(target=worker) t.start() -
多进程:
from multiprocessing import Process def worker(): print("Worker process") p = Process(target=worker) p.start() -
使用asyncio:
import asyncio async def main(): print("Hello") asyncio.run(main()) -
使用with语句:
with open('file.txt') as f: content = f.read() -
使用@property:
class MyClass: def __init__(self): self._value = 0 @property def value(self): return self._value -
使用assert:
assert a > 0, "a must be positive" -
使用__name__:
if __name__ == "__main__": print("This is the main module") -
使用__init__.py:
- 在包目录下创建
__init__.py文件,使其成为包。
- 在包目录下创建
-
使用__str__和__repr__:
class MyClass: def __str__(self): return "MyClass instance" -
使用__getitem__:
class MyList: def __getitem__(self, index): return index * 2 -
os模块:
import os current_dir = os.getcwd() -
sys模块:
import sys print(sys.version) -
math模块:
import math pi = math.pi -
datetime模块:
from datetime import datetime now = datetime.now() -
timeit模块:
import timeit execution_time = timeit.timeit("x = 1 + 1", number=1000) -
使用break和continue:
for i in range(10): if i == 5: break if i % 2 == 0: continue print(i) -
使用pass:
if condition: pass # 占位符 -
使用del:
del my_list[0] -
使用isinstance:
if isinstance(a, int): print("a is an integer") -
使用id:
print(id(a)) -
使用super:
class Parent: def __init__(self): print("Parent") class Child(Parent): def __init__(self): super().__init__() print("Child") -
使用staticmethod和classmethod:
class MyClass: @staticmethod def static_method(): pass @classmethod def class_method(cls): pass -
使用__slots__:
class MyClass: __slots__ = ['name', 'age'] -
使用contextlib:
from contextlib import contextmanager @contextmanager def my_context(): yield -
使用functools:
from functools import lru_cache @lru_cache(maxsize=None) def fibonacci(n): if n < 2: return n return fibonacci(n-1) + fibonacci(n-2) -
使用itertools:
import itertools for combination in itertools.combinations([1, 2, 3], 2): print(combination) -
使用functools.partial:
from functools import partial def add(x, y): return x + y add_five = partial(add, 5) -
使用zip_longest:
from itertools import zip_longest for a, b in zip_longest([1, 2], [3, 4, 5]): print(a, b) -
使用Counter:
from collections import Counter count = Counter(['a', 'b', 'a']) -
使用deque:
from collections import deque
d = deque()
d.append(1)
d.appendleft(2)
总结
以上就是Python的100个语法速记,希望能帮助你在学习和使用Python的过程中更加高效。Python的魅力在于其简洁的语法和强大的功能,掌握这些基本语法后,你将能够更自信地进行编程。欢迎大家在评论区分享你们的学习经验和问题!