Python Fundamentals Cheatcodes
Python 3 Fundamentals — Reference Sheet
1. Basic Syntax Rules
Statements and Execution
Python executes code sequentially from top to bottom. Statements do not require terminating semicolons.
main.pyRunnable## A simple sequence of statements print("Initializing database connection...") network_port = 8080 print("Listening on port:", network_port)
Code Comments (Annotations)
Comments are ignored by the Python interpreter during script execution. Use them to explain your program's structure and goals.
main.pyRunnable## This is a single-line comment """ This is a multiline comment block, ideal for script documentation headers. """
Case Sensitivity
Python is strictly case-sensitive. Variable names, functions, and keywords must match case parameters exactly.
main.pyRunnablenetwork_rate = 100 # Variable A Network_Rate = 200 # Variable B (separate allocation in memory) print(network_rate) # Works PRINT(network_rate) # ❌ ERROR: NameError (PRINT is not defined)
2. Variable Naming Rules
Variables act as named containers for system data. Choose descriptive names that follow these standard syntax rules:
- ✅ Good Naming Rules (Valid Syntax):
system_status = "active"(Uses standard Snake Case with lowercase letters and underscores)active_port_80 = True(Numbers are valid in middle or end positions)_internal_flag = False(Leading underscores are valid)
- ❌ Forbidden Naming Rules (Invalid Syntax):
system status = "active"(❌ Spaces are not allowed)80_active_port = True(❌ Identifiers cannot begin with a number)system-status = "active"(❌ Hyphens are treated as mathematical subtraction operators)while = True(❌ Reserved language keywords cannot be overwritten as identifiers)
3. Data Types Quick Reference
| Data Type | Python Identifier | Definition | Declaration Example |
|---|---|---|---|
| String | str | Text characters enclosed in quotes | name = "Marcus" |
| Integer | int | Positive or negative whole numbers | count = 45 |
| Float | float | Precise decimal values | gpa = 3.85 |
| Boolean | bool | Binary switches (True or False) | is_active = True |
4. Operators Quick Reference
Arithmetic Operators
main.pyRunnablex + y # Addition x - y # Subtraction x * y # Multiplication x / y # Division (returns a decimal Float value) x // y # Floor Division (divides and discards decimal values to return an Integer) x % y # Modulus (returns the remainder of division) x ** y # Exponent (x raised to the power of y)
Comparison Operators (Returns Boolean True or False)
main.pyRunnablex == y # Equal to? x != y # Not equal to? x > y # Greater than? x < y # Less than? x >= y # Greater than or equal to? x <= y # Less than or equal to?
Logical Operators (Merging Conditionals)
main.pyRunnablex and y # Returns True only if both statements are True x or y # Returns True if at least one statement is True not x # Negates the boolean value (turns True to False and vice versa)
Assignment Operators
main.pyRunnablebalance = 100 # Stores 100 in balance balance += 10 # Adds 10 to balance (balance is now 110) balance -= 5 # Subtracts 5 from balance (balance is now 105) balance *= 2 # Multiplies balance by 2 (balance is now 210) balance /= 2 # Divides balance by 2 (balance is now 105.0)
5. Type Casting Reference
Use explicit casting functions to convert compatible data types:
main.pyRunnable## Convert Strings to Numbers for mathematical calculations user_age = int("16") # Converts text string to integer 16 rate_value = float("3.85") # Converts text string to float 3.85 ## Convert Numbers to Strings for print concatenation output_label = str(16) # Converts integer 16 to text string "16"
6. Input / Output Reference
main.pyRunnable## 1. Ask for input (Always returns data as a String!) username = input("Enter username: ") user_age = int(input("Enter age: ")) # Captures input and immediately casts to an integer ## 2. Print output to console print("Active User:", username) print("Age Next Year:", user_age + 1)
7. Reserved Keywords
These identifiers are reserved by the interpreter for structural commands and cannot be used as variable names:
and as assert break class continue def del elif else except False finally for from global if import in is lambda None nonlocal not or pass raise return True try while with yield
8. Tracing Common Error Types
If your program crashes, check the traceback log for these standard exceptions:
SyntaxError— The code violates grammar rules (e.g., unmatched quotes, missing colons).NameError— You referenced an identifier that is misspelled or has not been declared.TypeError— You attempted an operation on incompatible types (e.g., adding text and integers:"Age: " + 16).ValueError— You passed a correct type but an incompatible value (e.g., converting letters:int("sixteen")).ZeroDivisionError— You mathematically attempted to divide a number by zero.
9. Quick Troubleshooting Checklist
Follow these five steps to systematically debug errors in your programs:
- Inspect Variable Spellings: Check that your variable names are spelled exactly the same way every time they appear in your code (e.g.,
total_costvstotalcost). - Audit Input Casting: Ensure all inputs captured via
input()are cast toint()orfloat()before being used in mathematical calculations. - Check Enclosures: Check that every opening double/single quote and parenthetical bracket has a corresponding closing partner.
- Inspect Concat Types: Confirm that you are not adding text strings and numbers together directly inside
print()without casting them usingstr(). - Verify Number Formatting: Check that numbers with decimals are not passed into the
int()function, which expects only clean whole number digits in string format.
10. Memory Helpers & Precedence Rules
Mathematical Operator Precedence (PEMDAS)
Python calculates complex arithmetic operations in this sequence:
- P — Parentheses
() - E — Exponents
** - M / D — Multiplication
*and Division/(evaluated left-to-right) - A / S — Addition
+and Subtraction-(evaluated left-to-right)
Logical Operator Precedence (NOT ➡️ AND ➡️ OR)
When combining logical operations, the interpreter solves them in this sequence:
notstatements are evaluated first.andstatements are evaluated second.orstatements are evaluated third.
11. Final Reference Checklist
Use this checklist to verify your procedural programs are ready:
Finished this lesson?
Mark it complete to advance your curriculum progress.