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.
Start LearningPython & Your First Program
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.
# My first program
print("Hello Python")
print("I am learning on DocoDive")
Try it yourself
Print your name, city, and age on three separate lines.
print("Sufyan")
print("Karachi")
print(19)Variables & Basic Data Types
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).
name = "Sufyan" age = 19 height = 5.9 is_student = True nothing = None print(name, type(name)) print(age, type(age))
Try it yourself
Create variables for your city, age, and height, then print them all.
city = "Karachi" age = 19 height = 5.9 print(city, age, height)
Operators & Expressions
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.
price = 500 quantity = 3 total = price * quantity print(total) print(total > 1000) print(quantity >= 3 and price > 100)
Try it yourself
Write a program that prints 10 % 3 and 10 // 3.
print(10 % 3) print(10 // 3)
Strings
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.
text = " Hello DocoDive "
clean = text.strip().upper()
print(clean)
name = "Sufyan"
print(f"Welcome, {name}!")
Try it yourself
Print your name in uppercase and report its length.
name = "Sufyan" print(name.upper()) print(len(name))
Input & Type Conversion
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.
age_text = input("Age: ")
age = int(age_text)
print("Next year:", age + 1)
Try it yourself
Ask the user for two numbers and print their sum.
a = int(input("First: "))
b = int(input("Second: "))
print(a + b)Conditions
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.
score = 85
if score >= 90:
print("A")
elif score >= 75:
print("B")
else:
print("C")
Try it yourself
Print 'Adult' if age is 18 or above, otherwise print 'Minor'.
age = 19
print("Adult" if age >= 18 else "Minor")Loops
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.
for i in range(3):
print(i)
n = 0
while n < 3:
n += 1
if n == 2:
continue
print(n)
Try it yourself
Print only the odd numbers from 1 to 10.
for n in range(1, 11, 2):
print(n)Lists
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.
fruits = ["mango", "apple", "banana"]
fruits.append("grape")
fruits.sort()
print(fruits)
print(fruits[0], fruits[-1])
Try it yourself
Create a list of even numbers from 3 to 15.
evens = []
for n in range(3, 16):
if n % 2 == 0:
evens.append(n)
print(evens)Tuples, Sets & Dictionaries
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.
point = (10, 20)
skills = {"Python", "HTML", "CSS"}
student = {"name": "Sufyan", "age": 19}
print(point[0])
print(skills)
print(student["name"])
Try it yourself
Create a dict with 'name' and 'score', then print the score.
s = {"name": "Sufyan", "score": 95}
print(s["score"])Functions
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.
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
print(greet("Sufyan"))
print(greet("Sufyan", greeting="Hi"))
Try it yourself
Write an add(a, b) function that returns the sum.
def add(a, b):
return a + b
print(add(3, 7))Function Power-Up
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.
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)
Try it yourself
Use zip to pair two lists and print the result.
names = ["A", "B"] ages = [19, 20] print(list(zip(names, ages)))
List, Set & Dictionary Comprehensions
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 ...}.
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)
Try it yourself
Build a dict mapping each name to its length.
names = ["Ali", "Sufyan"]
print({n: len(n) for n in names})Files & Directories
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.
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())
Try it yourself
Create a notes.txt file, write your name in it, then read it back.
with open('notes.txt', 'w') as f:
f.write('Sufyan')
with open('notes.txt') as f:
print(f.read())Errors & Exception Handling
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.
try:
num = int(input("Number: "))
print(10 / num)
except ValueError:
print("Invalid number")
except ZeroDivisionError:
print("Cannot divide by zero")
else:
print("Success")
Try it yourself
Write a safe division function that handles zero.
def safe_div(a, b):
try:
return a / b
except ZeroDivisionError:
return None
print(safe_div(10, 0))Modules & Packages
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.
import math
print(math.sqrt(16))
if __name__ == "__main__":
print("Direct run")
Try it yourself
Use math to print the square root of 25 and pi.
import math print(math.sqrt(25)) print(math.pi)
Useful Standard Library
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.
import random import datetime from collections import Counter print(random.randint(1, 10)) print(datetime.date.today()) print(Counter(["a", "b", "a", "c"]))
Try it yourself
Generate a random 10-character token using letters and digits.
import random
import string
chars = string.ascii_letters + string.digits
print(''.join(random.choices(chars, k=10)))Object-Oriented Python Basics
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.
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())
Try it yourself
Create a Car class with brand and speed, and a method that prints them.
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()Debugging & Writing Better Python
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.
def divide(a, b):
breakpoint() # pauses execution here
return a / b
print(divide(10, 2))
Try it yourself
Write a function that returns None and prints a clear message for invalid input.
def safe_int(value):
try:
return int(value)
except ValueError:
print(f"'{value}' is not a number")
return None
safe_int("abc")Virtual Environments, pip & Project Structure
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.
# 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
Try it yourself
Write the command that creates a virtual environment named .venv.
python -m venv .venv
Capstone: Student Management System
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.
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)
Try it yourself
Add view() and delete(name) methods to StudentManager.
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
Step-by-step: How it works
- The program asks for a starting and ending number.
random.randint(start, end)picks a secret number inside that range.- The loop runs while you still have attempts left.
- Each turn you type a guess, and
used_guessesincreases by 1. - The program says "too low" or "too high" and shows remaining attempts.
- If you guess correctly, the loop breaks and you win.
- The
elseafterwhileruns only if you run out of attempts — a clean Python trick.
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}.")
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
Step-by-step: How it works
word_bankholds a list of possible words.random.choice(word_bank)selects the secret word.revealedis a list of underscores — one per letter.- The loop runs while lives remain and the word is still hidden.
- The player enters one letter — the program validates it.
- If the letter is in the word, every matching position is revealed.
- If not, lives decrease by 1.
- Game ends when the word is fully revealed (win) or lives hit 0 (loss).
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}")
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
Step-by-step: How it works
random.randint(1000, 9999)creates the secret code, thenstr()turns it into text.- The player enters a 4-digit guess.
- Validation rejects anything that isn't exactly 4 digits.
- The program compares each position:
guess[i]vssecret_code[i]. - A counter counts how many positions match.
- The player sees the count but not which digits were correct — that's the puzzle.
- Play repeats until the guess matches the secret code exactly.
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")
You've completed all 20 lessons. Ready to continue?
Continue to Python Intermediate to level up your skills.