Fundamentals 12 min read

Comprehensive Python Syntax Cheat Sheet: 25 Key Concepts with Code Examples

This article presents a concise yet thorough overview of Python's essential syntax, covering printing, variable assignment, data types, control flow, functions, OOP features, decorators, context managers, generators, and advanced topics such as metaclasses and recursion, each illustrated with clear code snippets.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Comprehensive Python Syntax Cheat Sheet: 25 Key Concepts with Code Examples

1. Print Output – Use the print function to display information. Example: print("Hello, World!") # 输出结果: Hello, World!

2. Variable Assignment – Simple assignment of values to variables. Example: x = 10 y = "Hello" print(x, y) # 输出结果: 10 Hello

3. Data Types – Python supports integers, floats, strings, lists, tuples, dictionaries, and sets. Example: integer = 10 float_num = 10.5 string = "Hello" list_ = [1, 2, 3] tuple_ = (1, 2, 3) dictionary = {"name": "Alice", "age": 30} set_ = {1, 2, 3}

4. Conditional Statements – Use if , elif , and else for branching. Example: x = 10 if x > 0: print("正数") elif x == 0: print("零") else: print("负数") # 输出结果: 正数

5. Loops – Use for and while to iterate. Example: # for loop for i in range(5): print(i) # 输出结果: 0 1 2 3 4 # while loop i = 0 while i < 5: print(i) # 输出结果: 0 1 2 3 4 i += 1

6. List Comprehension – Concise list creation. Example: squares = [x**2 for x in range(10)] print(squares) # 输出结果: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

7. Dictionary Comprehension – Concise dictionary creation. Example: squares_dict = {x: x**2 for x in range(5)} print(squares_dict) # 输出结果: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

8. Set Comprehension – Concise set creation. Example: squares_set = {x**2 for x in range(5)} print(squares_set) # 输出结果: {0, 1, 4, 9, 16}

9. Function Definition – Define functions with def . Example: def greet(name): return f"Hello, {name}!" print(greet("Alice")) # 输出结果: Hello, Alice!

10. Parameter Passing – Functions can accept positional, keyword, and default arguments. Example: def greet(name, greeting="Hello"): return f"{greeting}, {name}!" print(greet("Alice")) # 输出结果: Hello, Alice! print(greet("Alice", greeting="Hi")) # 输出结果: Hi, Alice!

11. Variable Arguments – Use *args and **kwargs for flexible arguments. Example: def print_args(*args): for arg in args: print(arg) def print_kwargs(**kwargs): for key, value in kwargs.items(): print(f"{key}: {value}") print_args(1, 2, 3) # 输出结果: 1 2 3 print_kwargs(name="Alice", age=30) # 输出结果: name: Alice age: 30

12. Generators – Use yield to create iterators. Example: def even_numbers(n): for i in range(n): if i % 2 == 0: yield i for num in even_numbers(10): print(num) # 输出结果: 0 2 4 6 8

13. Exception Handling – Manage errors with try , except , else , and finally . Example: try: result = 10 / 0 except ZeroDivisionError: print("除零错误!") finally: print("清理代码。") # 输出结果: 除零错误! 清理代码。

14. File Operations – Read and write files using open . Example: try: with open("example.txt", "r") as file: contents = file.read() print(contents) except FileNotFoundError: print("文件未找到!") except PermissionError: print("权限被拒绝!") finally: print("清理代码。")

15. Class Definition – Define classes with class . Example: class Dog: def __init__(self, name): self.name = name def bark(self): print(f"{self.name} is barking!") my_dog = Dog("Buddy") my_dog.bark() # 输出结果: Buddy is barking!

16. Inheritance – Create subclasses that inherit from a parent class. Example: class Animal: def eat(self): print("The animal is eating.") class Cat(Animal): def meow(self): print("Meow!") my_cat = Cat() my_cat.eat() # 输出结果: The animal is eating. my_cat.meow() # 输出结果: Meow!

17. Polymorphism – Different classes respond uniquely to the same method. Example: class Shape: def draw(self): raise NotImplementedError() class Circle(Shape): def draw(self): print("Drawing a circle.") class Rectangle(Shape): def draw(self): print("Drawing a rectangle.") def draw_shape(shape): shape.draw() circle = Circle() rectangle = Rectangle() draw_shape(circle) # 输出结果: Drawing a circle. draw_shape(rectangle) # 输出结果: Drawing a rectangle.

18. Decorators – Modify function behavior. Example: def my_decorator(func): def wrapper(): print("在函数之前执行的代码") func() print("在函数之后执行的代码") return wrapper @my_decorator def say_hello(): print("Hello!") say_hello() # 输出结果: # 在函数之前执行的代码 # Hello! # 在函数之后执行的代码

19. Context Managers – Manage resources with the with statement. Example: class MyContextManager: def __enter__(self): print("进入上下文") return self def __exit__(self, exc_type, exc_val, exc_tb): print("退出上下文") with MyContextManager() as manager: print("在上下文中执行的代码") # 输出结果: # 进入上下文 # 在上下文中执行的代码 # 退出上下文

20. Closures – Capture surrounding state in nested functions. Example: def outer_function(msg): def inner_function(): print(msg) return inner_function hi_func = outer_function("Hi") bye_func = outer_function("Bye") hi_func() # 输出结果: Hi bye_func() # 输出结果: Bye

21. Property Access – Control attribute access with @property . Example: class Person: def __init__(self, name, age): self._name = name self._age = age @property def age(self): return self._age @age.setter def age(self, value): if value < 0: raise ValueError("年龄不能为负数") self._age = value person = Person("Alice", 30) print(person.age) # 输出结果: 30 person.age = 35 print(person.age) # 输出结果: 35

22. Class and Static Methods – Define with @classmethod and @staticmethod . Example: class MyClass: count = 0 def __init__(self, name): self.name = name MyClass.count += 1 @classmethod def get_count(cls): return cls.count @staticmethod def info(): print("这是一个静态方法") obj1 = MyClass("Obj1") obj2 = MyClass("Obj2") print(MyClass.get_count()) # 输出结果: 2 MyClass.info() # 输出结果: 这是一个静态方法

23. Descriptors – Manage attribute access via the descriptor protocol. Example: class Descriptor: def __get__(self, instance, owner): print("获取属性") return instance._value def __set__(self, instance, value): print("设置属性") instance._value = value def __delete__(self, instance): print("删除属性") del instance._value class MyClass: value = Descriptor() def __init__(self, value): self.value = value obj = MyClass(10) print(obj.value) # 获取属性\n10 obj.value = 20 # 设置属性 del obj.value # 删除属性

24. Metaclasses – Control class creation. Example: class Meta(type): def __new__(cls, name, bases, dct): print(f"Creating class {name}") return super().__new__(cls, name, bases, dct) class MyClass(metaclass=Meta): pass obj = MyClass() # 输出结果: Creating class MyClass

25. Recursion – Solve problems by defining functions that call themselves. Example: def factorial(n): if n == 0: return 1 else: return n * factorial(n - 1) print(factorial(5)) # 输出结果: 120

These 25 key Python syntax points are commonly used and highly practical; mastering them will improve your programming skills and enable you to write more effective code.

Pythoncode examplesSyntaxProgramming Basics
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.