π Complete Python Tutorial for Beginners

π Table of Contents
- What is Python?
- Installing Python
- Your First Program
- Variables
- Data Types
- Operators
- Strings
- Lists
- Tuples
- Dictionaries
- Sets
- Conditionals (if/else)
- Loops
- Functions
- Classes and Objects
- Modules and Imports
- File Handling
- Error Handling
- List Comprehensions
- Lambda Functions
- Useful Built-in Functions
- Practice Projects
1. What is Python?
Python is a simple and powerful programming language. Itβs easy to read and write.
Why Learn Python?
- β Easy to learn (like writing English)
- β Used for web, AI, hacking, automation
- β Huge community and libraries
- β High-paying jobs
Where is Python Used?
| Field | Examples |
|---|---|
| Web Development | Django, Flask |
| Data Science | Pandas, NumPy |
| AI/Machine Learning | TensorFlow, PyTorch |
| Hacking/Security | Scapy, Requests |
| Automation | Scripts, Bots |
2. Installing Python
On Linux (Kali/Ubuntu):
sudo apt updatesudo apt install python3 python3-pipCheck Version:
python3 --versionOutput:
Python 3.11.2Run Python:
python3You will see:
>>>This is the Python interactive shell. Type code here!
3. Your First Program
Hello World! π
Create a file called hello.py:
print("Hello, World!")Run it:
python3 hello.pyOutput:
Hello, World!What happened?
print()is a function that shows text on screen"Hello, World!"is a string (text inside quotes)
4. Variables

Variables are like boxes that store data.
Creating Variables:
# Storing a name (string)name = "Ahmed"
# Storing a number (integer)age = 25
# Storing a decimal (float)height = 1.75
# Storing true/false (boolean)is_hacker = TruePrinting Variables:
name = "Ahmed"age = 25
print(name) # Output: Ahmedprint(age) # Output: 25print(name, age) # Output: Ahmed 25Variable Rules:
| β Allowed | β Not Allowed |
|---|---|
name | 1name (canβt start with number) |
user_name | user-name (no dashes) |
userName | user name (no spaces) |
_private | class (reserved word) |
Changing Variables:
x = 10print(x) # Output: 10
x = 20 # Changed!print(x) # Output: 20
x = x + 5 # Add 5print(x) # Output: 255. Data Types

Python has different types of data:
Main Data Types:
# String (str) - Textname = "Hacker"print(type(name)) # <class 'str'>
# Integer (int) - Whole numbersage = 25print(type(age)) # <class 'int'>
# Float - Decimal numbersprice = 19.99print(type(price)) # <class 'float'>
# Boolean (bool) - True or Falseis_admin = Trueprint(type(is_admin)) # <class 'bool'>
# List - Collection of itemsskills = ["python", "linux", "hacking"]print(type(skills)) # <class 'list'>
# Dictionary (dict) - Key-value pairsuser = {"name": "Ahmed", "age": 25}print(type(user)) # <class 'dict'>
# None - Empty/Nothingresult = Noneprint(type(result)) # <class 'NoneType'>Type Conversion:
# String to Integernum_str = "100"num_int = int(num_str)print(num_int + 50) # Output: 150
# Integer to Stringage = 25age_str = str(age)print("I am " + age_str) # Output: I am 25
# String to Floatprice = float("19.99")print(price) # Output: 19.996. Operators

Arithmetic Operators (Math):
a = 10b = 3
print(a + b) # Addition: 13print(a - b) # Subtraction: 7print(a * b) # Multiplication: 30print(a / b) # Division: 3.333...print(a // b) # Floor Division: 3print(a % b) # Modulus (remainder): 1print(a ** b) # Power (10Β³): 1000Comparison Operators:
x = 10y = 5
print(x == y) # Equal: Falseprint(x != y) # Not equal: Trueprint(x > y) # Greater: Trueprint(x < y) # Less: Falseprint(x >= y) # Greater/equal: Trueprint(x <= y) # Less/equal: FalseLogical Operators:
a = Trueb = False
print(a and b) # Both true? Falseprint(a or b) # One true? Trueprint(not a) # Opposite: FalseAssignment Operators:
x = 10 # Assignx += 5 # Same as: x = x + 5 β 15x -= 3 # Same as: x = x - 3 β 12x *= 2 # Same as: x = x * 2 β 24x /= 4 # Same as: x = x / 4 β 6.07. Strings

