👶 STARTING FROM ZERO

🐍 Python Basics

Never programmed before? Perfect! We'll teach you Python like you're learning your ABCs. By the end, you'll write actual code!

Chapter 1: What is Python?

👶 Explain Like I'm 5

Python is a language that lets you talk to computers!

Just like you speak English to friends, you write Python to make computers do things.

Python is EASY - it reads almost like English!

🌍 What Can You Build With Python?

  • Websites: Instagram, YouTube, Spotify use Python!
  • AI & Machine Learning: ChatGPT, image recognition
  • Data Analysis: Analyzing sales, predicting trends
  • Automation: Auto-send emails, rename 1000 files
  • Games: Simple games and simulations

Your First Python Code!

# This is my first Python program!
# Lines starting with # are comments (notes for humans)

print("Hello, World!")

# Output: Hello, World!

🔍 What Just Happened?

print() is a function (a command) that displays something on screen

"Hello, World!" is a string (text in quotes)

Python reads this and shows "Hello, World!" on your screen!

Chapter 2: Variables (Storage Boxes)

👶 Explain Like I'm 5

A variable is like a labeled box where you store stuff!

You give the box a name (like "age") and put something inside (like 25).

Later, you can open the box and use what's inside!

📦 Think of Variables as Boxes

┌─────────────┐    ┌─────────────┐    ┌─────────────┐
│    age      │    │    name     │    │   height    │
├─────────────┤    ├─────────────┤    ├─────────────┤
│     25      │    │   "Alice"   │    │    5.6      │
└─────────────┘    └─────────────┘    └─────────────┘
   integer            string            float
# Creating variables (putting stuff in boxes)

age = 25                  # Box named "age" holds number 25
name = "Alice"            # Box named "name" holds text "Alice"
height = 5.6              # Box named "height" holds decimal 5.6
is_student = True         # Box named "is_student" holds True/False

# Using the variables
print("Name:", name)
print("Age:", age)
print("Height:", height, "feet")
print("Is student?", is_student)

# Output:
# Name: Alice
# Age: 25
# Height: 5.6 feet
# Is student? True

✏️ Try It Yourself!

Create variables for:

  • Your favorite color
  • Your birth year
  • Price of a pizza

Chapter 3: Data Types (Different Kinds of Stuff)

👶 Explain Like I'm 5

Just like real life has different things (numbers, words, yes/no answers)...

Python has different types of data!

The type matters because you can't add "apple" + 5 (that makes no sense!)

Data Type Python Name Example Used For
Integer int 42, -7, 0 Whole numbers (age, count)
Float float 3.14, -0.5, 2.0 Decimal numbers (price, weight)
String str "Hello", 'World' Text (names, messages)
Boolean bool True, False Yes/No, On/Off questions
# Different data types

my_age = 25                  # Integer (whole number)
my_height = 5.9              # Float (decimal number)
my_name = "John"             # String (text)
is_happy = True              # Boolean (True or False)

# Check what type a variable is using type()
print(type(my_age))        # Output: <class 'int'>
print(type(my_height))     # Output: <class 'float'>
print(type(my_name))       # Output: <class 'str'>
print(type(is_happy))      # Output: <class 'bool'>

Converting Between Types (Type Casting)

🔄 Why Convert Types?

Sometimes you get a number as text (like from user input): "25"

You can't do math with text! You need to convert it to an actual number.

# Type conversion examples

# String to Integer
age_text = "25"
age_number = int(age_text)
print(age_number + 5)        # Output: 30

# Integer to String
year = 2024
year_text = str(year)
print("Year is: " + year_text)  # Output: Year is: 2024

# Float to Integer (cuts off decimals!)
price = 99.99
print(int(price))           # Output: 99

# Integer to Float
count = 5
print(float(count))         # Output: 5.0

Chapter 4: Strings (Working with Text)

📝 Strings are Text!

Anything in quotes is a string: "Hello", 'World', "123"

Note: "123" is text, not a number! You can't do math with it.

String Methods (Text Superpowers!)

Python gives you many ways to manipulate text:

# String methods - text manipulation superpowers!

text = "  Hello World  "

# Convert to UPPERCASE
print(text.upper())           # Output: "  HELLO WORLD  "

# Convert to lowercase
print(text.lower())           # Output: "  hello world  "

# Remove spaces from both sides
print(text.strip())           # Output: "Hello World"

# Replace words
print(text.replace("World", "Python"))   # Output: "  Hello Python  "

# Split into a list of words
words = "apple,banana,cherry"
print(words.split(","))        # Output: ['apple', 'banana', 'cherry']

# Check if text contains something
print("World" in text)       # Output: True
print("Python" in text)      # Output: False

# Count occurrences
message = "I love Python. Python is great!"
print(message.count("Python"))  # Output: 2

# Get length of string
print(len("Hello"))          # Output: 5

String Indexing (Finding Characters)

🔢 Every Character Has a Position!

Think of a string as a row of lockers. Each locker has a number starting from 0!

📊 String Index Positions

String: "Python"

Position:  0   1   2   3   4   5
         +---+---+---+---+---+---+
         | P | y | t | h | o | n |
         +---+---+---+---+---+---+
Negative: -6  -5  -4  -3  -2  -1
word = "Python"

# Access single characters
print(word[0])       # Output: P (first character)
print(word[1])       # Output: y (second character)
print(word[-1])      # Output: n (last character)
print(word[-2])      # Output: o (second to last)

