Kahibaro
Discord Login Register

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:

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:

  python my_script.py
  python

(Your system might use python3 instead of python.)

Basics

Printing and comments

  print("Hello")
  # This is a comment
  """
This is a multi-line string.
Not truly a comment, but often used like one.
"""

Variables and basic types

  name = "Alice"   # str
  age = 30         # int
  height = 1.75    # float
  is_student = True  # bool
  type(age)  # <class 'int'>

Numbers and Operators

Arithmetic operators

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

  "Hello " + "World"  # "Hello World"
  "ha" * 3  # "hahaha"
  len("Python")  # 6
  text = "Python"
  text[0]    # "P"
  text[1:4]  # "yth"
  text[-1]   # "n"
  s = "Hello"
  s.lower()  # "hello"
  s.upper()  # "HELLO"
  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

Logical operators

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

  for i in range(5):  # 0,1,2,3,4
      print(i)
  for i in range(2, 10, 2):  # 2,4,6,8
      print(i)
  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

  numbers = [1, 2, 3]
  mixed = [1, "two", 3.0]
  numbers[0]      # 1
  numbers[-1]     # 3
  numbers[1] = 20
  numbers.append(4)
  numbers.insert(1, 99)
  numbers.remove(20)
  popped = numbers.pop()  # removes last
  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:

  if x > 5   # WRONG
      print("Hi")
  # FIX:
  if x > 5:  # note the colon
      print("Hi")
  print("Hello)     # WRONG
  # FIX:
  print("Hello")

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:

  if x > 0:
  print("positive")   # WRONG
  # FIX:
  if x > 0:
      print("positive")

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:

  pritn("hi")   # WRONG
  # FIX:
  print("hi")
  print(age)    # WRONG if age not defined yet
  age = 20

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:

  age = 20
  print("Age: " + age)   # WRONG
  # FIX:
  print("Age: " + str(age))
  # or:
  print(f"Age: {age}")
  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:

  int("abc")  # ValueError

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:

  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:

  age = person.get("age", "Unknown")
  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:

ImportError / ModuleNotFoundError

Python couldn’t find a module.

Example:

import requessts   # typo

Fix strategy:

  pip install requests

FileNotFoundError

The file path you gave doesn’t exist.

Example:

with open("data.txt") as f:
    content = f.read()

Fix strategy:

  import os
  print(os.getcwd())

Glossary of Terms

Short definitions to refresh your memory. These are reminders, not full lessons.

Use this appendix whenever you:

Views: 18

Comments

Please login to add a comment.

Don't have an account? Register now!