KAHIBARO Bookshelves
Discord Login Register

19. Appendix

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)  # 1000

Converting types

int("10")      # 10
float("3.14")  # 3.14
str(123)       # "123"
bool(0)        # False
bool(5)        # True

Strings

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}")                  # 00042

Conditions

Comparison operators

  • == equal
  • != not equal
  • > greater than
  • < less than
  • >= greater than or equal
  • <= less than or equal

Logical operators

  • and
  • or
  • not

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 += 1

for 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 key

Looping:

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 here

Imports 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 requests

In Python:

import requests

Very 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 : after if, 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 function

Fix 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  # ZeroDivisionError

Fix 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 2

Fix 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"]  # KeyError

Fix 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 append

Fix 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 use list()).

ImportError / ModuleNotFoundError

Python couldn’t find a module.

Example:

import requessts   # typo

Fix 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. in print("Hi"), the string "Hi" is an argument.
  • Boolean (bool)
    A type with only two possible values: True or False.
  • 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 is True, using if, elif, and else.
  • Data type
    The kind or category of a value, such as int, 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 with try / except.
  • Float
    A number with a decimal point, like 3.14 or 0.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 using import.
  • 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 can import and 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, using for or while.
  • Object
    A specific instance created from a class, with its own data and behavior. For example, one Person object with name="Alice".
  • Parameter
    A variable listed in a function definition, e.g. def greet(name): — here name is a parameter.
  • Return value
    The value a function sends back using return. If no return is used, the function returns None.
  • 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 is True.
  • For loop
    Repeats over each item in a sequence (like a list or range).

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.

Views: 0

Comments

Please login to add a comment.

Don't have an account? Register now!

Where to Move

