Functions & basics
Reusable building blocks — parameters, returns, scope, and clear function design.
How to Return Multiple Values from a Python Function
This code demonstrates how a Python function can return multiple values as a tuple, and how to unpack that tuple into individual variables.
def get_user_stats(name, score, level):
"""Return multiple values as a tuple."""
return name, score, level
if __name__ == "__main__":
result = get_user_stats("Alice", 95, 3)
print(result)
print(type(result))
# Unpacking into individual variables
player_name, player_score, player_level…
How to Use a Lambda Sort Key in Python
Sort a list of strings by length, then alphabetically, using a lambda function as the sorting key in Python.
def sort_words(words):
"""Sort words by length, then alphabetically using a lambda key."""
return sorted(words, key=lambda word: (len(word), word))
if __name__ == "__main__":
sample_words = ["apple", "kiwi", "banana", "fig", "cherry"]
result = sort_words(sample_words)
print("Original:", sampl…
Browse by section
Each section groups closely related Python snippets.
Functions & basics — Python code examples
What you will find here
This page collects functions & basics snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.
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.