Strings are text. Use quotes: "hello" or 'hello'
Creating Strings:
# Single quotesname = 'Ahmed'
# Double quotesmessage = "Hello World"
# Triple quotes (multi-line)poem = """Roses are red,Violets are blue,Python is awesome,And so are you!"""print(poem)String Operations:
text = "Hello World"
# Lengthprint(len(text)) # 11
# Access characters (index starts at 0)print(text[0]) # Hprint(text[1]) # eprint(text[-1]) # d (last character)
# Slicing [start:end]print(text[0:5]) # Helloprint(text[6:]) # Worldprint(text[:5]) # Hello
# Uppercase / Lowercaseprint(text.upper()) # HELLO WORLDprint(text.lower()) # hello world
# Replaceprint(text.replace("World", "Python")) # Hello Python
# Split into listprint(text.split(" ")) # ['Hello', 'World']
# Check if containsprint("World" in text) # TrueString Formatting:
name = "Ahmed"age = 25
# Method 1: f-strings (Best! β)print(f"My name is {name} and I am {age} years old")
# Method 2: .format()print("My name is {} and I am {} years old".format(name, age))
# Method 3: % operator (old)print("My name is %s and I am %d years old" % (name, age))Output:
My name is Ahmed and I am 25 years oldEscape Characters:
# New lineprint("Hello\nWorld")# Output:# Hello# World
# Tabprint("Name:\tAhmed")# Output: Name: Ahmed
# Backslashprint("C:\\Users\\Ahmed")# Output: C:\Users\Ahmed
# Quote inside stringprint("He said \"Hello\"")# Output: He said "Hello"8. Lists

Lists store multiple items in order. Use square brackets []
Creating Lists:
# Empty listmy_list = []
# List of stringsfruits = ["apple", "banana", "orange"]
# List of numbersnumbers = [1, 2, 3, 4, 5]
# Mixed listmixed = ["hello", 42, True, 3.14]
# List of listsmatrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]Accessing Items:
fruits = ["apple", "banana", "orange", "grape"]
print(fruits[0]) # apple (first)print(fruits[1]) # bananaprint(fruits[-1]) # grape (last)print(fruits[-2]) # orange (second last)
# Slicingprint(fruits[1:3]) # ['banana', 'orange']print(fruits[:2]) # ['apple', 'banana']print(fruits[2:]) # ['orange', 'grape']Modifying Lists:
fruits = ["apple", "banana", "orange"]
# Change itemfruits[0] = "mango"print(fruits) # ['mango', 'banana', 'orange']
# Add item to endfruits.append("grape")print(fruits) # ['mango', 'banana', 'orange', 'grape']
# Insert at positionfruits.insert(1, "kiwi")print(fruits) # ['mango', 'kiwi', 'banana', 'orange', 'grape']
# Remove by valuefruits.remove("banana")print(fruits) # ['mango', 'kiwi', 'orange', 'grape']
# Remove by indexdel fruits[0]print(fruits) # ['kiwi', 'orange', 'grape']
# Remove and return last itemlast = fruits.pop()print(last) # grapeprint(fruits) # ['kiwi', 'orange']
# Clear all itemsfruits.clear()print(fruits) # []List Methods:
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
# Lengthprint(len(numbers)) # 8
# Sort (changes original)numbers.sort()print(numbers) # [1, 1, 2, 3, 4, 5, 6, 9]
# Reversenumbers.reverse()print(numbers) # [9, 6, 5, 4, 3, 2, 1, 1]
# Count occurrencesprint(numbers.count(1)) # 2
# Find indexprint(numbers.index(5)) # 2
# Copy listcopy = numbers.copy()
# Join two listsa = [1, 2]b = [3, 4]c = a + bprint(c) # [1, 2, 3, 4]9. Tuples
Tuples are like lists but cannot be changed (immutable). Use parentheses ()
# Creating tuplecoordinates = (10, 20)colors = ("red", "green", "blue")
# Access items (same as list)print(colors[0]) # redprint(colors[-1]) # blue
# Cannot change! β# colors[0] = "yellow" # Error!
# Tuple with one item (need comma)single = (42,)
# Unpack tuplex, y = coordinatesprint(x) # 10print(y) # 20
# Useful for returning multiple valuesdef get_user(): return ("Ahmed", 25)
name, age = get_user()print(name, age) # Ahmed 25When to use Tuple?
- Data that shouldnβt change
- Faster than lists
- Can be used as dictionary keys
10. Dictionaries

