DOCODIVE
Beginner Free Learning Path

Python Beginner Guide

Build a strong Python foundation from zero. Learn core syntax, data structures, functions, files, exceptions, modules, OOP, development tools, and build real-world projects.

3–5 weeks 20 lessons 3 projects 1 capstone No experience required
Start Learning
01

Python & Your First Program

15 min
What you'll learn
  • Explain what Python is
  • Run your first script
  • Understand comments and indentation

Python is a readable, beginner-friendly programming language used for web development, data analysis, automation, AI, and many other areas. In this lesson, you will create your first .py file, run it, and learn why indentation matters in Python.

Python
# My first program
print("Hello Python")
print("I am learning on DocoDive")
Output
python
Hello Python I am learning on DocoDive
💡 Tip: Python is case-sensitive: Print() and print() are different names.
Try it yourself

Print your name, city, and age on three separate lines.

Use print() three times, or use \n to separate the lines.
print("Sufyan")
print("Karachi")
print(19)
02

Variables & Basic Data Types

15 min
What you'll learn
  • Create variables
  • Use int, float, str, bool, None
  • Check types with type()

A variable is a named container that stores a value. In Python you assign with '='. Common data types are int (whole numbers), float (decimals), str (text), bool (True/False), and None (empty).

Python
name = "Sufyan"
age = 19
height = 5.9
is_student = True
nothing = None
print(name, type(name))
print(age, type(age))
Output
python
Sufyan <class 'str'> 19 <class 'int'>
⚠️ Common Mistake: A variable name cannot start with a number. 2name is invalid, but name2 is fine.
Try it yourself

Create variables for your city, age, and height, then print them all.

Assign three variables, then print(city, age, height).
city = "Karachi"
age = 19
height = 5.9
print(city, age, height)
03

Operators & Expressions

20 min
What you'll learn
  • Use arithmetic operators
  • Compare values
  • Combine with logical operators