# Slicing - get a portion of the string
# syntax: word[start:stop] (stop is NOT included!)
print(word[0:3])     # Output: Pyt (characters 0, 1, 2)
print(word[2:])      # Output: thon (from position 2 to end)
print(word[:4])      # Output: Pyth (from start to position 3)
print(word[::2])     # Output: Pto (every 2nd character)
print(word[::-1])    # Output: nohtyP (reversed!)

F-Strings (Easy Text Formatting)

# F-strings - the easiest way to insert variables into text!
# Put 'f' before the quotes, then use {variable} inside

name = "Alice"
age = 25
salary = 50000.789

# Simple f-string
print(f"My name is {name} and I am {age} years old.")
# Output: My name is Alice and I am 25 years old.

# Format numbers
print(f"My salary is ${salary:.2f}")  # .2f = 2 decimal places
# Output: My salary is $50000.79

# Do calculations inside {}
print(f"In 5 years I will be {age + 5}")
# Output: In 5 years I will be 30

Chapter 5: Operators (Doing Math & Comparisons)

Arithmetic Operators (Math!)

Operator Name Example Result
+ Addition 5 + 3 8
- Subtraction 10 - 4 6
* Multiplication 6 * 7 42
/ Division 10 / 3 3.333...
// Floor Division 10 // 3 3 (no decimals)
% Modulus (Remainder) 10 % 3 1
** Power/Exponent 2 ** 3 8 (2³)

Comparison Operators (True or False?)

# Comparison operators return True or False

print(5 == 5)      # Equal to? True
print(5 != 3)      # Not equal to? True
print(7 > 4)       # Greater than? True
print(2 < 8)       # Less than? True
print(6 >= 6)      # Greater than or equal? True
print(3 <= 5)      # Less than or equal? True

Logical Operators (Combining Conditions)

# Logical operators combine True/False values

age = 25
has_license = True

# AND - Both must be True
print(age >= 18 and has_license)    # True (can drive!)

# OR - At least one must be True
print(age < 18 or has_license)      # True (has license)

# NOT - Reverses the result
print(not has_license)               # False (opposite of True)

Chapter 6: If Statements (Making Decisions)

👶 Explain Like I'm 5

An if statement is like a question with a plan:

"IF it's raining, THEN take an umbrella. ELSE, wear sunglasses."

Python does the same thing with code!

# Basic if statement
age = 20

if age >= 18:
    print("You are an adult!")
    print("You can vote!")

# Output:
# You are an adult!
# You can vote!

⚠️ Important: Indentation!

Notice the spaces before print()? That's called indentation.

Python uses indentation to know which code belongs to the if!

Always use 4 spaces (or 1 Tab) for indentation.

if-else (Two Options)

age = 15

if age >= 18:
    print("You are an adult!")
else:
    print("You are a minor.")

# Output: You are a minor.

if-elif-else (Multiple Options)

# Grade calculator
score = 75

if score >= 90:
    print("Grade: A - Excellent!")
elif score >= 80:
    print("Grade: B - Good!")
elif score >= 70:
    print("Grade: C - Average")
elif score >= 60:
    print("Grade: D - Below Average")
else:
    print("Grade: F - Fail")

# Output: Grade: C - Average

Chapter 7: Loops (Repeating Stuff)

👶 Explain Like I'm 5

A loop is like saying: "Do this 10 times" or "Do this for each item in the list"

Instead of writing the same code 100 times, you write it once and loop!

For Loop (Do This for Each Item)

# For loop - repeat for each item in a sequence

# Loop through a list
fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print(f"I like {fruit}!")

# Output:
# I like apple!
# I like banana!
# I like cherry!

The range() Function

# range() generates a sequence of numbers

# Print numbers 0 to 4
for i in range(5):
    print(i)

# Output: 0, 1, 2, 3, 4

# Print numbers 1 to 5
for i in range(1, 6):
    print(i)

# Output: 1, 2, 3, 4, 5

# Print even numbers 0 to 10
for i in range(0, 11, 2):  # Start, Stop, Step
    print(i)

# Output: 0, 2, 4, 6, 8, 10

While Loop (Keep Going Until...)

# While loop - repeat WHILE a condition is True

count = 1

while count <= 5:
    print(f"Count is: {count}")
    count = count + 1  # Don't forget to increment!

# Output:
# Count is: 1
# Count is: 2
# Count is: 3
# Count is: 4
# Count is: 5

Break and Continue (Loop Control)

# break - exit the loop immediately
for i in range(10):
    if i == 5:
        print("Found 5! Breaking out...")
        break
    print(i)

# Output: 0, 1, 2, 3, 4, Found 5! Breaking out...

# continue - skip this iteration, go to next
for i in range(5):
    if i == 2:
        continue  # Skip when i is 2
    print(i)

# Output: 0, 1, 3, 4 (skipped 2!)

🚫 Common Mistakes in Python Basics

💭 Short reflection

In one sentence: why is it important to use a loop (for/while) instead of copying the same code many times?

✅ CORE (Must know)

📚 NON-CORE (Good to know)

Chapter 8: Summary - What You Learned!

Concept What It Does Example
Variables Store data age = 25
Data Types Different kinds of data int, float, str, bool
Strings Work with text "Hello".upper()
Operators Math & comparisons + - * / == > <
If Statements Make decisions if age >= 18:
For Loops Repeat for each item for x in list:
While Loops Repeat while condition is True while count < 10:

🎉 Congratulations!

You now know the fundamentals of Python programming!

Next up: Data Structures (Lists, Tuples, Dictionaries) →