3405 words
17 minutes
Complete Python Tutorial for Beginners

🐍 Complete Python Tutorial for Beginners#

Python Logo


πŸ“š Table of Contents#

  1. What is Python?
  2. Installing Python
  3. Your First Program
  4. Variables
  5. Data Types
  6. Operators
  7. Strings
  8. Lists
  9. Tuples
  10. Dictionaries
  11. Sets
  12. Conditionals (if/else)
  13. Loops
  14. Functions
  15. Classes and Objects
  16. Modules and Imports
  17. File Handling
  18. Error Handling
  19. List Comprehensions
  20. Lambda Functions
  21. Useful Built-in Functions
  22. Practice Projects

1. What is Python?#

Python Programming

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?#

FieldExamples
Web DevelopmentDjango, Flask
Data SciencePandas, NumPy
AI/Machine LearningTensorFlow, PyTorch
Hacking/SecurityScapy, Requests
AutomationScripts, Bots

2. Installing Python#

On Linux (Kali/Ubuntu):#

Terminal window
sudo apt update
sudo apt install python3 python3-pip

Check Version:#

Terminal window
python3 --version

Output:

Python 3.11.2

Run Python:#

Terminal window
python3

You 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:

Terminal window
python3 hello.py

Output:

Hello, World!

What happened?#

  • print() is a function that shows text on screen
  • "Hello, World!" is a string (text inside quotes)

4. Variables#

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 = True

Printing Variables:#

name = "Ahmed"
age = 25
print(name) # Output: Ahmed
print(age) # Output: 25
print(name, age) # Output: Ahmed 25

Variable Rules:#

βœ… Allowed❌ Not Allowed
name1name (can’t start with number)
user_nameuser-name (no dashes)
userNameuser name (no spaces)
_privateclass (reserved word)

Changing Variables:#

x = 10
print(x) # Output: 10
x = 20 # Changed!
print(x) # Output: 20
x = x + 5 # Add 5
print(x) # Output: 25

5. Data Types#

Data Types

Python has different types of data:

Main Data Types:#

# String (str) - Text
name = "Hacker"
print(type(name)) # <class 'str'>
# Integer (int) - Whole numbers
age = 25
print(type(age)) # <class 'int'>
# Float - Decimal numbers
price = 19.99
print(type(price)) # <class 'float'>
# Boolean (bool) - True or False
is_admin = True
print(type(is_admin)) # <class 'bool'>
# List - Collection of items
skills = ["python", "linux", "hacking"]
print(type(skills)) # <class 'list'>
# Dictionary (dict) - Key-value pairs
user = {"name": "Ahmed", "age": 25}
print(type(user)) # <class 'dict'>
# None - Empty/Nothing
result = None
print(type(result)) # <class 'NoneType'>

Type Conversion:#

# String to Integer
num_str = "100"
num_int = int(num_str)
print(num_int + 50) # Output: 150
# Integer to String
age = 25
age_str = str(age)
print("I am " + age_str) # Output: I am 25
# String to Float
price = float("19.99")
print(price) # Output: 19.99

6. Operators#

Operators

Arithmetic Operators (Math):#