Operators work on values: arithmetic (+, -, *, /, //, %), comparison (==, !=, >, <, >=, <=), and logical (and, or, not). These are the foundation for calculations and conditions.

Python
price = 500
quantity = 3
total = price * quantity
print(total)
print(total > 1000)
print(quantity >= 3 and price > 100)
Output
python
1500 True True
🔎 Important: The = sign assigns a value, while == compares two values. Do not mix them.
Try it yourself

Write a program that prints 10 % 3 and 10 // 3.

% gives the remainder and // gives floor division.
print(10 % 3)
print(10 // 3)
04

Strings

20 min
What you'll learn
  • Index and slice strings
  • Use string methods
  • Format with f-strings

Strings are sequences of characters. Indexing starts at 0, and slicing returns a range. Methods like lower(), upper(), strip(), replace(), split(), and join() transform text. f-strings are the modern way to format strings.

Python
text = "  Hello DocoDive  "
clean = text.strip().upper()
print(clean)
name = "Sufyan"
print(f"Welcome, {name}!")
Output
python
HELLO DOCODIVE Welcome, Sufyan!
✓ Best Practice: Use f-strings for clear, readable string formatting.
Try it yourself

Print your name in uppercase and report its length.

Use name.upper() and len(name).
name = "Sufyan"
print(name.upper())
print(len(name))
05

Input & Type Conversion

15 min
What you'll learn
  • Get user input
  • Convert types with int() and float()
  • Avoid conversion errors

input() always returns a string, even when the user types a number. To do math you must convert with int() or float(). A wrong conversion raises ValueError, so basic validation matters.

Python
age_text = input("Age: ")
age = int(age_text)
print("Next year:", age + 1)
Output
python
Age: 19 Next year: 20
⚠️ Common Mistake: Never do math on input() without converting first — "19" + 1 will crash.
Try it yourself

Ask the user for two numbers and print their sum.

Convert both with int(input(...)), then add them.
a = int(input("First: "))
b = int(input("Second: "))
print(a + b)
06

Conditions

20 min
What you'll learn
  • Use if / elif / else
  • Nest conditions
  • Write conditional expressions

Conditions let a program make decisions. if checks the first condition, elif checks more, and else is the fallback. Indentation tells Python which block each line belongs to.

Python
score = 85
if score >= 90:
    print("A")
elif score >= 75:
    print("B")
else:
    print("C")
Output
python
B
💡 Tip: Lines after a colon (:) must be indented with 4 spaces.
Try it yourself

Print 'Adult' if age is 18 or above, otherwise print 'Minor'.

Use if age >= 18 and an else block.
age = 19
print("Adult" if age >= 18 else "Minor")
07

Loops

20 min
What you'll learn
  • Use for and while
  • Loop with range()
  • Use break, continue, pass

Loops repeat code. A for loop iterates over a sequence, and a while loop runs until its condition is false. range() generates numbers. break exits a loop, continue skips to the next iteration.

Python
for i in range(3):
    print(i)

n = 0
while n < 3:
    n += 1
    if n == 2:
        continue
    print(n)
Output
python
0 1 2 1 3
🔎 Important: If a while condition never becomes false, you get an infinite loop.
Try it yourself

Print only the odd numbers from 1 to 10.

Use range(1, 11, 2).
for n in range(1, 11, 2):
    print(n)
08

Lists

25 min
What you'll learn
  • Create and mutate lists
  • Slice lists
  • Use append, insert, remove, sort

A list is an ordered, mutable collection. Indexing starts at 0, and negative indices count from the end. append() adds an item, pop() removes one, and sort() arranges the list.

Python
fruits = ["mango", "apple", "banana"]
fruits.append("grape")
fruits.sort()
print(fruits)
print(fruits[0], fruits[-1])
Output
python
['apple', 'banana', 'grape', 'mango'] apple mango
💡 Tip: Start with simple list operations first. List comprehensions will be introduced later.
Try it yourself

Create a list of even numbers from 3 to 15.

Loop through the range and append only even numbers.
evens = []
for n in range(3, 16):
    if n % 2 == 0:
        evens.append(n)
print(evens)
09

Tuples, Sets & Dictionaries

25 min
What you'll learn
  • Use tuples for fixed data
  • Use sets for unique values
  • Store key-value pairs in dicts

A tuple is an immutable ordered collection, a set stores unique unordered values, and a dictionary maps keys to values. Fixed data -> tuple, unique items -> set, mapping -> dict.

Python
point = (10, 20)
skills = {"Python", "HTML", "CSS"}
student = {"name": "Sufyan", "age": 19}
print(point[0])
print(skills)
print(student["name"])
Output
python
10 {'Python', 'HTML', 'CSS'} Sufyan
💡 Tip: For missing dict keys, use .get("key") so the program does not crash.
Try it yourself

Create a dict with 'name' and 'score', then print the score.

Use student['score'].
s = {"name": "Sufyan", "score": 95}
print(s["score"])
10

Functions

25 min
What you'll learn
  • Define functions with def
  • Use parameters and return
  • Use default and keyword arguments

A function is a reusable block defined with def. Parameters are inputs and return sends a value back. Default arguments preset values, and keyword arguments make calls clearer.

Python
def greet(name, greeting="Hello"):
    return f"{greeting}, {name}!"

print(greet("Sufyan"))
print(greet("Sufyan", greeting="Hi"))
Output
python
Hello, Sufyan! Hi, Sufyan!
🔎 Important: Without a return statement, a function returns None.
Try it yourself

Write an add(a, b) function that returns the sum.

Define it with def and return a + b.
def add(a, b):
    return a + b
print(add(3, 7))
11

Function Power-Up

25 min
What you'll learn
  • Use *args and **kwargs
  • Write lambda functions
  • Use map, filter, zip, enumerate

*args accepts arbitrary positional arguments, and **kwargs accepts arbitrary keyword arguments. A lambda is a one-line anonymous function. map and filter transform collections, zip iterates in parallel, and enumerate adds an index.

Python
nums = [1, 2, 3, 4]
squared = list(map(lambda x: x**2, nums))
evens = list(filter(lambda x: x % 2 == 0, nums))
print(squared)
print(evens)
Output
python
[1, 4, 9, 16] [2, 4]
✓ Best Practice: Use the clearest approach for the reader. For simple transformations, a list comprehension is often easier to read than map() with a lambda.
Try it yourself

Use zip to pair two lists and print the result.

Try list(zip(names, ages)).
names = ["A", "B"]
ages = [19, 20]
print(list(zip(names, ages)))
12

List, Set & Dictionary Comprehensions

20 min
What you'll learn
  • Write list comprehensions
  • Write dict comprehensions
  • Use nested comprehensions

Comprehensions build collections in one clean line. A list comprehension is [expr for item in iterable if condition], and a dict comprehension is {key: value for ...}.

Python
nums = [1, 2, 3, 4]
squares = [n**2 for n in nums]
even_squares = {n: n**2 for n in nums if n % 2 == 0}
print(squares)
print(even_squares)
Output
python
[1, 4, 9, 16] {2: 4, 4: 16}
💡 Tip: If a comprehension gets too long, use a normal loop for readability.
Try it yourself

Build a dict mapping each name to its length.

Use {name: len(name) for name in names}.
names = ["Ali", "Sufyan"]
print({n: len(n) for n in names})
13

Files & Directories

25 min
What you'll learn
  • Read and write text files
  • Use the with statement
  • Work with JSON and pathlib

Files are central to real programs. with open() automatically closes the file. Modes: r read, w write, a append. JSON stores structured data, and pathlib makes paths clean and safe.

Python
from pathlib import Path
import json

data = {"name": "Sufyan", "age": 19}
Path("data.json").write_text(json.dumps(data))
print(Path("data.json").read_text())
Output
python
{"name": "Sufyan", "age": 19}
✓ Best Practice: Use with open(...) so you never forget to close a file.
Try it yourself

Create a notes.txt file, write your name in it, then read it back.

Open with 'w' to write and 'r' to read.
with open('notes.txt', 'w') as f:
    f.write('Sufyan')
with open('notes.txt') as f:
    print(f.read())
14

Errors & Exception Handling

20 min
What you'll learn
  • Understand syntax vs runtime errors
  • Use try/except/else/finally
  • Raise exceptions

Syntax errors happen while writing code; runtime errors happen while it runs. try runs risky code, except catches errors, else runs on success, and finally always runs. raise lets you fail deliberately.

Python
try:
    num = int(input("Number: "))
    print(10 / num)
except ValueError:
    print("Invalid number")
except ZeroDivisionError:
    print("Cannot divide by zero")
else:
    print("Success")
Output
python
Number: 0 Cannot divide by zero
⚠️ Common Mistake: A bare except: hides every error. Catch specific exceptions instead.
Try it yourself

Write a safe division function that handles zero.

Use try/except ZeroDivisionError.
def safe_div(a, b):
    try:
        return a / b
    except ZeroDivisionError:
        return None
print(safe_div(10, 0))
15

Modules & Packages

20 min
What you'll learn
  • Import built-in modules
  • Create custom modules
  • Use if __name__ == '__main__'

A module is a .py file you can import. A package is a folder of modules. import math brings in the whole module; from math import sqrt brings one name. The __name__ == '__main__' guard runs code only on direct execution.

Python
import math
print(math.sqrt(16))

if __name__ == "__main__":
    print("Direct run")
Output
python
4.0 Direct run
💡 Tip: Add an if __name__ == '__main__' guard to every reusable file.
Try it yourself

Use math to print the square root of 25 and pi.

Use math.sqrt(25) and math.pi.
import math
print(math.sqrt(25))
print(math.pi)
16

Useful Standard Library

25 min
What you'll learn
  • Use math, random, datetime
  • Use pathlib and os
  • Use json, re and collections

Python's standard library is huge. Beginners should know representative modules: math for calculations, random for randomness, datetime for dates, pathlib for files, json for data, and collections for useful containers.

Python
import random
import datetime
from collections import Counter

print(random.randint(1, 10))
print(datetime.date.today())
print(Counter(["a", "b", "a", "c"]))
Output
python
Example output (your random number will vary): 7 2026-08-23 Counter({'a': 2, 'b': 1, 'c': 1})
✓ Best Practice: Learn the standard library first — many problems need no external package.
Try it yourself

Generate a random 10-character token using letters and digits.

Combine string.ascii_letters + string.digits with random.choices.
import random
import string
chars = string.ascii_letters + string.digits
print(''.join(random.choices(chars, k=10)))
17

Object-Oriented Python Basics

25 min
What you'll learn
  • Define classes and objects
  • Use attributes and methods
  • Understand __init__ and self

OOP organizes code into objects. A class is a blueprint and an object is an instance of it. __init__ is the constructor that initializes the object. self refers to the instance, and methods are functions inside the class.

Python
class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def greet(self):
        return f"Hi, I am {self.name}"

s = Student("Sufyan", 19)
print(s.greet())
Output
python
Hi, I am Sufyan
🔎 Important: self is the first parameter of every method — do not forget it.
Try it yourself

Create a Car class with brand and speed, and a method that prints them.

Set self.brand and self.speed inside __init__.
class Car:
    def __init__(self, brand, speed):
        self.brand = brand
        self.speed = speed
    def show(self):
        print(self.brand, self.speed)
Car("Toyota", 120).show()
18

Debugging & Writing Better Python

20 min
What you'll learn
  • Read tracebacks
  • Debug with print and pdb
  • Follow PEP 8 basics

Errors are inevitable — learn to read a traceback. print debugging is simple and effective; pdb is the interactive debugger. For clean code, use meaningful names, small functions, and comments only when needed.

Python
def divide(a, b):
    breakpoint()  # pauses execution here
    return a / b

print(divide(10, 2))
Output
python
Execution pauses at breakpoint(). Type 'c' to continue debugging.
💡 Tip: Read a traceback from bottom to top — the last line is the actual error.
Try it yourself

Write a function that returns None and prints a clear message for invalid input.

Use try/except to handle ValueError.
def safe_int(value):
    try:
        return int(value)
    except ValueError:
        print(f"'{value}' is not a number")
        return None
safe_int("abc")
19

Virtual Environments, pip & Project Structure

25 min
What you'll learn
  • Create virtual environments
  • Install packages with pip
  • Use requirements.txt

Real projects use isolated environments. python -m venv creates one, python -m pip installs packages, and requirements.txt freezes dependencies. Project folders and .gitignore keep things organized.

Python
# Create a virtual environment
python -m venv .venv

# Activate (Windows PowerShell)
.venv\Scripts\Activate.ps1

# Activate (macOS / Linux)
source .venv/bin/activate

# Install a package
python -m pip install requests

# Save dependencies
python -m pip freeze > requirements.txt
Output
python
Virtual environment ready. Package installed and requirements.txt saved.
✓ Best Practice: Never install packages into the global Python — always use a virtual environment.
Try it yourself

Write the command that creates a virtual environment named .venv.

It starts with python -m venv.
python -m venv .venv
20

Capstone: Student Management System

45 min
What you'll learn
  • Combine all beginner concepts
  • Build a full CLI project
  • Use files, JSON, functions and OOP

This final project combines variables, loops, conditions, functions, lists, dictionaries, files, JSON, exceptions, and OOP. You will build a CLI system that can add, view, search, update, delete, and save students to JSON.

Starter Code
import json
from pathlib import Path

class StudentManager:
    def __init__(self, path="students.json"):
        self.path = Path(path)
        self.students = json.loads(self.path.read_text()) if self.path.exists() else []

    def add(self, name, age):
        self.students.append({"name": name, "age": age})
        self.save()

    def save(self):
        self.path.write_text(json.dumps(self.students, indent=2))

sm = StudentManager()
sm.add("Sufyan", 19)
print(sm.students)
Output
python
[{'name': 'Sufyan', 'age': 19}]
🔎 Important: Write small functions and put each feature in its own function — debugging becomes much easier.
Try it yourself

Add view() and delete(name) methods to StudentManager.

view() prints all students; delete() removes by name and saves.
def view(self):
    for s in self.students:
        print(s)
def delete(self, name):
    self.students = [s for s in self.students if s["name"] != name]
    self.save()

Beginner Projects

Apply everything you've learned. Click each project to open its full guide.

About this project

The computer secretly picks a number from a range you choose. You get 7 attempts to find it. After each guess, the program tells you whether to go higher or lower.

What you'll practice
random.randint() int(input()) while loop if / else variables
Step-by-step: How it works
  1. The program asks for a starting and ending number.
  2. random.randint(start, end) picks a secret number inside that range.
  3. The loop runs while you still have attempts left.
  4. Each turn you type a guess, and used_guesses increases by 1.
  5. The program says "too low" or "too high" and shows remaining attempts.
  6. If you guess correctly, the loop breaks and you win.
  7. The else after while runs only if you run out of attempts — a clean Python trick.
Python
import random

print("Number Guessing Game")
print("I will pick a secret number inside your chosen range.\n")

start = int(input("Enter the starting number: "))
end = int(input("Enter the ending number: "))

secret = random.randint(start, end)

max_guesses = 7
used_guesses = 0

print(f"\nGuess the secret number between {start} and {end}.")
print(f"You have {max_guesses} attempts.\n")

while used_guesses < max_guesses:
    used_guesses += 1
    guess = int(input(f"Attempt {used_guesses}: "))

    if guess == secret:
        print(f"\nCorrect! The secret number is {secret}.")
        print(f"You found it in {used_guesses} attempt(s).")
        break

    remaining = max_guesses - used_guesses
    if guess < secret:
        print(f"Too low. {remaining} attempt(s) left.\n")
    else:
        print(f"Too high. {remaining} attempt(s) left.\n")

else:
    print(f"\nOut of attempts! The secret number was {secret}.")
Sample Run
python guessing_game.py
Enter the starting number: 1 Enter the ending number: 100 Guess the secret number between 1 and 100. You have 7 attempts. Attempt 1: 50 Too high. 6 attempt(s) left. Attempt 2: 25 Too low. 5 attempt(s) left. Attempt 3: 37 Correct! The secret number is 37. You found it in 3 attempt(s).

About this project

The computer picks a secret word from a list. You guess one letter at a time. Correct letters are revealed; wrong guesses cost a life. Win by revealing the whole word before lives run out.

What you'll practice
random.choice() lists enumerate() while loop input validation
Step-by-step: How it works
  1. word_bank holds a list of possible words.
  2. random.choice(word_bank) selects the secret word.
  3. revealed is a list of underscores — one per letter.
  4. The loop runs while lives remain and the word is still hidden.
  5. The player enters one letter — the program validates it.
  6. If the letter is in the word, every matching position is revealed.
  7. If not, lives decrease by 1.
  8. Game ends when the word is fully revealed (win) or lives hit 0 (loss).
Python
import random

print("Word Guessing Game")
player_name = input("What is your name? ")
print(f"Good luck, {player_name}!\n")

word_bank = [
    "planet", "garden", "rocket", "forest",
    "orange", "silver", "bridge", "candle",
    "winter", "summer", "tiger", "eagle"
]

secret_word = random.choice(word_bank)
revealed = ["_"] * len(secret_word)
lives = 8

print("Guess the secret word one letter at a time.\n")

while lives > 0 and "_" in revealed:
    print("Word: " + " ".join(revealed))
    print(f"Lives left: {lives}")

    letter = input("Guess a letter: ").strip().lower()

    if len(letter) != 1 or not letter.isalpha():
        print("Please enter a single letter.\n")
        continue

    if letter in revealed:
        print("You already found that letter.\n")
        continue

    if letter in secret_word:
        for index, char in enumerate(secret_word):
            if char == letter:
                revealed[index] = letter
        print("Correct!\n")
    else:
        lives -= 1
        print(f"Wrong. {lives} live(s) left.\n")

if "_" not in revealed:
    print(f"You won, {player_name}!")
    print(f"The word was: {secret_word}")
else:
    print(f"You lost, {player_name}.")
    print(f"The word was: {secret_word}")
Sample Run
python word_guessing.py
Word Guessing Game What is your name? Sufyan Good luck, Sufyan! Guess the secret word one letter at a time. Word: _ _ _ _ _ _ Lives left: 8 Guess a letter: p Correct! Word: p _ _ _ _ _ Lives left: 8 Guess a letter: y Correct! Word: p y _ _ _ _ Lives left: 8 Guess a letter: t Correct! Word: p y t _ _ _ Lives left: 8 Guess a letter: h Correct! Word: p y t h _ _ Lives left: 8 Guess a letter: o Correct! Word: p y t h o _ Lives left: 8 Guess a letter: n Correct! You won, Sufyan! The word was: python

About this project

Crack a secret 4-digit code. After each guess, the program tells you how many digits are in the correct position — but not which ones — so you solve it by logic.

What you'll practice
random.randint() str() while True input validation sum()
Step-by-step: How it works
  1. random.randint(1000, 9999) creates the secret code, then str() turns it into text.
  2. The player enters a 4-digit guess.
  3. Validation rejects anything that isn't exactly 4 digits.
  4. The program compares each position: guess[i] vs secret_code[i].
  5. A counter counts how many positions match.
  6. The player sees the count but not which digits were correct — that's the puzzle.
  7. Play repeats until the guess matches the secret code exactly.
Python
import random

print("Mastermind 4-Digit")
print("Crack the secret 4-digit code.\n")

secret_code = str(random.randint(1000, 9999))
tries = 0

while True:
    guess = input("Enter a 4-digit guess: ").strip()

    if not guess.isdigit() or len(guess) != 4:
        print("Enter exactly 4 digits.\n")
        continue

    tries += 1

    if guess == secret_code:
        print(f"\nMastermind! You cracked the code in {tries} tries.")
        break

    correct_spots = sum(1 for i in range(4) if guess[i] == secret_code[i])

    print(f"Digits in the correct position: {correct_spots}")
    print(f"Attempts so far: {tries}\n")
Sample Run
python mastermind.py
Mastermind 4-Digit Crack the secret 4-digit code. Enter a 4-digit guess: 5678 Digits in the correct position: 1 Attempts so far: 1 Enter a 4-digit guess: 1234 Digits in the correct position: 0 Attempts so far: 2 Enter a 4-digit guess: 9876 Mastermind! You cracked the code in 3 tries.
You've completed all 20 lessons. Ready to continue?

Continue to Python Intermediate to level up your skills.

📱 Scan this QR code with your phone camera to instantly open this page.

Works on iOS, Android, and any modern device. No app installation required.

Account Verified!

Your email has been verified successfully.