Python Code
Samples
Easy snippets you can copy, study, and run in the browser editor.
How to generate an htpasswd bcrypt entry in Python
Create a mock htpasswd file entry with a bcrypt-hashed password for a given username using a simple Python script.
import bcrypt
def mock_htpasswd_entry(username, password):
salt = bcrypt.gensalt(rounds=12)
hashed = bcrypt.hashpw(password.encode(), salt).decode()
return f"{username}:{hashed}"
if __name__ == "__main__":
entry = mock_htpasswd_entry("demo_user", "s3cretP@ss")
print(entry)
How to Hash Passwords with bcrypt in Python
Hash a plaintext password with bcrypt using a randomly generated salt, then verify a plaintext attempt against the stored hash.
import bcrypt
def hash_password(password: str) -> str:
"""Hash a password using bcrypt with a generated salt."""
salt = bcrypt.gensalt()
return bcrypt.hashpw(password.encode("utf-8"), salt).decode("utf-8")
def check_password(password: str, hashed: str) -> bool:
"""Verify a plaintext password against …
Browse by section
Each section groups closely related Python snippets.
Guide: free Python code samples library
Copy-ready Python snippets for learners and developers
PythonSkillset code samples are short, focused examples organised by topic and difficulty. Every snippet is server-rendered HTML — readable by search engines and easy to copy. Open any sample, read the notes, copy the code, then press Try in editor to run it in the browser with Pyodide.
How to use this library
- Pick a topic section — strings, lists, files, functions, and more
- Open a sample, read How it works, and copy the code block
- Run it in the IDE, tweak values, then take a related quiz or tutorial lesson
Samples vs tutorials and challenges
Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.