Dictionaries store data in key-value pairs. Use curly braces {}
Creating Dictionaries:
# Empty dictionarymy_dict = {}
# Dictionary with datauser = { "name": "Ahmed", "age": 25, "skills": ["python", "hacking"], "is_admin": True}Accessing Values:
user = {"name": "Ahmed", "age": 25, "city": "Casablanca"}
# Get by keyprint(user["name"]) # Ahmedprint(user["age"]) # 25
# Get with default (no error if missing)print(user.get("email")) # Noneprint(user.get("email", "N/A")) # N/A
# Get all keysprint(user.keys()) # dict_keys(['name', 'age', 'city'])
# Get all valuesprint(user.values()) # dict_values(['Ahmed', 25, 'Casablanca'])
# Get all itemsprint(user.items()) # dict_items([('name', 'Ahmed'), ...])Modifying Dictionaries:
user = {"name": "Ahmed", "age": 25}
# Change valueuser["age"] = 26print(user) # {'name': 'Ahmed', 'age': 26}
# Add new keyuser["email"] = "ahmed@hack.com"print(user) # {'name': 'Ahmed', 'age': 26, 'email': 'ahmed@hack.com'}
# Remove keydel user["email"]
# Or use popage = user.pop("age")print(age) # 26
# Update multipleuser.update({"city": "Casablanca", "job": "Hacker"})print(user) # {'name': 'Ahmed', 'city': 'Casablanca', 'job': 'Hacker'}Looping Through Dictionary:
user = {"name": "Ahmed", "age": 25, "city": "Casablanca"}
# Loop through keysfor key in user: print(key)
# Loop through valuesfor value in user.values(): print(value)
# Loop through bothfor key, value in user.items(): print(f"{key}: {value}")Output:
name: Ahmedage: 25city: Casablanca11. Sets
Sets store unique items (no duplicates). Use curly braces {}
# Creating setnumbers = {1, 2, 3, 4, 5}fruits = {"apple", "banana", "orange"}
# Duplicates are removed automaticallynums = {1, 2, 2, 3, 3, 3}print(nums) # {1, 2, 3}
# Add itemfruits.add("grape")print(fruits) # {'apple', 'banana', 'orange', 'grape'}
# Remove itemfruits.remove("apple")
# Set operationsa = {1, 2, 3, 4}b = {3, 4, 5, 6}
print(a | b) # Union: {1, 2, 3, 4, 5, 6}print(a & b) # Intersection: {3, 4}print(a - b) # Difference: {1, 2}
# Check membership (very fast!)print(3 in a) # True12. Conditionals (if/else)

Conditionals let you make decisions in your code.
Basic if:
age = 18
if age >= 18: print("You are an adult")if-else:
age = 15
if age >= 18: print("You are an adult")else: print("You are a minor")Output:
You are a minorif-elif-else:
score = 75
if score >= 90: grade = "A"elif score >= 80: grade = "B"elif score >= 70: grade = "C"elif score >= 60: grade = "D"else: grade = "F"
print(f"Your grade is: {grade}")Output:
Your grade is: CNested if:
age = 25has_id = True
if age >= 18: if has_id: print("Welcome to the club!") else: print("Please show your ID")else: print("You are too young")One-line if (Ternary):
age = 20status = "adult" if age >= 18 else "minor"print(status) # adultMultiple Conditions:
age = 25has_license = True
# AND - Both must be trueif age >= 18 and has_license: print("You can drive")
# OR - At least one must be trueif age < 13 or age > 65: print("Free ticket!")
# NOT - Oppositeis_banned = Falseif not is_banned: print("You can enter")13. Loops

Loops repeat code multiple times.
For Loop:
# Loop through listfruits = ["apple", "banana", "orange"]for fruit in fruits: print(fruit)
# Output:# apple# banana# orangeRange():
# Numbers 0 to 4for i in range(5): print(i)# Output: 0, 1, 2, 3, 4
# Numbers 1 to 5for i in range(1, 6): print(i)# Output: 1, 2, 3, 4, 5
# Count by 2for i in range(0, 10, 2): print(i)# Output: 0, 2, 4, 6, 8While Loop:
# Repeat while condition is truecount = 0while count < 5: print(count) count += 1# Output: 0, 1, 2, 3, 4
# Infinite loop (be careful!)# while True:# print("Forever...")Break and Continue:
# Break - Exit loop earlyfor i in range(10): if i == 5: break print(i)# Output: 0, 1, 2, 3, 4
# Continue - Skip current iterationfor i in range(5): if i == 2: continue print(i)# Output: 0, 1, 3, 4Loop with Index:
fruits = ["apple", "banana", "orange"]
# Using enumeratefor index, fruit in enumerate(fruits): print(f"{index}: {fruit}")
# Output:# 0: apple# 1: banana# 2: orangeNested Loops:
# Multiplication tablefor i in range(1, 4): for j in range(1, 4): print(f"{i} x {j} = {i*j}") print("---")14. Functions

