Back to Home 18 lessons

Python for Beginners
Start Your Coding Journey

Learn Python from scratch — no prior experience needed. Master variables, loops, functions, OOP, and more with 18 beginner-friendly lessons by @PoeticGlenn.

— Sponsored —
Loading Python runtime…
Run each code example directly in your browser!
Every snippet includes a ▶ Run button powered by Pyodide — a Python interpreter that runs entirely in your browser. No installation needed. Click Run to execute the code and see the output instantly. All examples use Python 3.12+ syntax and are fully compatible with Pyodide.

What you will learn

This curriculum takes you from absolute beginner to confident Python programmer. You'll learn fundamental concepts: variables, data types, strings, numbers, lists, tuples, dictionaries, sets, conditionals, loops, functions, error handling, modules, file I/O, and object‑oriented programming — all explained step‑by‑step with clear examples from @PoeticGlenn.

Why Python is the Best Language to Start Your Programming Journey

Python is the most popular programming language in the world — and for good reason. It's designed to be readable, expressive, and beginner‑friendly. Unlike many other languages, Python's syntax is clean and intuitive, allowing you to focus on learning programming concepts rather than wrestling with complex syntax.

This curriculum, crafted by @PoeticGlenn, is your complete guide to Python from the ground up. You'll start with the absolute basics — what a variable is, how to store data — and gradually build up to advanced topics like object‑oriented programming. Every lesson is packed with real‑world examples, clear explanations, and code you can run and modify.

Readable & Elegant

Python's syntax is designed to be intuitive and readable, making it the perfect first language for new programmers.

Huge Community

With millions of Python developers worldwide, you'll never be stuck — help and resources are always available.

Endless Opportunities

From web development to data science, AI, automation, and beyond — Python opens doors to every field of tech.

"Python is the language that will teach you how to think like a programmer. Once you master it, every other language becomes easier to learn." 🐍

From a Hobby Project to the World's Most Popular Language

Python was created in the late 1980s by Guido van Rossum as a hobby project to keep him busy during the Christmas holidays. He named it after the British comedy troupe Monty Python — not the snake! What started as a personal project has grown into the most widely used programming language on the planet, powering everything from YouTube to NASA's space missions.

1989 — The Beginning

Guido van Rossum starts working on Python as a "hobby project" during Christmas. He wants to create a language that's easy to read and fun to use.

1991 — First Release

Python 0.9.0 is released. It already includes classes, functions, exception handling, and the core data types — lists, strings, and dictionaries.

1994 — Python 1.0

The first major milestone. Python 1.0 introduces functional programming tools like lambda, map, and filter.

2000 — Python 2.0

Python 2.0 introduces list comprehensions, garbage collection, and Unicode support. It becomes the standard for many years.

2008 — Python 3.0

A major overhaul to fix language inconsistencies. Python 3 is not backward‑compatible with Python 2 — a deliberate decision to improve the language.

2020 — Python 2 Retired

After 20 years, Python 2 is officially sunset. The community fully transitions to Python 3, which continues to evolve with new features every year.

Today — Python Everywhere

Python is the #1 language for data science, AI, web development, and automation. It's taught in schools, used by Fortune 500 companies, and loved by millions.

@PoeticGlenn says: "Python's philosophy — 'Readability counts' and 'Simple is better than complex' — is why it's the perfect language for beginners. Every line of Python code is designed to be understood by humans first, computers second."

What Can You Build with Python?

Python is a general‑purpose language — it can be used for almost anything. Here are some of the most popular applications of Python in the real world.

Web Development

Build powerful web applications with Django, Flask, and FastAPI. Used by Instagram, Pinterest, and Spotify.

Data Science & AI

Analyse data, build machine learning models, and create AI applications with NumPy, Pandas, and TensorFlow.

Automation

Automate repetitive tasks, scrape websites, and build bots. Python is the #1 choice for scripting and automation.

Game Development

Create games with Pygame and other libraries. Python is used for prototyping and indie game development.

Cybersecurity

Write security tools, penetration testing scripts, and network analysis applications with Python.

IoT & Embedded

Program Raspberry Pi, microcontrollers, and IoT devices. Python runs on everything from small boards to supercomputers.