Move chapter:

  • ☰ 1. Chapter 1: What Is Programming?
    • ☰ 1.1. What is a computer program?
      • ☰ 1.2. What is Python?
        • ☰ 1.3. Where is Python used?
          • ☰ 1.4. How programming helps solve problems
            • ☰ 1.5. Your first Python program
            • ☰ 2. Chapter 2: Setting Up Python
              • ☰ 2.1. Installing Python (Windows / macOS / Linux)
                • ☰ 2.2. Using Python in the terminal
                  • ☰ 2.3. Using an IDE (IDLE / VS Code)
                    • ☰ 2.4. Running Python scripts
                      • ☰ 2.5. Python interactive mode
                      • ☰ 3. Chapter 3: Variables and Data Types
                        • ☰ 3.1. What is a variable?
                          • ☰ 3.2. Creating variables
                            • ☰ 3.3. Numbers
                              • ☰ 3.4. Test
                                • ☰ 3.5. Boolean values
                                  • ☰ 3.6. Type checking
                                  • ☰ 4. Chapter 4: Basic Operations
                                    • ☰ 4.1. Arithmetic operations
                                      • ☰ 4.2. Working with numbers
                                        • ☰ 4.3. String operations
                                          • ☰ 4.4. Combining text and variables
                                            • ☰ 4.5. Comments in Python
                                            • ☰ 5. Chapter 5: User Input and Output
                                              • ☰ 5.1. Getting input from the user
                                                • ☰ 5.2. Converting input to numbers
                                                  • ☰ 5.3. Formatting output
                                                    • ☰ 5.4. Writing interactive programs
                                                    • ☰ 6. Chapter 6: Conditions
                                                      • ☰ 6.1. Comparison operators
                                                        • ☰ 6.2. Logical operators
                                                          • ☰ 6.3. if, elif, else
                                                            • ☰ 6.4. Nested conditions
                                                              • ☰ 6.5. Common beginner mistakes
                                                              • ☰ 7. Chapter 7: Loops
                                                                • ☰ 7.1. Why loops are useful
                                                                  • ☰ 7.2. for loops
                                                                    • ☰ 7.3. while loops
                                                                      • ☰ 7.4. Loop counters
                                                                        • ☰ 7.5. break and continue
                                                                          • ☰ 7.6. Loop exercises
                                                                          • ☰ 8. Chapter 8: Data Collections
                                                                            • ☰ 8.1. Lists
                                                                              • ☰ 8.2. Tuples
                                                                                • ☰ 8.3. Dictionaries
                                                                                  • ☰ 8.4. Sets (basics)
                                                                                    • ☰ 8.5. Choosing the right data structure
                                                                                    • ☰ 9. Chapter 9: Functions
                                                                                      • ☰ 9.1. Why functions matter
                                                                                        • ☰ 9.2. Defining functions
                                                                                          • ☰ 9.3. Parameters and arguments
                                                                                            • ☰ 9.4. Return values
                                                                                              • ☰ 9.5. Scope (local vs global)
                                                                                                • ☰ 9.6. Reusing code
                                                                                                • ☰ 10. Chapter 10: Working with Files
                                                                                                  • ☰ 10.1. What is a file?
                                                                                                    • ☰ 10.2. Reading text files
                                                                                                      • ☰ 10.3. Writing and appending files
                                                                                                        • ☰ 10.4. File paths
                                                                                                          • ☰ 10.5. Simple file-based programs
                                                                                                          • ☰ 11. Chapter 11: Errors and Debugging
                                                                                                            • ☰ 11.1. Types of errors
                                                                                                              • ☰ 11.2. Reading error messages
                                                                                                                • ☰ 11.3. Common beginner errors
                                                                                                                  • ☰ 11.4. try and except
                                                                                                                    • ☰ 11.5. Debugging strategies
                                                                                                                    • ☰ 12. Chapter 12: Using Python Libraries
                                                                                                                      • ☰ 12.1. What is a library?
                                                                                                                        • ☰ 12.2. Importing modules
                                                                                                                          • ☰ 12.3. Standard libraries
                                                                                                                            • ☰ 12.3.1. math
                                                                                                                              • ☰ 12.3.2. random
                                                                                                                                • ☰ 12.3.3. datetime
                                                                                                                                • ☰ 12.4. Installing external libraries with pip
                                                                                                                                • ☰ 13. Chapter 13: Object-Oriented Programming
                                                                                                                                  • ☰ 13.1. What is object-oriented programming?
                                                                                                                                    • ☰ 13.2. Classes and objects
                                                                                                                                      • ☰ 13.3. The `__init__` method
                                                                                                                                        • ☰ 13.4. Attributes and methods
                                                                                                                                          • ☰ 13.5. Encapsulation
                                                                                                                                            • ☰ 13.6. Inheritance (basics)
                                                                                                                                              • ☰ 13.7. Simple OOP examples
                                                                                                                                              • ☰ 14. Chapter 14: Automation with Python
                                                                                                                                                • ☰ 14.1. What is automation?
                                                                                                                                                  • ☰ 14.2. Automating simple tasks
                                                                                                                                                    • ☰ 14.3. Working with files and folders
                                                                                                                                                      • ☰ 14.4. Automating text processing
                                                                                                                                                        • ☰ 14.5. Scheduling scripts
                                                                                                                                                          • ☰ 14.6. Practical automation examples
                                                                                                                                                          • ☰ 15. Chapter 15: Web Development with Python
                                                                                                                                                            • ☰ 15.1. How the web works (basic overview)
                                                                                                                                                              • ☰ 15.2. Introduction to Flask
                                                                                                                                                                • ☰ 15.3. Creating a simple web server
                                                                                                                                                                  • ☰ 15.4. Routing and templates
                                                                                                                                                                    • ☰ 15.5. Handling user input (forms)
                                                                                                                                                                      • ☰ 15.6. Very basic APIs
                                                                                                                                                                      • ☰ 16. Chapter 16: Data Science with Python
                                                                                                                                                                        • ☰ 16.1. What is data science?
                                                                                                                                                                          • ☰ 16.2. Working with data
                                                                                                                                                                            • ☰ 16.3. Introduction to NumPy
                                                                                                                                                                              • ☰ 16.4. Introduction to pandas
                                                                                                                                                                                • ☰ 16.5. Data visualization with matplotlib
                                                                                                                                                                                  • ☰ 16.6. Simple data analysis examples
                                                                                                                                                                                  • ☰ 17. Chapter 17: Mini Projects
                                                                                                                                                                                    • ☰ 17.1. Number guessing game
                                                                                                                                                                                      • ☰ 17.2. Simple calculator
                                                                                                                                                                                        • ☰ 17.3. To-do list
                                                                                                                                                                                          • ☰ 17.4. Password generator
                                                                                                                                                                                            • ☰ 17.5. Quiz application
                                                                                                                                                                                              • ☰ 17.6. Small web or data project
                                                                                                                                                                                              • ☰ 18. Chapter 18: Next Steps
                                                                                                                                                                                                • ☰ 18.1. How to practice Python
                                                                                                                                                                                                  • ☰ 18.2. Writing clean and readable code
                                                                                                                                                                                                    • ☰ 18.3. Choosing a specialization
                                                                                                                                                                                                      • ☰ 18.3.1. Web development
                                                                                                                                                                                                        • ☰ 18.3.2. Data science
                                                                                                                                                                                                          • ☰ 18.3.3. Automation
                                                                                                                                                                                                            • ☰ 18.3.4. Software development
                                                                                                                                                                                                            • ☰ 18.4. Learning resources and communities
                                                                                                                                                                                                            • ☰ 19. Appendix
                                                                                                                                                                                                              • ☰ 19.1. Python syntax cheat sheet
                                                                                                                                                                                                                • ☰ 19.2. Common errors and solutions
                                                                                                                                                                                                                  • ☰ 19.3. Glossary of terms