Reference library

Python Code Samples

Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.

2 matches
Strings & text easy

Find the Index of a Substring or Return a Default in Python

Finds the index of a substring using str.find() and returns a specified default value instead of -1 when the substring is not found.

substring string-index str-find
Python
def find_substring_or_default(text, substring, default=-1):
    index = text.find(substring)
    return index if index != -1 else default

if __name__ == "__main__":
    text = "The quick brown fox jumps over the lazy dog"
    print(find_substring_or_default(text, "brown"))
    print(find_substring_or_default(text, "c…
13 0 Open
Dictionaries & sets medium

Get Nested Dict Value with Default in Python

Access values deep inside a nested dictionary using a dotted path string, returning a default when any key is missing.

dictionaries nested default-value
Python
def get_nested(d, path, default=None):
    """Walk a nested dict along a dotted path, returning default if missing."""
    current = d
    for key in path.split("."):
        if isinstance(current, dict) and key in current:
            current = current[key]
        else:
            return default
    return current
…
16 0 Open

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

  1. Pick a topic section — strings, lists, files, functions, and more
  2. Open a sample, read How it works, and copy the code block
  3. 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.