No matter what field you're interested in, Python has a role to play. It's the Swiss Army knife of programming languages.

Python is the Smartest First Language You Can Learn

Every programmer starts somewhere. Python is the most recommended first language by educators, bootcamps, and universities worldwide. Here's why.

📖 Readable Syntax

Python code reads like plain English. You spend less time decoding syntax and more time learning programming concepts.

🚀 Immediate Results

Python is interpreted — you write code and run it instantly. No compilation step means faster feedback and more learning.

🧩 Beginner‑Friendly

Python was designed for education. It's forgiving, has helpful error messages, and a massive community of learners and mentors.

💼 Career Goldmine

Python skills are in high demand across every industry. Learning Python opens doors to web development, data science, AI, and more.

@PoeticGlenn says: "Learning Python is like learning to drive on an automatic car — you focus on the road (programming concepts) instead of the gearstick (syntax). Once you can drive, you can learn any vehicle."

Why Python Dominates Every Sector of Technology

Python isn't just popular — it's ubiquitous. From Google to NASA, from startups to governments, Python is the language of choice for building the future. Here's why it matters.

Education

Python is the #1 language taught in universities and coding bootcamps. It's the standard for introducing computer science.

Enterprise

Google, Facebook, Amazon, and thousands of other companies rely on Python for critical infrastructure and product development.

Research

Python is the language of science. From physics to biology, researchers use Python to analyse data and model complex systems.

By learning Python, you're learning the language that powers the modern world — and setting yourself up for a lifetime of opportunities.

🔧 Setting Up Your Python Environment

Before you write your first line of code, you need Python installed on your machine. Here's how to get started.

🔧 1.1 Installing Python

Python is free and available for Windows, macOS, and Linux. Follow these steps to get Python on your computer.

Step-by-step guide:

  • Step 1: Go to python.org and download the latest Python 3 version for your operating system.
  • Step 2: Run the installer. On Windows, make sure to check "Add Python to PATH" before clicking Install.
  • Step 3: Verify the installation by opening a terminal (Command Prompt on Windows, Terminal on macOS/Linux) and typing python --version.
  • Step 4: You should see something like Python 3.12.x — this means Python is installed and ready.
  • Step 5: Try running Python interactively by typing python in the terminal. You'll see a >>> prompt where you can type Python code directly.
terminal / python
print("Hello, World!")

Pro Tip

We recommend using VS Code (free) with the Python extension or PyCharm Community Edition (free) for writing Python code. These editors provide syntax highlighting, auto‑completion, and debugging tools that make learning easier.

📦 Variables and Data Types

Variables are named containers for data. Learn how to store and work with different types of data in Python.

📦 2.1 Variables and Basic Types

In Python, you don't need to declare the type of a variable — Python figures it out automatically. This is called dynamic typing.

Step-by-step explanation:

  • Step 1: Assign a value to a variable using the = operator.
  • Step 2: Python infers the type from the value: int for whole numbers, float for decimal numbers, str for text, bool for True/False.
  • Step 3: Use the type() function to check the type of a variable.
  • Step 4: Variables can be reassigned to different types — Python is flexible.
  • Step 5: Variable names are case‑sensitive and should be descriptive.
python
age = 25
print("Age:", age)
print("Type of age:", type(age))

price = 19.99
print("Price:", price)
print("Type of price:", type(price))

name = "Alice"
print("Name:", name)
print("Type of name:", type(name))

is_student = True
print("Is student:", is_student)
print("Type of is_student:", type(is_student))

age = "twenty-five"
print("Age now:", age)
print("Type now:", type(age))
Python's dynamic typing makes code fast to write and easy to read. Unlike languages like C or Java, you don't need to declare types — Python handles it for you.

🔤 Strings — Working with Text

Strings are sequences of characters. Python provides powerful tools for manipulating and formatting text.

🔤 3.1 String Operations and Methods

Strings can be combined, sliced, and transformed using built‑in methods.

Step-by-step explanation:

  • Step 1: Create strings with single quotes ' ' or double quotes " ".
  • Step 2: Concatenate strings with the + operator.
  • Step 3: Access individual characters using indexing (0‑based).
  • Step 4: Use methods like .upper(), .lower(), .strip() to transform strings.
  • Step 5: Use len() to get the length of a string.
