Python

This guide quickly references essential Python syntax, functions, and concepts. Whether you are a beginner or an experienced developer, this cheat sheet will help you improve your Python skills. You'll find examples of basic syntax, data structures, control flow, functions, classes, and more.

Basic Syntax

Variables

x = 10
y = "Hello, World!"
z = 3.14

Data Types

integer = 10
floating_point = 3.14
string = "Hello"
boolean = True
list = [1, 2, 3]
dictionary = {"key": "value"}
tuple = (1, 2, 3)
set = {1, 2, 3}

Control Structures

Conditional Statements

if x > 5:
    print("x is greater than 5")
elif x == 5:
    print("x is 5")
else:
    print("x is less than 5")

Loops

for i in range(5):
    print(i)

while x > 0:
    print(x)
    x -= 1

Functions

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

print(greet("Alice"))

Classes

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

    def bark(self):
        return f"{self.name} says woof!"

dog = Dog("Buddy", 3)
print(dog.bark())

Sorting

sorted_list = sorted(my_list)
sorted_dict = sorted(my_dict.items(), key=lambda item: item[1])

Basic Input/Output

user_input = input("Enter your name: ")
print("Hello,", user_input)

Working with Files

Reading Files

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

Writing Files

with open("file.txt", "w") as file:
    file.write("Hello, World!")

Networking

HTTP Requests

import requests

response = requests.get("http://example.com")
print(response.status_code)
print(response.text)

Socket Programming

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("example.com", 80))
s.sendall(b"GET / HTTP/1.1\r\nHost: example.com\r\n\r\n")
response = s.recv(4096)
print(response)
s.close()

Hashing

import hashlib

# MD5
hash_md5 = hashlib.md5(b"password").hexdigest()
print(f"MD5: {hash_md5}")

# SHA-256
hash_sha256 = hashlib.sha256(b"password").hexdigest()
print(f"SHA-256: {hash_sha256}")

Encryption and Decryption

Using cryptography Library

from cryptography.fernet import Fernet

# Generate a key
key = Fernet.generate_key()
cipher_suite = Fernet(key)

# Encrypt a message
cipher_text = cipher_suite.encrypt(b"Secret message")
print(f"Encrypted: {cipher_text}")

# Decrypt the message
plain_text = cipher_suite.decrypt(cipher_text)
print(f"Decrypted: {plain_text}")

Password Hashing

from passlib.hash import pbkdf2_sha256

# Hash a password
hashed = pbkdf2_sha256.hash("password")
print(f"Hashed: {hashed}")

# Verify a password
is_correct = pbkdf2_sha256.verify("password", hashed)
print(f"Password correct: {is_correct}")

Web Scraping

Using BeautifulSoup

from bs4 import BeautifulSoup
import requests

response = requests.get("http://example.com")
soup = BeautifulSoup(response.text, 'html.parser')

for link in soup.find_all('a'):
    print(link.get('href'))

Working with JSON

import json

# Parse JSON
data = '{"name": "Alice", "age": 25}'
parsed_data = json.loads(data)
print(parsed_data)

# Convert to JSON
dict_data = {"name": "Bob", "age": 30}
json_data = json.dumps(dict_data)
print(json_data)

Command Execution

Using subprocess Module

import subprocess

# Run a command and get the output
result = subprocess.run(["ls", "-la"], capture_output=True, text=True)
print(result.stdout)

Regular Expressions

import re

pattern = r"\b[A-Za-z]+\b"
text = "The quick brown fox jumps over the lazy dog"

matches = re.findall(pattern, text)
print(matches)

Logging

import logging

logging.basicConfig(level=logging.INFO)
logging.info("This is an info message")
logging.warning("This is a warning message")
logging.error("This is an error message")

Useful Tips

Virtual Environments

# Create a virtual environment
python -m venv venv

# Activate the virtual environment
# On Windows
venv\Scripts\activate
# On Unix or MacOS
source venv/bin/activate

# Install dependencies
pip install -r requirements.txt

# Deactivate the virtual environment
deactivate

Exception Handling

try:
    result = 10 / 0
except ZeroDivisionError as e:
    print(f"Error: {e}")
finally:
    print("This block is always executed")

List Comprehensions

squares = [x ** 2 for x in range(10)]
print(squares)

Dictionary Comprehensions

squares_dict = {x: x ** 2 for x in range(10)}
print(squares_dict)

Using itertools for Efficient Iteration

import itertools

permutations = list(itertools.permutations([1, 2, 3]))
print(permutations)

combinations = list(itertools.combinations([1, 2, 3], 2))
print(combinations)

Using collections for Advanced Data Structures

from collections import Counter, defaultdict, deque

# Counter
counter = Counter("hello world")
print(counter)

# Defaultdict
default_dict = defaultdict(int)
default_dict["key"] += 1
print(default_dict)

# Deque
deque_list = deque([1, 2, 3])
deque_list.appendleft(0)
print(deque_list)

Using os for System Operations

import os

# Get current working directory
cwd = os.getcwd()
print(cwd)

# List files in directory
files = os.listdir(".")
print(files)

# Execute a system command
os.system("echo Hello, World!")

Penetration Testing Tools

scapy for Network Packet Manipulation

from scapy.all import *

# Create a packet
packet = IP(dst="192.168.1.1")/ICMP()
# Send the packet
send(packet)

nmap for Network Scanning

import nmap

nm = nmap.PortScanner()
nm.scan('127.0.0.1', '22-443')
print(nm.csv())

socket for Simple Network Connections

pythonCopy codeimport socket

# Create a socket object
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect to a server
s.connect(('localhost', 8080))
# Send data
s.sendall(b'Hello, World!')
# Receive data
data = s.recv(1024)
print('Received', repr(data))
# Close the connection
s.close()

Last updated

Was this helpful?