a = 10
b = 3
print(a + b) # Addition: 13
print(a - b) # Subtraction: 7
print(a * b) # Multiplication: 30
print(a / b) # Division: 3.333...
print(a // b) # Floor Division: 3
print(a % b) # Modulus (remainder): 1
print(a ** b) # Power (10Β³): 1000

Comparison Operators:#

x = 10
y = 5
print(x == y) # Equal: False
print(x != y) # Not equal: True
print(x > y) # Greater: True
print(x < y) # Less: False
print(x >= y) # Greater/equal: True
print(x <= y) # Less/equal: False

Logical Operators:#

a = True
b = False
print(a and b) # Both true? False
print(a or b) # One true? True
print(not a) # Opposite: False

Assignment Operators:#

x = 10 # Assign
x += 5 # Same as: x = x + 5 β†’ 15
x -= 3 # Same as: x = x - 3 β†’ 12
x *= 2 # Same as: x = x * 2 β†’ 24
x /= 4 # Same as: x = x / 4 β†’ 6.0

7. Strings#

Strings

Strings are text. Use quotes: "hello" or 'hello'

Creating Strings:#

# Single quotes
name = 'Ahmed'
# Double quotes
message = "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"
# Length
print(len(text)) # 11
# Access characters (index starts at 0)
print(text[0]) # H
print(text[1]) # e
print(text[-1]) # d (last character)
# Slicing [start:end]
print(text[0:5]) # Hello
print(text[6:]) # World
print(text[:5]) # Hello
# Uppercase / Lowercase
print(text.upper()) # HELLO WORLD
print(text.lower()) # hello world
# Replace
print(text.replace("World", "Python")) # Hello Python
# Split into list
print(text.split(" ")) # ['Hello', 'World']
# Check if contains
print("World" in text) # True

String 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 old

Escape Characters:#

# New line
print("Hello\nWorld")
# Output:
# Hello
# World
# Tab
print("Name:\tAhmed")
# Output: Name: Ahmed
# Backslash
print("C:\\Users\\Ahmed")
# Output: C:\Users\Ahmed
# Quote inside string
print("He said \"Hello\"")
# Output: He said "Hello"

8. Lists#

Lists

Lists store multiple items in order. Use square brackets []

Creating Lists:#

# Empty list
my_list = []
# List of strings
fruits = ["apple", "banana", "orange"]
# List of numbers
numbers = [1, 2, 3, 4, 5]
# Mixed list
mixed = ["hello", 42, True, 3.14]
# List of lists
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Accessing Items:#

fruits = ["apple", "banana", "orange", "grape"]
print(fruits[0]) # apple (first)
print(fruits[1]) # banana
print(fruits[-1]) # grape (last)
print(fruits[-2]) # orange (second last)
# Slicing
print(fruits[1:3]) # ['banana', 'orange']
print(fruits[:2]) # ['apple', 'banana']
print(fruits[2:]) # ['orange', 'grape']

Modifying Lists:#

fruits = ["apple", "banana", "orange"]
# Change item
fruits[0] = "mango"
print(fruits) # ['mango', 'banana', 'orange']
# Add item to end
fruits.append("grape")
print(fruits) # ['mango', 'banana', 'orange', 'grape']
# Insert at position
fruits.insert(1, "kiwi")
print(fruits) # ['mango', 'kiwi', 'banana', 'orange', 'grape']
# Remove by value
fruits.remove("banana")
print(fruits) # ['mango', 'kiwi', 'orange', 'grape']
# Remove by index
del fruits[0]
print(fruits) # ['kiwi', 'orange', 'grape']
# Remove and return last item
last = fruits.pop()
print(last) # grape
print(fruits) # ['kiwi', 'orange']
# Clear all items
fruits.clear()
print(fruits) # []

List Methods:#

numbers = [3, 1, 4, 1, 5, 9, 2, 6]
# Length
print(len(numbers)) # 8
# Sort (changes original)
numbers.sort()
print(numbers) # [1, 1, 2, 3, 4, 5, 6, 9]
# Reverse
numbers.reverse()
print(numbers) # [9, 6, 5, 4, 3, 2, 1, 1]
# Count occurrences
print(numbers.count(1)) # 2
# Find index
print(numbers.index(5)) # 2
# Copy list
copy = numbers.copy()
# Join two lists
a = [1, 2]
b = [3, 4]
c = a + b
print(c) # [1, 2, 3, 4]

9. Tuples#

Tuples are like lists but cannot be changed (immutable). Use parentheses ()

# Creating tuple
coordinates = (10, 20)
colors = ("red", "green", "blue")
# Access items (same as list)
print(colors[0]) # red
print(colors[-1]) # blue
# Cannot change! ❌
# colors[0] = "yellow" # Error!
# Tuple with one item (need comma)
single = (42,)
# Unpack tuple
x, y = coordinates
print(x) # 10
print(y) # 20
# Useful for returning multiple values
def get_user():
return ("Ahmed", 25)
name, age = get_user()
print(name, age) # Ahmed 25

When to use Tuple?

  • Data that shouldn’t change
  • Faster than lists
  • Can be used as dictionary keys

10. Dictionaries#

Dictionary

Dictionaries store data in key-value pairs. Use curly braces {}

Creating Dictionaries:#

# Empty dictionary
my_dict = {}
# Dictionary with data
user = {
"name": "Ahmed",
"age": 25,
"skills": ["python", "hacking"],
"is_admin": True
}

Accessing Values:#

user = {"name": "Ahmed", "age": 25, "city": "Casablanca"}
# Get by key
print(user["name"]) # Ahmed
print(user["age"]) # 25
# Get with default (no error if missing)
print(user.get("email")) # None
print(user.get("email", "N/A")) # N/A
# Get all keys
print(user.keys()) # dict_keys(['name', 'age', 'city'])
# Get all values
print(user.values()) # dict_values(['Ahmed', 25, 'Casablanca'])
# Get all items
print(user.items()) # dict_items([('name', 'Ahmed'), ...])

Modifying Dictionaries:#

user = {"name": "Ahmed", "age": 25}
# Change value
user["age"] = 26
print(user) # {'name': 'Ahmed', 'age': 26}
# Add new key
user["email"] = "ahmed@hack.com"
print(user) # {'name': 'Ahmed', 'age': 26, 'email': 'ahmed@hack.com'}
# Remove key
del user["email"]
# Or use pop
age = user.pop("age")
print(age) # 26
# Update multiple
user.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 keys
for key in user:
print(key)
# Loop through values
for value in user.values():
print(value)
# Loop through both
for key, value in user.items():
print(f"{key}: {value}")

Output:

name: Ahmed
age: 25
city: Casablanca

11. Sets#

Sets store unique items (no duplicates). Use curly braces {}

# Creating set
numbers = {1, 2, 3, 4, 5}
fruits = {"apple", "banana", "orange"}
# Duplicates are removed automatically
nums = {1, 2, 2, 3, 3, 3}
print(nums) # {1, 2, 3}
# Add item
fruits.add("grape")
print(fruits) # {'apple', 'banana', 'orange', 'grape'}
# Remove item
fruits.remove("apple")
# Set operations
a = {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) # True

12. Conditionals (if/else)#

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 minor

if-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: C

Nested if:#

age = 25
has_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 = 20
status = "adult" if age >= 18 else "minor"
print(status) # adult

Multiple Conditions:#

age = 25
has_license = True
# AND - Both must be true
if age >= 18 and has_license:
print("You can drive")
# OR - At least one must be true
if age < 13 or age > 65:
print("Free ticket!")
# NOT - Opposite
is_banned = False
if not is_banned:
print("You can enter")

13. Loops#

Loops

Loops repeat code multiple times.

For Loop:#

# Loop through list
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(fruit)
# Output:
# apple
# banana
# orange

Range():#

# Numbers 0 to 4
for i in range(5):
print(i)
# Output: 0, 1, 2, 3, 4
# Numbers 1 to 5
for i in range(1, 6):
print(i)
# Output: 1, 2, 3, 4, 5
# Count by 2
for i in range(0, 10, 2):
print(i)
# Output: 0, 2, 4, 6, 8

While Loop:#

# Repeat while condition is true
count = 0
while 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 early
for i in range(10):
if i == 5:
break
print(i)
# Output: 0, 1, 2, 3, 4
# Continue - Skip current iteration
for i in range(5):
if i == 2:
continue
print(i)
# Output: 0, 1, 3, 4

Loop with Index:#

fruits = ["apple", "banana", "orange"]
# Using enumerate
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
# Output:
# 0: apple
# 1: banana
# 2: orange

Nested Loops:#

# Multiplication table
for i in range(1, 4):
for j in range(1, 4):
print(f"{i} x {j} = {i*j}")
print("---")

14. Functions#

Functions

Functions are reusable blocks of code.

Basic Function:#

# Define function
def say_hello():
print("Hello!")
# Call function
say_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 directly
print(add(10, 20)) # Output: 30

Default 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)) # 3
print(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: Casablanca

15. Classes and Objects#

OOP

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 objects
dog1 = Dog("Buddy", 3)
dog2 = Dog("Max", 5)
# Use methods
dog1.bark() # Buddy says: Woof!
dog2.info() # Max is 5 years old
# Access attributes
print(dog1.name) # Buddy

Inheritance:#

# Parent class
class 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 objects
cat = 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 scanner
scanner = 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

Modules are files containing Python code you can reuse.

Import Entire Module:#

import math
print(math.pi) # 3.141592653589793
print(math.sqrt(16)) # 4.0
print(math.floor(3.7))# 3

Import Specific Function:#

from math import sqrt, pi
print(sqrt(25)) # 5.0
print(pi) # 3.141592653589793

Import with Alias:#

import random as r
print(r.randint(1, 10)) # Random number 1-10
print(r.choice(["a", "b", "c"])) # Random choice

Common Modules:#

# Random numbers
import random
print(random.randint(1, 100)) # Random 1-100
print(random.choice([1, 2, 3])) # Random from list
# Date and time
from datetime import datetime
now = datetime.now()
print(now.strftime("%Y-%m-%d %H:%M:%S"))
# Operating system
import os
print(os.getcwd()) # Current directory
print(os.listdir()) # List files
# JSON
import json
data = {"name": "Ahmed", "age": 25}
json_str = json.dumps(data)
print(json_str) # {"name": "Ahmed", "age": 25}
# Requests (install: pip install requests)
import requests
response = requests.get("https://api.github.com")
print(response.status_code) # 200

Create Your Own Module:#

mytools.py
def greet(name):
return f"Hello, {name}!"
def add(a, b):
return a + b
main.py
import mytools
print(mytools.greet("Ahmed")) # Hello, Ahmed!
print(mytools.add(5, 3)) # 8

17. File Handling#

File Handling

Reading Files:#

# Read entire file
with open("file.txt", "r") as f:
content = f.read()
print(content)
# Read line by line
with open("file.txt", "r") as f:
for line in f:
print(line.strip())
# Read all lines into list
with 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:#

ModeDescription
rRead (default)
wWrite (overwrites)
aAppend
r+Read and Write
rbRead binary
wbWrite 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 JSON
data = {"name": "Ahmed", "age": 25}
with open("data.json", "w") as f:
json.dump(data, f, indent=4)
# Read JSON
with open("data.json", "r") as f:
loaded = json.load(f)
print(loaded["name"]) # Ahmed

18. Error Handling#

Error Handling

Try/Except catches errors so your program doesn’t crash.

Basic Try/Except:#

try:
result = 10 / 0
except:
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 way
squares = []
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 only
evens = [i for i in range(10) if i % 2 == 0]
print(evens) # [0, 2, 4, 6, 8]
# Filter strings
words = ["apple", "banana", "cherry", "date"]
long_words = [w for w in words if len(w) > 5]
print(long_words) # ['banana', 'cherry']

Transform Items:#

# Uppercase all
words = ["hello", "world"]
upper = [w.upper() for w in words]
print(upper) # ['HELLO', 'WORLD']
# Multiple operations
nums = [1, 2, 3, 4, 5]
result = [n * 2 for n in nums if n > 2]
print(result) # [6, 8, 10]

Dictionary Comprehension:#

# Create dictionary
squares = {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 function
def add(a, b):
return a + b
# Lambda (same thing!)
add = lambda a, b: a + b
print(add(5, 3)) # 8

With map():#

numbers = [1, 2, 3, 4, 5]
# Double each number
doubled = 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 numbers
evens = 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 age
sorted_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() - Length
print(len("hello")) # 5
print(len([1, 2, 3])) # 3
# type() - Data type
print(type(42)) # <class 'int'>
# range() - Number sequence
print(list(range(5))) # [0, 1, 2, 3, 4]
# sum() - Add all
print(sum([1, 2, 3, 4])) # 10
# min() / max()
print(min([5, 2, 8, 1])) # 1
print(max([5, 2, 8, 1])) # 8
# abs() - Absolute value
print(abs(-10)) # 10
# round() - Round number
print(round(3.7)) # 4
print(round(3.14159, 2)) # 3.14
# sorted() - Sort
print(sorted([3, 1, 4, 1, 5])) # [1, 1, 3, 4, 5]
# reversed() - Reverse
print(list(reversed([1, 2, 3]))) # [3, 2, 1]
# zip() - Combine lists
names = ["Ahmed", "Sara"]
ages = [25, 20]
print(list(zip(names, ages))) # [('Ahmed', 25), ('Sara', 20)]
# enumerate() - Index + value
for 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 input
name = input("Enter your name: ")
print(f"Hello, {name}!")
# print() with options
print("Hello", "World", sep="-") # Hello-World
print("No newline", end="!") # No newline!

22. Practice Projects#

Project 1: Password Generator#

import random
import 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 passwords
for 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 requests
from 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?#

  1. Practice daily - Solve problems on:

  2. Build projects - Make real things!

  3. Learn libraries:

    • Web: Flask, Django
    • Data: Pandas, NumPy
    • Hacking: Scapy, Pwntools
    • Automation: Selenium, BeautifulSoup
  4. Read code - Study open source projects


Keep Learning

Happy Coding! πŸπŸš€


Created by cat0x01 πŸ₯·πŸ»