Table of Contents
How to Use This Appendix
The appendix is your quick reference section. It’s not meant to teach everything from scratch, but to help you:
- Quickly check Python syntax.
- Look up common errors and how to fix them.
- Remember key terms and their meanings.
Use it alongside the main chapters when you forget details or want a fast reminder.
Python Syntax Cheat Sheet
This cheat sheet assumes you already saw these ideas in earlier chapters. It focuses on the most common patterns and “look-up” style examples.
Running Python
Terminal / command line:
- Run a script:
python my_script.py- Start interactive mode:
python
(Your system might use python3 instead of python.)
Basics
Printing and comments
- Print something:
print("Hello")- Single-line comment:
# This is a comment- Multi-line string (often used for long comments or docs):
"""
This is a multi-line string.
Not truly a comment, but often used like one.
"""Variables and basic types
- Assigning:
name = "Alice" # str
age = 30 # int
height = 1.75 # float
is_student = True # bool- Check type:
type(age) # <class 'int'>Numbers and Operators
Arithmetic operators
- Addition:
a + b - Subtraction:
a - b - Multiplication:
a * b - Division (float):
a / b - Floor division (integer-ish):
a // b - Remainder (modulo):
a % b - Power:
a ** b
Example:
x = 10
y = 3
print(x + y) # 13
print(x / y) # 3.3333333...
print(x // y) # 3
print(x % y) # 1
print(x ** y) # 1000Converting types
int("10") # 10
float("3.14") # 3.14
str(123) # "123"
bool(0) # False
bool(5) # TrueStrings
Creating strings
s1 = "Hello"
s2 = 'World'
s3 = "I'm learning Python"Basic string operations
- Concatenation:
"Hello " + "World" # "Hello World"- Repetition:
"ha" * 3 # "hahaha"- Length:
len("Python") # 6- Indexing and slicing:
text = "Python"
text[0] # "P"
text[1:4] # "yth"
text[-1] # "n"- Changing case:
s = "Hello"
s.lower() # "hello"
s.upper() # "HELLO"- Finding and replacing:
s = "Hello world"
s.find("world") # 6
s.replace("world", "Python") # "Hello Python"f-strings (formatted strings)
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")Input and Output
Getting input
user_name = input("Enter your name: ")Input is always a string. Convert if needed:
age = int(input("Enter your age: "))
height = float(input("Enter your height in meters: "))Formatting numbers
pi = 3.14159265
print(f"Pi is about {pi:.2f}") # 2 decimal places
print(f"{42:05d}") # 00042Conditions
Comparison operators
==equal!=not equal>greater than<less than>=greater than or equal<=less than or equal
Logical operators
andornot
if / elif / else pattern
age = 20
if age < 13:
print("Child")
elif age < 18:
print("Teenager")
else:
print("Adult")Nested conditions
if age >= 18:
if age >= 65:
print("Senior")
else:
print("Adult but not senior")Loops
while loop
count = 0
while count < 5:
print(count)
count += 1for loop
- Over a range:
for i in range(5): # 0,1,2,3,4
print(i)- With start and step:
for i in range(2, 10, 2): # 2,4,6,8
print(i)- Over a list:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)break and continue
for n in range(10):
if n == 5:
break # stop loop completely
if n % 2 == 0:
continue # skip even numbers
print(n)Collections
Lists
- Create:
numbers = [1, 2, 3]
mixed = [1, "two", 3.0]- Access:
numbers[0] # 1
numbers[-1] # 3- Modify:
numbers[1] = 20- Add / remove:
numbers.append(4)
numbers.insert(1, 99)
numbers.remove(20)
popped = numbers.pop() # removes last- Length:
len(numbers)Tuples
Like lists but immutable:
point = (10, 20)
x = point[0]Dictionaries
Key-value pairs:
person = {
"name": "Alice",
"age": 25,
}
print(person["name"]) # "Alice"
person["age"] = 26 # update
person["city"] = "London" # new keyLooping:
for key, value in person.items():
print(key, value)Sets (basics)
No duplicates, unordered:
nums = {1, 2, 3, 3}
print(nums) # {1, 2, 3}
nums.add(4)
nums.remove(2)Functions
Defining and calling
def greet(name):
print(f"Hello, {name}!")
greet("Alice")Return values
def add(a, b):
return a + b
result = add(3, 5)Default arguments
def greet(name, greeting="Hello"):
print(f"{greeting}, {name}!")
greet("Bob")
greet("Carol", "Hi")Files (text mode)
Always prefer with to auto-close:
# Reading
with open("data.txt", "r", encoding="utf-8") as f:
content = f.read()
# Writing (overwrites)
with open("output.txt", "w", encoding="utf-8") as f:
f.write("Hello\n")
# Appending
with open("output.txt", "a", encoding="utf-8") as f:
f.write("More text\n")Errors and Exceptions
try / except
try:
x = int(input("Enter a number: "))
print(10 / x)
except ValueError:
print("That was not a valid integer!")
except ZeroDivisionError:
print("You cannot divide by zero.")Raising your own error
def sqrt(x):
if x < 0:
raise ValueError("x must be non-negative")
# compute sqrt hereImports and Libraries
Importing modules
import math
print(math.sqrt(16))
from math import sqrt
print(sqrt(25))
import random as rnd
print(rnd.randint(1, 10))Installing external libraries
Terminal:
pip install requestsIn Python:
import requestsVery Small OOP Reminder
Class and object
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print(f"Hi, I'm {self.name}.")
alice = Person("Alice", 25)
alice.greet()Common Errors and Solutions
This section helps when you see confusing error messages. Match the error type and scan for the short fix.
SyntaxError
Python couldn’t understand your code at all.
Typical causes:
- Missing colon
:afterif,for,while,def,class:
if x > 5 # WRONG
print("Hi")
# FIX:
if x > 5: # note the colon
print("Hi")- Unmatched parentheses, brackets, or quotes:
print("Hello) # WRONG
# FIX:
print("Hello")- Wrong indentation or mixing tabs and spaces.
Fix strategy: Check the line shown in the error and the line just before it carefully.
IndentationError
Your indentation (spaces at the start of the line) is inconsistent or invalid.
Common reasons:
- Missing indentation inside a block:
if x > 0:
print("positive") # WRONG
# FIX:
if x > 0:
print("positive")- Mixing tabs and spaces in the same file.
Fix strategy: Decide on 4 spaces per indent and stick to it. Most editors can convert tabs to spaces.
NameError: name 'something' is not defined
You used a name Python doesn’t know.
Typical reasons:
- Typo:
pritn("hi") # WRONG
# FIX:
print("hi")- Using a variable before assigning it:
print(age) # WRONG if age not defined yet
age = 20- Using a variable inside a function that’s only defined outside, without passing it in.
Fix strategy: Check for spelling and make sure the variable or function is defined above the usage.
TypeError
An operation was used on the wrong type.
Common cases:
- Adding string and integer:
age = 20
print("Age: " + age) # WRONG
# FIX:
print("Age: " + str(age))
# or:
print(f"Age: {age}")- Calling something that’s not a function:
x = 5
x() # WRONG, x is an int, not a functionFix strategy: Look at the full error message; it often says exactly which operation failed and for which types.
ValueError
You used the correct type, but an invalid value.
Examples:
- Converting a non-number string to int:
int("abc") # ValueError- Using
range(-5)is fine, but some functions may reject negative values.
Fix strategy: Double-check input values, add validation, or handle cases with try / except.
ZeroDivisionError: division by zero
You tried to divide by zero:
x = 0
10 / x # ZeroDivisionErrorFix strategy: Check for zero before dividing:
if x != 0:
result = 10 / x
else:
print("Cannot divide by zero")IndexError: list index out of range
You tried to access a list index that doesn’t exist.
Example:
nums = [10, 20, 30]
nums[3] # WRONG, last index is 2Fix strategy:
- Remember lists are 0-based.
- Check
len(list)before indexing. - Use safe loops:
for item in nums:
print(item)KeyError (dictionaries)
You tried to access a dictionary key that doesn’t exist.
Example:
person = {"name": "Alice"}
person["age"] # KeyErrorFix strategy:
- Use
dict.get(key, default):
age = person.get("age", "Unknown")- Check with
in:
if "age" in person:
print(person["age"])AttributeError
You tried to use an attribute or method that the object doesn’t have.
Example:
x = 5
x.append(10) # AttributeError, int has no appendFix strategy:
- Check the type:
print(type(x)). - Look up what methods that type supports.
- Make sure you didn’t overwrite something (e.g.
list = []then trying to uselist()).
ImportError / ModuleNotFoundError
Python couldn’t find a module.
Example:
import requessts # typoFix strategy:
- Check spelling.
- For external libraries, ensure they’re installed:
pip install requests- Make sure you’re using the same Python interpreter where the package is installed.
FileNotFoundError
The file path you gave doesn’t exist.
Example:
with open("data.txt") as f:
content = f.read()Fix strategy:
- Check the file name and folder.
- Print the current working directory:
import os
print(os.getcwd())- Use full (absolute) paths when debugging problems.
Glossary of Terms
Short definitions to refresh your memory. These are reminders, not full lessons.
- Argument
A value you pass into a function when you call it, e.g. inprint("Hi"), the string"Hi"is an argument. - Boolean (bool)
A type with only two possible values:TrueorFalse. - Class
A blueprint for creating objects. It defines what data (attributes) and actions (methods) those objects have. - Comment
Text in your code ignored by Python, used to explain what your code does. Starts with#. - Conditional (if statement)
Code that runs only if a condition isTrue, usingif,elif, andelse. - Data type
The kind or category of a value, such asint,float,str,bool,list, etc. - Dictionary (
dict)
A collection of key–value pairs, like a mini database where you look things up by key. - Exception
An error that happens while the program is running (runtime error), which can be caught and handled withtry/except. - Float
A number with a decimal point, like3.14or0.5. - Function
A reusable block of code that can take inputs (arguments), do something, and optionally return a result. - IDE (Integrated Development Environment)
A program designed for writing code (like VS Code, PyCharm, or IDLE) that provides editing, running, and debugging tools. - Import
Bringing code from another module or library into your file usingimport. - Indentation
Spaces at the start of a line that show which code belongs to which block (if,for,def, etc.). In Python, indentation is part of the syntax. - Integer (
int)
A whole number without a decimal part, like-3,0,42. - Library / Module
A collection of ready-made functions, classes, and tools you canimportand use instead of writing everything yourself. - List
An ordered, changeable collection of items, e.g.[1, 2, 3]or["a", "b"]. - Loop
Code that repeats multiple times, usingfororwhile. - Object
A specific instance created from a class, with its own data and behavior. For example, onePersonobject withname="Alice". - Parameter
A variable listed in a function definition, e.g.def greet(name):— herenameis a parameter. - Return value
The value a function sends back usingreturn. If noreturnis used, the function returnsNone. - Set
An unordered collection of unique elements, e.g.{1, 2, 3}. - String (
str)
Text data, e.g."Hello"or"123". - Syntax
The rules for how code must be written so the interpreter can understand it. - Variable
A named place in memory where a value is stored, e.g.x = 10. - While loop
Repeats as long as a condition isTrue. - For loop
Repeats over each item in a sequence (like a list orrange).
Use this appendix whenever you:
- See an error you don’t recognize.
- Forget how to write a particular Python expression.
- Need a quick definition of a term.