python
greeting = "Hello"
name = "World"
message = greeting + " " + name + "!"
print("Message:", message)

word = "Python"
print("First character:", word[0])
print("Last character:", word[-1])
print("Slice (0:3):", word[0:3])

text = "  Hello, World!  "
print("Original:", text)
print("Upper:", text.upper())
print("Lower:", text.lower())
print("Strip:", text.strip())
print("Title:", text.strip().title())
print("Replace:", text.replace("World", "Python"))
print("Length:", len(text))
Strings are immutable — you can't change a character in place. Methods like .upper() return a new string rather than modifying the original.

🔢 Numbers and Arithmetic

Python supports integers, floating‑point numbers, and complex numbers. Learn to perform arithmetic operations.

🔢 4.1 Arithmetic Operations

Python has all the standard arithmetic operators: addition, subtraction, multiplication, division, and more.

Step-by-step explanation:

  • Step 1: Use +, -, *, / for basic arithmetic.
  • Step 2: Use // for floor division (integer result).
  • Step 3: Use % for modulo (remainder).
  • Step 4: Use ** for exponentiation.
  • Step 5: Python follows standard operator precedence (PEMDAS).
python
a = 10
b = 3

print("a + b =", a + b)
print("a - b =", a - b)
print("a * b =", a * b)
print("a / b =", a / b)
print("a // b =", a // b)
print("a % b =", a % b)
print("a ** b =", a ** b)

result = 2 + 3 * 4 ** 2
print("2 + 3 * 4 ** 2 =", result)

result2 = (2 + 3) * (4 ** 2)
print("(2 + 3) * (4 ** 2) =", result2)

x = 5
y = 2.5
print("x + y =", x + y)
print("int(2.9) =", int(2.9))
print("float(5) =", float(5))
Division (/) always returns a float. If you need an integer result, use floor division (//).

📋 Lists — Ordered Collections

Lists are ordered, mutable collections that can hold any type of data. They're one of the most useful data structures in Python.

📋 5.1 Working with Lists

Lists can contain mixed types, support indexing and slicing, and have many useful methods.

Step-by-step explanation:

  • Step 1: Create a list using square brackets [].
  • Step 2: Access elements by index (0‑based).
  • Step 3: Modify elements by assigning to an index.
  • Step 4: Use methods: .append(), .insert(), .remove(), .pop().
  • Step 5: Use len() to get the number of elements.
python
fruits = ["apple", "banana", "orange", "grape"]
print("Fruits:", fruits)

print("First fruit:", fruits[0])
print("Last fruit:", fruits[-1])
print("First two:", fruits[0:2])

fruits[1] = "blueberry"
print("After modification:", fruits)

fruits.append("kiwi")
print("After append:", fruits)
fruits.insert(1, "mango")
print("After insert:", fruits)

fruits.remove("orange")
print("After remove:", fruits)
last = fruits.pop()
print("Popped:", last)
print("After pop:", fruits)

numbers = [3, 1, 4, 1, 5, 9, 2]
numbers.sort()
print("Sorted:", numbers)
numbers.reverse()
print("Reversed:", numbers)
print("Count of 1:", numbers.count(1))
print("Index of 5:", numbers.index(5))
Lists are mutable — you can change, add, and remove elements after creation.

📌 Tuples — Immutable Sequences

Tuples are like lists but immutable — once created, they cannot be changed. Use tuples for data that shouldn't be modified.

📌 6.1 Working with Tuples

Tuples are defined with parentheses () and support indexing and unpacking.

Step-by-step explanation:

  • Step 1: Create a tuple using parentheses ().
  • Step 2: Access elements by index (same as lists).
  • Step 3: Tuple unpacking: assign tuple values to multiple variables.
  • Step 4: Tuples are immutable — you cannot modify them.
  • Step 5: Use tuples to group related data together.
python
coordinates = (10, 20)
rgb = (255, 128, 0)
person = ("Alice", 25, "Engineer")
print("Coordinates:", coordinates)
print("RGB:", rgb)
print("Person:", person)

print("X:", coordinates[0])
print("Y:", coordinates[1])
print("First color:", rgb[0])

x, y = coordinates
print("Unpacked x:", x)
print("Unpacked y:", y)

name, age, job = person
print("Name:", name)
print("Age:", age)
print("Job:", job)

single = (42,)
print("Single element tuple:", single)

def get_stats(numbers):
    return min(numbers), max(numbers), sum(numbers)/len(numbers)

min_val, max_val, avg = get_stats([5, 10, 15, 20])
print("Min:", min_val, "Max:", max_val, "Average:", avg)
Use tuples when you want to guarantee that data won't be accidentally modified. They're also more memory‑efficient than lists.

📖 Dictionaries — Key‑Value Pairs

Dictionaries store data as key‑value pairs. They're like real‑world dictionaries — you look up a word (key) to find its definition (value).

📖 7.1 Working with Dictionaries

Dictionaries are mutable, unordered collections of key‑value pairs. Keys must be unique and immutable (strings, numbers, tuples).

Step-by-step explanation:

  • Step 1: Create a dictionary with curly braces {} and colons :.
  • Step 2: Access values using square bracket notation dict['key'].
  • Step 3: Add or modify key‑value pairs by assignment.
  • Step 4: Use .get() to safely access values (returns None if key doesn't exist).
  • Step 5: Iterate over keys, values, or items using loops.
python
person = {
    "name": "Alice",
    "age": 30,
    "city": "New York",
    "job": "Engineer"
}
print("Person:", person)

print("Name:", person["name"])
print("Age:", person["age"])

print("Country:", person.get("country", "Unknown"))

person["country"] = "USA"
person["age"] = 31
print("Updated:", person)

print("Keys:", person.keys())
print("Values:", person.values())
print("Items:", person.items())

print("\nIterating over items:")
for key, value in person.items():
    print(f"{key}: {value}")

squares = {x: x**2 for x in range(5)}
print("Squares:", squares)

users = {
    "alice": {"age": 30, "city": "NYC"},
    "bob": {"age": 25, "city": "LA"}
}
print("Alice's city:", users["alice"]["city"])
Dictionary keys must be immutable (strings, numbers, tuples). Lists and other dictionaries cannot be used as keys.

🧩 Sets — Unordered Unique Collections

Sets store unique elements in no particular order. They're useful for membership testing and removing duplicates.

🧩 8.1 Working with Sets

Sets are defined with curly braces {} and support mathematical set operations.

Step-by-step explanation:

  • Step 1: Create a set with curly braces {} or set().
  • Step 2: Sets automatically remove duplicates.
  • Step 3: Use .add() and .remove() to modify sets.
  • Step 4: Perform set operations: union, intersection, difference.
  • Step 5: Use sets for fast membership testing.
python
fruits = {"apple", "banana", "orange", "apple", "banana"}
print("Fruits (duplicates removed):", fruits)

numbers = [1, 2, 3, 2, 1, 4, 5]
unique = set(numbers)
print("Unique numbers:", unique)

fruits.add("grape")
print("After add:", fruits)
fruits.remove("banana")
print("After remove:", fruits)

set_a = {1, 2, 3, 4, 5}
set_b = {4, 5, 6, 7, 8}

print("Union:", set_a | set_b)
print("Intersection:", set_a & set_b)
print("Difference (A - B):", set_a - set_b)
print("Symmetric difference:", set_a ^ set_b)

print("Is 3 in set_a?", 3 in set_a)
print("Is 10 in set_a?", 10 in set_a)

squares = {x**2 for x in range(6)}
print("Squares set:", squares)
Membership testing in sets is O(1) (constant time) — much faster than lists for large collections.

🔀 Conditionals — Making Decisions

Conditionals allow your code to make decisions based on conditions. Use if, elif, and else.

🔀 9.1 If, Elif, Else Statements

Python uses indentation (whitespace) to define code blocks. This makes the code clean and readable.

Step-by-step explanation:

  • Step 1: Use if followed by a condition and a colon :.
  • Step 2: Indent the code block that runs if the condition is True.
  • Step 3: Use elif (else if) for additional conditions.
  • Step 4: Use else for the fallback when all conditions are False.
  • Step 5: Conditions use comparison operators: ==, !=, >, <, >=, <=.
python
age = 20
if age >= 18:
    print("You are an adult")
else:
    print("You are a minor")

score = 85
if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
elif score >= 60:
    grade = "D"
else:
    grade = "F"
print("Grade:", grade)

temperature = 25
is_sunny = True
if temperature > 30:
    print("It's hot")
elif temperature > 20 and is_sunny:
    print("It's warm and sunny")
elif temperature > 20:
    print("It's warm")
else:
    print("It's cool")

x = 10
if x > 0:
    if x % 2 == 0:
        print("x is positive and even")
    else:
        print("x is positive and odd")
else:
    print("x is not positive")

age = 16
status = "Adult" if age >= 18 else "Minor"
print("Status:", status)
Python uses indentation to define blocks — not curly braces or keywords like end. This makes Python code clean and forces consistent formatting.

🔄 Loops — Repeating Actions

Loops allow you to execute a block of code multiple times. Python has for loops and while loops.

🔄 10.1 For and While Loops

for loops iterate over sequences (lists, strings, dictionaries). while loops run while a condition is True.

Step-by-step explanation:

  • Step 1: Use for to iterate over a sequence.
  • Step 2: Use range() to generate numeric sequences.
  • Step 3: Use while when the number of iterations is not known in advance.
  • Step 4: Use break to exit a loop early.
  • Step 5: Use continue to skip the rest of the current iteration.
python
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
    print("I like", fruit)

print("\nCounting with range:")
for i in range(5):
    print(i, end=" ")
print()

print("\nWith index:")
for i, fruit in enumerate(fruits):
    print(f"{i}: {fruit}")

print("\nWhile loop:")
count = 0
while count < 5:
    print(count, end=" ")
    count += 1
print()

print("\nBreak and continue:")
for i in range(10):
    if i == 3:
        continue
    if i == 7:
        break
    print(i, end=" ")
print()

person = {"name": "Alice", "age": 30, "city": "NYC"}
print("\nDictionary loop:")
for key, value in person.items():
    print(f"{key}: {value}")

print("\nNested loops:")
for i in range(3):
    for j in range(2):
        print(f"({i},{j})", end=" ")
    print()
range(n) generates numbers from 0 to n-1. Use range(start, stop, step) for more control.

⚙️ Functions — Reusable Code Blocks

Functions allow you to encapsulate reusable code. They take inputs (parameters) and can return outputs.

⚙️ 11.1 Defining and Using Functions

Functions are defined with the def keyword. They can have parameters and return values.

Step-by-step explanation:

  • Step 1: Define a function with def function_name(parameters):.
  • Step 2: Indent the function body.
  • Step 3: Use return to send a value back to the caller.
  • Step 4: Call the function by name with arguments.
  • Step 5: Functions can have default parameter values.
python
def greet(name):
    return f"Hello, {name}!"

print(greet("Alice"))
print(greet("Bob"))

def add(a, b):
    return a + b

result = add(5, 3)
print("5 + 3 =", result)

def power(base, exponent=2):
    return base ** exponent

print("3^2 =", power(3))
print("2^3 =", power(2, 3))

def sum_all(*numbers):
    return sum(numbers)

print("Sum of 1, 2, 3:", sum_all(1, 2, 3))
print("Sum of 1, 2, 3, 4, 5:", sum_all(1, 2, 3, 4, 5))

def describe_person(name, age, city="Unknown"):
    return f"{name} is {age} years old and lives in {city}"

print(describe_person("Alice", 30, "NYC"))
print(describe_person("Bob", 25))

square = lambda x: x ** 2
print("Lambda square of 5:", square(5))

def apply(func, value):
    return func(value)

print("apply(square, 4):", apply(square, 4))
Functions help you write DRY (Don't Repeat Yourself) code. They make your programs more organized, testable, and reusable.

⚠️ Error Handling — Try / Except

Errors happen. Learn to handle them gracefully so your program doesn't crash unexpectedly.

⚠️ 12.1 Exception Handling

Use try and except to catch and handle exceptions (errors) in your code.

Step-by-step explanation:

  • Step 1: Wrap code that might raise an error in a try block.
  • Step 2: Catch specific exceptions with except.
  • Step 3: Use else for code that runs if no exception occurs.
  • Step 4: Use finally for code that runs regardless of whether an exception occurred.
  • Step 5: Raise your own exceptions with raise.
python
try:
    number = int(input("Enter a number: "))
    print("You entered:", number)
except ValueError:
    print("That's not a valid number!")

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")
except TypeError:
    print("Invalid type for division!")
except Exception as e:
    print("Something went wrong:", e)

try:
    file = open("example.txt", "r")
    content = file.read()
except FileNotFoundError:
    print("File not found!")
else:
    print("File content length:", len(content))
finally:
    try:
        file.close()
    except:
        pass
    print("Cleanup complete.")

def validate_age(age):
    if age < 0:
        raise ValueError("Age cannot be negative")
    elif age > 150:
        raise ValueError("Age cannot be greater than 150")
    return f"Valid age: {age}"

try:
    print(validate_age(25))
    print(validate_age(-5))
except ValueError as e:
    print("Error:", e)
Always catch specific exceptions when possible. Catching Exception can hide bugs. Use finally for resource cleanup.

🧩 Modules and Imports

Modules allow you to organize code into separate files and reuse code from Python's standard library or third‑party packages.

🧩 13.1 Importing and Using Modules

Python has a rich standard library. You can also install third‑party modules using pip.

Step-by-step explanation:

  • Step 1: Import a module with import module_name.
  • Step 2: Access functions and variables using module_name.function().
  • Step 3: Import specific items with from module_name import item.
  • Step 4: Use an alias with import module_name as alias.
  • Step 5: Install third‑party modules with pip install module_name.
python
import math
print("math.pi =", math.pi)
print("math.sqrt(16) =", math.sqrt(16))
print("math.factorial(5) =", math.factorial(5))

from math import sin, cos, radians
angle = radians(45)
print("sin(45°) =", sin(angle))
print("cos(45°) =", cos(angle))

import random as rnd
print("Random integer (1-10):", rnd.randint(1, 10))
print("Random choice:", rnd.choice(["apple", "banana", "orange"]))

from datetime import datetime
now = datetime.now()
print("Current date and time:", now)
print("Year:", now.year)
print("Month:", now.month)

try:
    import pandas as pd
    print("Pandas is installed! Version:", pd.__version__)
except ImportError:
    print("Pandas is not installed. Run: pip install pandas")
Python's standard library is huge — it includes modules for math, random, datetime, file I/O, networking, and much more. Explore it to find tools that make your life easier.

📁 File I/O — Reading and Writing Files

Learn to read from and write to files on your computer. This is essential for working with data and saving program results.

📁 14.1 Reading and Writing Files

Use the open() function to work with files. Always close files or use the with context manager.

Step-by-step explanation:

  • Step 1: Open a file with open(filename, mode).
  • Step 2: Modes: 'r' (read), 'w' (write), 'a' (append).
  • Step 3: Read content with .read(), .readline(), or .readlines().
  • Step 4: Write content with .write().
  • Step 5: Always close files with .close() or use with.
python
with open("example.txt", "w") as file:
    file.write("Hello, World!\n")
    file.write("This is line 2.\n")
    file.write("This is line 3.\n")
print("File written successfully.")

with open("example.txt", "r") as file:
    content = file.read()
print("File content:")
print(content)

print("Reading line by line:")
with open("example.txt", "r") as file:
    for line in file:
        print(f"Line: {line.strip()}")

with open("example.txt", "r") as file:
    lines = file.readlines()
print("Lines list:", lines)

with open("example.txt", "a") as file:
    file.write("This line was appended.\n")
print("Appended successfully.")

fruits = ["apple\n", "banana\n", "orange\n"]
with open("fruits.txt", "w") as file:
    file.writelines(fruits)

try:
    with open("nonexistent.txt", "r") as file:
        content = file.read()
except FileNotFoundError:
    print("File not found!")

data = [
    ["Alice", "30", "Engineer"],
    ["Bob", "25", "Designer"],
    ["Charlie", "35", "Manager"]
]
with open("people.csv", "w") as file:
    for row in data:
        file.write(",".join(row) + "\n")
print("CSV written.")
The with statement automatically closes the file when you're done — even if an error occurs. Always use it when working with files.

🏗️ Classes and Object‑Oriented Programming

Classes allow you to create your own data types with properties and methods. OOP helps you structure large programs.

🏗️ 15.1 Defining and Using Classes

Classes are blueprints for objects. They encapsulate data (attributes) and behavior (methods).

Step-by-step explanation:

  • Step 1: Define a class with class ClassName:.
  • Step 2: Use __init__ as the constructor to set up new objects.
  • Step 3: Use self to refer to the current instance.
  • Step 4: Define methods (functions inside classes) that operate on the object.
  • Step 5: Create objects (instances) from the class.
python
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def greet(self):
        return f"Hello, my name is {self.name} and I am {self.age} years old."

    def birthday(self):
        self.age += 1
        print(f"{self.name} is now {self.age} years old!")

alice = Person("Alice", 30)
bob = Person("Bob", 25)

print(alice.greet())
print(bob.greet())

alice.birthday()
bob.birthday()

class Student:
    school = "Python University"

    def __init__(self, name, grade):
        self.name = name
        self.grade = grade

    def display(self):
        return f"{self.name} (Grade: {self.grade}) at {Student.school}"

s1 = Student("Alice", "A")
s2 = Student("Bob", "B")
print(s1.display())
print(s2.display())

class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        return "Some sound"

class Dog(Animal):
    def speak(self):
        return "Woof!"

class Cat(Animal):
    def speak(self):
        return "Meow!"

dog = Dog("Rex")
cat = Cat("Whiskers")
print(f"{dog.name} says: {dog.speak()}")
print(f"{cat.name} says: {cat.speak()}")

class Rectangle:
    def __init__(self, width, height):
        self._width = width
        self._height = height

    @property
    def area(self):
        return self._width * self._height

    @property
    def perimeter(self):
        return 2 * (self._width + self._height)

rect = Rectangle(4, 5)
print(f"Area: {rect.area}")
print(f"Perimeter: {rect.perimeter}")
Object‑Oriented Programming (OOP) is a powerful paradigm. It helps you model real‑world entities and build complex, maintainable software.

❓ Frequently Asked Questions — Python for Beginners

Common questions from new Python learners, answered.

Do I need any prior programming experience?

+

No! This curriculum is designed for absolute beginners. We start with the very basics — what a variable is — and build up from there.

How long does it take to learn Python?

+

You can learn the basics in a few weeks of consistent practice. This curriculum covers all the essential topics. Mastery comes with time and building projects.

What's the difference between Python 2 and Python 3?

+

Python 3 is the modern version. Python 2 was retired in 2020. Always use Python 3 for new projects.

Should I use an IDE or a text editor?

+

For beginners, an IDE like PyCharm Community Edition or VS Code with the Python extension is recommended. They provide helpful features like auto‑completion and error highlighting.

How do I install third‑party libraries?

+

Use pip — the Python package installer. For example: pip install pandas. Make sure you're in your terminal/command prompt.

What should I build after learning the basics?

+

Start with small projects: a calculator, a to‑do list app, a web scraper, or a simple game. Then move to larger projects like a blog or a data analysis project.

Is Python good for getting a job?

+

Absolutely! Python skills are in high demand across web development, data science, AI, automation, and more. It's one of the best languages for career growth.

💛 You've Completed Your Python Foundation!

Congratulations! You've journeyed from absolute beginner to a confident Python programmer. You've learned variables, data types, strings, numbers, lists, tuples, dictionaries, sets, conditionals, loops, functions, error handling, modules, file I/O, and object‑oriented programming — the entire foundation of Python.

This curriculum, crafted by @PoeticGlenn, is designed to give you the essential knowledge you need to start building real‑world projects. The skills you've practiced here are the same ones used by professional developers every day.

18 lessons 30+ code examples 1,200+ learners

"Everyone should learn to program a computer, because it teaches you how to think." — Steve Jobs Crafted with care by Glenn Junsay Pansensoy (@PoeticGlenn)

— Sponsored —