Functions are reusable blocks of code.
Basic Function:
# Define functiondef say_hello(): print("Hello!")
# Call functionsay_hello() # Output: Hello!say_hello() # Output: Hello!Function with Parameters:
def greet(name): print(f"Hello, {name}!")
greet("Ahmed") # Output: Hello, Ahmed!greet("Sara") # Output: Hello, Sara!Function with Return:
def add(a, b): return a + b
result = add(5, 3)print(result) # Output: 8
# Use directlyprint(add(10, 20)) # Output: 30Default Parameters:
def greet(name, message="Hello"): print(f"{message}, {name}!")
greet("Ahmed") # Hello, Ahmed!greet("Ahmed", "Welcome") # Welcome, Ahmed!Multiple Returns:
def get_stats(numbers): total = sum(numbers) average = total / len(numbers) return total, average
nums = [10, 20, 30]total, avg = get_stats(nums)print(f"Total: {total}, Average: {avg}")# Output: Total: 60, Average: 20.0*args (Variable Arguments):
def add_all(*numbers): return sum(numbers)
print(add_all(1, 2)) # 3print(add_all(1, 2, 3, 4, 5)) # 15**kwargs (Keyword Arguments):
def print_info(**kwargs): for key, value in kwargs.items(): print(f"{key}: {value}")
print_info(name="Ahmed", age=25, city="Casablanca")# Output:# name: Ahmed# age: 25# city: Casablanca15. Classes and Objects

Classes are blueprints for creating objects.
Basic Class:
class Dog: # Constructor (runs when object is created) def __init__(self, name, age): self.name = name self.age = age
# Method (function inside class) def bark(self): print(f"{self.name} says: Woof!")
def info(self): print(f"{self.name} is {self.age} years old")
# Create objectsdog1 = Dog("Buddy", 3)dog2 = Dog("Max", 5)
# Use methodsdog1.bark() # Buddy says: Woof!dog2.info() # Max is 5 years old
# Access attributesprint(dog1.name) # BuddyInheritance:
# Parent classclass Animal: def __init__(self, name): self.name = name
def speak(self): print("Some sound...")
# Child class (inherits from Animal)class Cat(Animal): def speak(self): print(f"{self.name} says: Meow!")
class Dog(Animal): def speak(self): print(f"{self.name} says: Woof!")
# Create objectscat = Cat("Whiskers")dog = Dog("Buddy")
cat.speak() # Whiskers says: Meow!dog.speak() # Buddy says: Woof!Class Example - Hacker Tool:
class Scanner: def __init__(self, target): self.target = target self.open_ports = []
def scan_port(self, port): # Simplified example print(f"Scanning {self.target}:{port}") self.open_ports.append(port)
def report(self): print(f"Open ports on {self.target}: {self.open_ports}")
# Use the scannerscanner = Scanner("192.168.1.1")scanner.scan_port(80)scanner.scan_port(443)scanner.report()# Output:# Scanning 192.168.1.1:80# Scanning 192.168.1.1:443# Open ports on 192.168.1.1: [80, 443]16. Modules and Imports

Modules are files containing Python code you can reuse.
Import Entire Module:
import math
print(math.pi) # 3.141592653589793print(math.sqrt(16)) # 4.0print(math.floor(3.7))# 3Import Specific Function:
from math import sqrt, pi
print(sqrt(25)) # 5.0print(pi) # 3.141592653589793Import with Alias:
import random as r
print(r.randint(1, 10)) # Random number 1-10print(r.choice(["a", "b", "c"])) # Random choiceCommon Modules:
# Random numbersimport randomprint(random.randint(1, 100)) # Random 1-100print(random.choice([1, 2, 3])) # Random from list
# Date and timefrom datetime import datetimenow = datetime.now()print(now.strftime("%Y-%m-%d %H:%M:%S"))
# Operating systemimport osprint(os.getcwd()) # Current directoryprint(os.listdir()) # List files
# JSONimport jsondata = {"name": "Ahmed", "age": 25}json_str = json.dumps(data)print(json_str) # {"name": "Ahmed", "age": 25}
# Requests (install: pip install requests)import requestsresponse = requests.get("https://api.github.com")print(response.status_code) # 200Create Your Own Module:
def greet(name): return f"Hello, {name}!"
def add(a, b): return a + bimport mytools
print(mytools.greet("Ahmed")) # Hello, Ahmed!print(mytools.add(5, 3)) # 817. File Handling

