# 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.&#x20;

### Basic Syntax

#### Variables

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

#### Data Types

```python
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**

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

**Loops**

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

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

#### Functions

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

print(greet("Alice"))
```

#### Classes

```python
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

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

#### Basic Input/Output

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

### Working with Files

#### Reading Files

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

#### Writing Files

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

### Networking

#### HTTP Requests

```python
import requests

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

#### Socket Programming

```python
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()
```

### Security-Related Modules

#### Hashing

```python
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**

```python
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

```python
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`

```python
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

```python
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

```python
import subprocess

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

### Regular Expressions

```python
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

```python
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

```sh
# 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

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

#### List Comprehensions

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

#### Dictionary Comprehensions

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

#### Using `itertools` for Efficient Iteration

```python
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

```python
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

```python
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

```python
from scapy.all import *

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

#### `nmap` for Network Scanning

```python
import nmap

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

#### `socket` for Simple Network Connections

```python
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()
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.hackerspot.net/cheatsheets/coding/python.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
