Cheatsheet Summary of 25 Core Python Concepts (Double Your Learning Efficiency)
Python beginners often struggle with “too many and scattered concepts that are forgotten as soon as they’re learned” – variable naming, data types, loop logic, function parameters… You just memorize one, and then confuse it with another.
Actually, learning Python doesn’t require rote memorization. Today, I’ve distilled 25 core concepts beginners must master into a “cheatsheet + minimalist example” format. Each cheatsheet is under 10 words – easy to read, easy to remember – doubling your learning efficiency!
Whether you’re solving practice problems, working on small projects, or preparing for an interview, follow the cheatsheets to quickly jog your memory anytime!
I. Basic Syntax: Foundational “Must-Knows”
1. Variable Naming
- Cheatsheet: Letters, digits, underscore; first char not digit.
- Explanation: Variable names can only contain letters (a-z/A-Z), digits (0-9), underscore (_). First character cannot be a digit. Case-sensitive.
- Example:pythonname = “Xiaoming” # Valid age20 = 20 # Valid 20age = 20 # Error (starts with digit) my-name = “123” # Error (contains illegal ‘-‘)
2. Comment Rules
- Cheatsheet: Single line
#, multi-line triple quotes. - Explanation: Single-line comments start with
#. Multi-line comments are wrapped in'''or""". Commented content is not executed. - Example:python# This is a single-line comment print(“hello”) # Can also add comment at line end ”’ This is a multi-line comment ”’ “”” Double quotes also work for multi-line comments “””
3. Data Type Classification
- Cheatsheet: Mutable: List, Dict, Set. Immutable: Num, Str, Tuple.
- Explanation: Mutable types (can modify elements): List (
list), Dictionary (dict), Set (set). Immutable types (cannot change after creation): Numbers (int/float), String (str), Tuple (tuple). - Example:pythonlst = [1, 2, 3] lst[0] = 0 # Mutable, can modify → [0, 2, 3] s = “hello” s[0] = “H” # Immutable, error!
4. Operator Precedence
- Cheatsheet: Parentheses first, then multiply/divide, then add/subtract.
- Explanation: Order of operations:
()> Arithmetic (**>*///>+-) > Comparison > Logical. - Example:pythonprint(2 + 3 * 4) # 14 (multiply first) print((2 + 3) * 4) # 20 (parentheses first) print(3 > 2 and 1 < 2) # True (compare then logic)
5. is vs ==
- Cheatsheet:
==compares value,iscompares identity (address). - Explanation:
==checks if values are equal.ischecks if they are the same object in memory (same identity). - Example:pythona = [1, 2] b = [1, 2] print(a == b) # True (same value) print(a is b) # False (different objects/addresses)
II. Data Types: Operation Cheatsheets “Clear in One Bite”
6. String Concatenation
- Cheatsheet: Few use
+, many usejoin(). - Explanation: Use
+for concatenating 2-3 strings. Usejoin()for joining many strings or a list for better efficiency. - Example:pythonprint(“hello” + ” world”) # Few strings lst = [“a”, “b”, “c”] print(“”.join(lst)) # Many strings → “abc”
7. Adding to a List
- Cheatsheet:
appendadds whole,extendadds elements. - Explanation:
append()adds the entire object.extend()unpacks an iterable and adds its elements. - Example:pythonlst = [1, 2] lst.append([3, 4]) # → [1, 2, [3, 4]] lst.extend([3, 4]) # → [1, 2, 3, 4]
8. Removing from a List
- Cheatsheet:
delby index,popremoves & returns,removeby value. - Explanation:
deldeletes by index.pop()removes element and returns it.remove()deletes first matching item by value. - Example:pythonlst = [1, 2, 3, 2] del lst[0] # → [2, 3, 2] lst.pop() # → 2, lst becomes [2, 3] lst.remove(2) # → [3] (removes first ‘2’)
9. Tuple Characteristics
- Cheatsheet: Parentheses, immutable.
- Explanation: Tuples are defined with
(). Cannot add, delete, or modify elements after creation. Good for storing fixed data. - Example:pythontup = (1, 2, 3) tup[0] = 0 # Error! (immutable)
10. Dictionary Operations
- Cheatsheet: Keys unique, store/access key-value pairs.
- Explanation: Dictionaries store
key:valuepairs. Keys must be unique. Access values by key. - Example:pythondic = {“name”: “Xiaoming”, “age”: 20} print(dic[“name”]) # Access by key → “Xiaoming” dic[“gender”] = “Male” # Add new key-value pair
11. Set Deduplication
- Cheatsheet: Braces without keys, auto-removes duplicates.
- Explanation: Sets are defined with
{}(no keys). Automatically removes duplicate elements. Unordered. - Example:pythons = {1, 2, 2, 3} print(s) # Auto-deduplicates → {1, 2, 3}
12. String Slicing
- Cheatsheet: Start included, end excluded; step optional.
- Explanation: Slice format:
s[start:end:step]. Includesstart, excludesend.stepcontrols interval. - Example:pythons = “abcdef” print(s[1:4]) # → “bcd” (indices 1,2,3) print(s[::2]) # → “ace” (step 2, get every other)
III. Flow Control: Loops & Conditionals “Stay on Track”
13. if Conditional
- Cheatsheet: Indent block; execute if true.
- Explanation: Code block executes if condition after
ifis true. Block must be indented (usually 4 spaces).else/elifmust align withif. - Example:pythonage = 18 if age >= 18: print(“Adult”) else: print(“Minor”)
14. for Loop
- Cheatsheet: Iterate over iterable after
in. - Explanation:
forloop iterates over iterables (list, string, range, etc.). Format:for variable in iterable:. - Example:pythonfor i in range(3): print(i) # → 0, 1, 2 for char in “abc”: print(char) # → a, b, c
15. while Loop
- Cheatsheet: Loop while true;
breakto stop. - Explanation: Loops while condition after
whileis true.breakimmediately terminates the entire loop. - Example:pythoni = 0 while i < 3: print(i) # → 0, 1, 2 i += 1
16. break vs continue
- Cheatsheet:
breakstops loop;continueskips current iteration. - Explanation:
breakterminates the whole loop.continueskips the rest of current iteration, moves to next. - Example:pythonfor i in range(5): if i == 2: break # Stops at 2 → prints 0, 1 for i in range(5): if i == 2: continue # Skips 2 → prints 0, 1, 3, 4
IV. Functions & Scope: Define & Call “Avoid Pitfalls”
17. Function Definition
- Cheatsheet: Start with
def, return withreturn. - Explanation: Define function with
defkeyword.returnspecifies return value (returnsNoneif noreturn). - Example:pythondef add(x, y): return x + y # Returns sum print(add(2, 3)) # → 5
18. Positional Arguments
- Cheatsheet: Pass by order; count must match.
- Explanation: Positional arguments must be passed in the order defined. Number must match.
- Example:pythondef func(a, b): print(a, b) func(1, 2) # By order → prints 1 2
19. Keyword Arguments
- Cheatsheet: Pass by name; order doesn’t matter.
- Explanation: Keyword arguments passed as
param_name=value. Order can be arbitrary. Must come after positional arguments. - Example:pythonfunc(b=2, a=1) # By name → prints 1 2 (order irrelevant)
20. Default Arguments
- Cheatsheet: Set default value; can be omitted.
- Explanation: Set default value in function definition. Can be omitted when calling (uses default).
- Example:pythondef func(a, b=2): print(a, b) func(1) # b omitted → prints 1 2
21. Variable Arguments
- Cheatsheet:
*argstuple,**kwargsdict. - Explanation:
*argsreceives any number of positional arguments (as tuple).**kwargsreceives any number of keyword arguments (as dict). - Example:pythondef func(*args, **kwargs): print(args) # → (1, 2, 3) print(kwargs) # → {“name”: “Xiaoming”} func(1, 2, 3, name=”Xiaoming”)
22. Global vs Local Variables
- Cheatsheet: Local inside function; declare
globalto modify outside. - Explanation: Variables defined inside a function are local (only used inside). Use
globaldeclaration to modify a global variable. - Example:pythona = 10 # Global variable def func(): global a # Declare to modify global a = 20 func() print(a) # → 20
V. Files & Modules: Practical Operations “Remember Cheatsheet”
23. Module Import
- Cheatsheet:
importwhole module,fromimport part. - Explanation:
import module_nameimports entire module.from module_name import functionalityimports only specified parts. - Example:pythonimport math print(math.sqrt(4)) # Whole module → 2.0 from math import sqrt print(sqrt(4)) # Partial import → 2.0
24. File Open Modes
- Cheatsheet:
rread,wwrite (overwrites),aappend. - Explanation:
rread-only (error if file not exist).wwrite (overwrites, creates if not exist).aappend (creates if not exist). - Example:pythonwith open(“test.txt”, “w”) as f: f.write(“hello”) # Write (overwrites) with open(“test.txt”, “a”) as f: f.write(” world”) # Append
25. Exception Handling
- Cheatsheet: Wrap in
try, catch withexcept. - Explanation: Use
try-exceptto catch exceptions, preventing program crash. Can specify exception type to catch. - Example:pythontry: 1 / 0 # Code that will cause error except ZeroDivisionError: print(“Cannot divide by zero”) # Catch and handle
Summary: Key Techniques for Rapid Memorization
These 25 cheatsheets cover about 90% of core scenarios for Python beginners. Remember two key points when memorizing:
- Memorize the cheatsheet first, then understand with examples (don’t memorize syntax by rote; let the cheatsheet trigger memory).
- Spend 5 minutes daily, recite the cheatsheet and write the corresponding example from memory. Repeat this 3 times to build a conditioned reflex.
Related articles