Reading Files:
# Read entire filewith open("file.txt", "r") as f: content = f.read() print(content)
# Read line by linewith open("file.txt", "r") as f: for line in f: print(line.strip())
# Read all lines into listwith open("file.txt", "r") as f: lines = f.readlines() print(lines)Writing Files:
# Write (overwrites file)with open("output.txt", "w") as f: f.write("Hello World!\n") f.write("Line 2\n")
# Append (adds to file)with open("output.txt", "a") as f: f.write("New line added\n")File Modes:
| Mode | Description |
|---|---|
r | Read (default) |
w | Write (overwrites) |
a | Append |
r+ | Read and Write |
rb | Read binary |
wb | Write binary |
Check if File Exists:
import os
if os.path.exists("file.txt"): print("File exists!")else: print("File not found")Working with JSON:
import json
# Write JSONdata = {"name": "Ahmed", "age": 25}with open("data.json", "w") as f: json.dump(data, f, indent=4)
# Read JSONwith open("data.json", "r") as f: loaded = json.load(f) print(loaded["name"]) # Ahmed18. Error Handling

Try/Except catches errors so your program doesnβt crash.
Basic Try/Except:
try: result = 10 / 0except: print("An error occurred!")Catch Specific Errors:
try: num = int(input("Enter a number: ")) result = 10 / num print(f"Result: {result}")except ValueError: print("That's not a valid number!")except ZeroDivisionError: print("Cannot divide by zero!")except Exception as e: print(f"Unknown error: {e}")Try/Except/Finally:
try: f = open("file.txt", "r") content = f.read()except FileNotFoundError: print("File not found!")finally: # This always runs print("Cleanup done")Raise Your Own Errors:
def set_age(age): if age < 0: raise ValueError("Age cannot be negative!") return age
try: set_age(-5)except ValueError as e: print(e) # Age cannot be negative!19. List Comprehensions
List Comprehensions create lists in one line.
Basic Comprehension:
# Normal waysquares = []for i in range(5): squares.append(i ** 2)print(squares) # [0, 1, 4, 9, 16]
# List comprehension (same result!)squares = [i ** 2 for i in range(5)]print(squares) # [0, 1, 4, 9, 16]With Condition:
# Even numbers onlyevens = [i for i in range(10) if i % 2 == 0]print(evens) # [0, 2, 4, 6, 8]
# Filter stringswords = ["apple", "banana", "cherry", "date"]long_words = [w for w in words if len(w) > 5]print(long_words) # ['banana', 'cherry']Transform Items:
# Uppercase allwords = ["hello", "world"]upper = [w.upper() for w in words]print(upper) # ['HELLO', 'WORLD']
# Multiple operationsnums = [1, 2, 3, 4, 5]result = [n * 2 for n in nums if n > 2]print(result) # [6, 8, 10]Dictionary Comprehension:
# Create dictionarysquares = {i: i**2 for i in range(5)}print(squares) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}20. Lambda Functions
Lambda creates small anonymous functions.
Basic Lambda:
# Normal functiondef add(a, b): return a + b
# Lambda (same thing!)add = lambda a, b: a + b
print(add(5, 3)) # 8With map():
numbers = [1, 2, 3, 4, 5]
# Double each numberdoubled = list(map(lambda x: x * 2, numbers))print(doubled) # [2, 4, 6, 8, 10]With filter():
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Keep even numbersevens = list(filter(lambda x: x % 2 == 0, numbers))print(evens) # [2, 4, 6, 8, 10]With sorted():
users = [ {"name": "Ahmed", "age": 25}, {"name": "Sara", "age": 20}, {"name": "Ali", "age": 30}]
# Sort by agesorted_users = sorted(users, key=lambda x: x["age"])print(sorted_users)# [{'name': 'Sara', 'age': 20}, {'name': 'Ahmed', 'age': 25}, {'name': 'Ali', 'age': 30}]21. Useful Built-in Functions
# len() - Lengthprint(len("hello")) # 5print(len([1, 2, 3])) # 3
# type() - Data typeprint(type(42)) # <class 'int'>
# range() - Number sequenceprint(list(range(5))) # [0, 1, 2, 3, 4]
# sum() - Add allprint(sum([1, 2, 3, 4])) # 10
# min() / max()print(min([5, 2, 8, 1])) # 1print(max([5, 2, 8, 1])) # 8
# abs() - Absolute valueprint(abs(-10)) # 10
# round() - Round numberprint(round(3.7)) # 4print(round(3.14159, 2)) # 3.14
# sorted() - Sortprint(sorted([3, 1, 4, 1, 5])) # [1, 1, 3, 4, 5]
# reversed() - Reverseprint(list(reversed([1, 2, 3]))) # [3, 2, 1]
# zip() - Combine listsnames = ["Ahmed", "Sara"]ages = [25, 20]print(list(zip(names, ages))) # [('Ahmed', 25), ('Sara', 20)]
# enumerate() - Index + valuefor i, val in enumerate(["a", "b", "c"]): print(i, val)# 0 a# 1 b# 2 c
# any() / all()print(any([False, False, True])) # True (at least one)print(all([True, True, True])) # True (all must be)
# input() - User inputname = input("Enter your name: ")print(f"Hello, {name}!")
# print() with optionsprint("Hello", "World", sep="-") # Hello-Worldprint("No newline", end="!") # No newline!22. Practice Projects
Project 1: Password Generator
import randomimport string
def generate_password(length=12): characters = string.ascii_letters + string.digits + string.punctuation password = ''.join(random.choice(characters) for _ in range(length)) return password
# Generate 5 passwordsfor i in range(5): print(generate_password(16))Project 2: Simple Calculator
def calculator(): while True: print("\n--- Calculator ---") print("1. Add") print("2. Subtract") print("3. Multiply") print("4. Divide") print("5. Exit")
choice = input("Choose operation: ")
if choice == "5": print("Goodbye!") break
num1 = float(input("First number: ")) num2 = float(input("Second number: "))
if choice == "1": print(f"Result: {num1 + num2}") elif choice == "2": print(f"Result: {num1 - num2}") elif choice == "3": print(f"Result: {num1 * num2}") elif choice == "4": if num2 != 0: print(f"Result: {num1 / num2}") else: print("Cannot divide by zero!")
calculator()Project 3: Web Scraper
import requestsfrom bs4 import BeautifulSoup
def scrape_titles(url): response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser')
titles = soup.find_all('h1') for title in titles: print(title.text.strip())
# scrape_titles("https://example.com")Project 4: Port Scanner
import socket
def scan_ports(host, start_port, end_port): print(f"Scanning {host}...") open_ports = []
for port in range(start_port, end_port + 1): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(1)
result = sock.connect_ex((host, port)) if result == 0: print(f"Port {port}: OPEN") open_ports.append(port) sock.close()
return open_ports
# scan_ports("127.0.0.1", 1, 100)Project 5: To-Do List
import json
TODO_FILE = "todos.json"
def load_todos(): try: with open(TODO_FILE, "r") as f: return json.load(f) except: return []
def save_todos(todos): with open(TODO_FILE, "w") as f: json.dump(todos, f, indent=2)
def main(): todos = load_todos()
while True: print("\n--- To-Do List ---") for i, todo in enumerate(todos, 1): status = "β" if todo["done"] else " " print(f"{i}. [{status}] {todo['task']}")
print("\nCommands: add, done <num>, delete <num>, quit") cmd = input("> ").strip().split()
if not cmd: continue
if cmd[0] == "add": task = input("Task: ") todos.append({"task": task, "done": False}) save_todos(todos)
elif cmd[0] == "done" and len(cmd) > 1: idx = int(cmd[1]) - 1 if 0 <= idx < len(todos): todos[idx]["done"] = True save_todos(todos)
elif cmd[0] == "delete" and len(cmd) > 1: idx = int(cmd[1]) - 1 if 0 <= idx < len(todos): todos.pop(idx) save_todos(todos)
elif cmd[0] == "quit": break
main()π Congratulations!
Youβve learned the basics of Python!
Whatβs Next?
-
Practice daily - Solve problems on:
-
Build projects - Make real things!
-
Learn libraries:
- Web: Flask, Django
- Data: Pandas, NumPy
- Hacking: Scapy, Pwntools
- Automation: Selenium, BeautifulSoup
-
Read code - Study open source projects

Happy Coding! ππ
Created by cat0x01 π₯·π»