Python编程入门必备:100个语法速记技巧,助你快速上手!

303 阅读6分钟

Python是一种广泛使用的高级编程语言,以其简洁易读的语法而闻名。无论你是初学者还是有经验的开发者,掌握Python的基本语法都是非常重要的。本文将为你总结100个Python语法要点,帮助你快速上手和巩固知识。

  1. 整数a = 10

  2. 浮点数b = 3.14

  3. 字符串s = "Hello, World!"

  4. 布尔值flag = True

  5. 列表my_list = [1, 2, 3]

  6. 元组my_tuple = (1, 2, 3)

  7. 字典my_dict = {'name': 'Alice', 'age': 25}

  8. 集合my_set = {1, 2, 3}

  9. 条件语句

    if a > b:
        print("a is greater")
    elif a < b:
        print("b is greater")
    else:
        print("a and b are equal")
    
  10. 循环

    • for循环
      for i in range(5):
          print(i)
      
    • while循环
      while a < 5:
          a += 1
      
  11. 定义函数

    def my_function(param):
        return param * 2
    
  12. 匿名函数lambda x: x * 2

  13. 定义类

    class MyClass:
        def __init__(self, value):
            self.value = value
    
  14. 创建对象obj = MyClass(10)

  15. try-except

    try:
        result = 10 / 0
    except ZeroDivisionError:
        print("Cannot divide by zero")
    
  16. 打开文件

    with open('file.txt', 'r') as f:
        content = f.read()
    
  17. 写入文件

    with open('file.txt', 'w') as f:
        f.write("Hello, World!")
    
  18. 导入模块import math

  19. 使用模块math.sqrt(16)

  20. 基本用法

    squares = [x**2 for x in range(10)]
    
  21. 基本用法

    square_dict = {x: x**2 for x in range(5)}
    
  22. 生成器函数

    def my_generator():
        yield 1
        yield 2
    
  23. 使用生成器

    gen = my_generator()
    for value in gen:
        print(value)
    
  24. 基本装饰器

    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
    
  25. maplist(map(str, [1, 2, 3]))

  26. filterlist(filter(lambda x: x > 0, [-1, 0, 1, 2]))

  27. reducefrom functools import reduce; reduce(lambda x, y: x + y, [1, 2, 3])

  28. NumPy:用于科学计算

  29. Pandas:用于数据分析

  30. Matplotlib:用于数据可视化

  31. 字符串格式化

    name = "Alice"
    greeting = f"Hello, {name}!"
    
  32. 多行字符串

    multi_line = """This is
    a multi-line
    string."""
    
  33. 列表切片

    my_list = [1, 2, 3, 4, 5]
    sub_list = my_list[1:4]  # [2, 3, 4]
    
  34. 字典访问

    age = my_dict.get('age', 0)  # 默认值为0
    
  35. 集合操作

    my_set.add(4)
    my_set.remove(1)
    
  36. 上下文管理器

    class MyContext:
        def __enter__(self):
            return self
        def __exit__(self, exc_type, exc_value, traceback):
            pass
    
  37. 类型注解

    def add(x: int, y: int) -> int:
        return x + y
    
  38. 类型检查

    from typing import List
    def process_items(items: List[str]) -> None:
        pass
    
  39. 交换变量

    a, b = b, a
    
  40. 列表连接

    combined = my_list + [6, 7]
    
  41. 字符串连接

    full_string = "Hello" + " " + "World"
    
  42. 检查子串

    if "Hello" in full_string:
        print("Found!")
    
  43. 获取长度

    length = len(my_list)
    
  44. 排序

    sorted_list = sorted(my_list)
    
  45. 反转

    reversed_list = my_list[::-1]
    
  46. 列表去重

    unique_list = list(set(my_list))
    
  47. 合并字典

    new_dict = {**my_dict, **{'city': 'New York'}}
    
  48. 获取字典键值

    keys = my_dict.keys()
    values = my_dict.values()
    
  49. 遍历字典

    for key, value in my_dict.items():
        print(key, value)
    
  50. 字符串分割与连接

    words = "Hello World".split()
    joined = " ".join(words)
    
  51. 时间模块

    import time
    current_time = time.time()
    
  52. 随机模块

    import random
    random_number = random.randint(1, 10)
    
  53. 正则表达式

    import re
    match = re.search(r'\d+', 'abc123')
    
  54. JSON处理

    import json
    json_data = json.dumps(my_dict)
    
  55. 请求模块

    import requests
    response = requests.get('https://api.example.com')
    
  56. print函数

    print("Hello, World!")
    
  57. 整数除法

    result = 7 / 2  # 3.5
    int_result = 7 // 2  # 3
    
  58. Unicode支持

    unicode_string = "你好"
    
  59. f-字符串

    name = "Alice"
    greeting = f"Hello, {name}!"
    
  60. 类型提示

    def greet(name: str) -> None:
        print(f"Hello, {name}")
    
  61. 列表推导式的条件

    even_numbers = [x for x in range(10) if x % 2 == 0]
    
  62. 字典推导式的条件

    even_square_dict = {x: x**2 for x in range(10) if x % 2 == 0}
    
  63. 集合推导式

    unique_squares = {x**2 for x in [1, 2, 2, 3]}
    
  64. 使用zip函数

    names = ['Alice', 'Bob']
    ages = [25, 30]
    combined = dict(zip(names, ages))
    
  65. 使用enumerate

    for index, value in enumerate(my_list):
        print(index, value)
    
  66. 使用all和any

    all_positive = all(x > 0 for x in my_list)
    any_positive = any(x > 0 for x in my_list)
    
  67. 使用Counter

    from collections import Counter
    count = Counter(my_list)
    
  68. 使用defaultdict

    from collections import defaultdict
    dd = defaultdict(int)
    dd['key'] += 1
    
  69. 使用namedtuple

    from collections import namedtuple
    Point = namedtuple('Point', ['x', 'y'])
    p = Point(10, 20)
    
  70. 使用deque

    from collections import deque
    d = deque([1, 2, 3])
    d.append(4)
    
  71. 多线程

    import threading
    def worker():
        print("Worker thread")
    t = threading.Thread(target=worker)
    t.start()
    
  72. 多进程

    from multiprocessing import Process
    def worker():
        print("Worker process")
    p = Process(target=worker)
    p.start()
    
  73. 使用asyncio

    import asyncio
    async def main():
        print("Hello")
    asyncio.run(main())
    
  74. 使用with语句

    with open('file.txt') as f:
        content = f.read()
    
  75. 使用@property

    class MyClass:
        def __init__(self):
            self._value = 0
        @property
        def value(self):
            return self._value
    
  76. 使用assert

    assert a > 0, "a must be positive"
    
  77. 使用__name__

    if __name__ == "__main__":
        print("This is the main module")
    
  78. 使用__init__.py

    • 在包目录下创建__init__.py文件,使其成为包。
  79. 使用__str__和__repr__

    class MyClass:
        def __str__(self):
            return "MyClass instance"
    
  80. 使用__getitem__

    class MyList:
        def __getitem__(self, index):
            return index * 2
    
  81. os模块

    import os
    current_dir = os.getcwd()
    
  82. sys模块

    import sys
    print(sys.version)
    
  83. math模块

    import math
    pi = math.pi
    
  84. datetime模块

    from datetime import datetime
    now = datetime.now()
    
  85. timeit模块

    import timeit
    execution_time = timeit.timeit("x = 1 + 1", number=1000)
    
  86. 使用break和continue

    for i in range(10):
        if i == 5:
            break
        if i % 2 == 0:
            continue
        print(i)
    
  87. 使用pass

    if condition:
        pass  # 占位符
    
  88. 使用del

    del my_list[0]
    
  89. 使用isinstance

    if isinstance(a, int):
        print("a is an integer")
    
  90. 使用id

    print(id(a))
    
  91. 使用super

    class Parent:
        def __init__(self):
            print("Parent")
    class Child(Parent):
        def __init__(self):
            super().__init__()
            print("Child")
    
  92. 使用staticmethod和classmethod

    class MyClass:
        @staticmethod
        def static_method():
            pass
        @classmethod
        def class_method(cls):
            pass
    
  93. 使用__slots__

    class MyClass:
        __slots__ = ['name', 'age']
    
  94. 使用contextlib

    from contextlib import contextmanager
    @contextmanager
    def my_context():
        yield
    
  95. 使用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)
    
  96. 使用itertools

    import itertools
    for combination in itertools.combinations([1, 2, 3], 2):
        print(combination)
    
  97. 使用functools.partial

    from functools import partial
    def add(x, y):
        return x + y
    add_five = partial(add, 5)
    
  98. 使用zip_longest

    from itertools import zip_longest
    for a, b in zip_longest([1, 2], [3, 4, 5]):
        print(a, b)
    
  99. 使用Counter

    from collections import Counter
    count = Counter(['a', 'b', 'a'])
    
  100. 使用deque

from collections import deque
d = deque()
d.append(1)
d.appendleft(2)

总结

以上就是Python的100个语法速记,希望能帮助你在学习和使用Python的过程中更加高效。Python的魅力在于其简洁的语法和强大的功能,掌握这些基本语法后,你将能够更自信地进行编程。欢迎大家在评论区分享你们的学习经验和问题!