Functions & basics
Reusable building blocks — parameters, returns, scope, and clear function design.
Chain Generators with yield from in Python
Combine multiple generators into one seamless sequence using the `yield from` delegation syntax in Python.
def numbers():
yield 1
yield 2
yield 3
def letters():
yield 'a'
yield 'b'
yield 'c'
def combined():
yield from numbers()
yield from letters()
if __name__ == "__main__":
print(list(combined()))
How to Create Generator Functions with yield in Python
Create a memory-efficient generator function using yield to produce a Fibonacci sequence up to a limit.
def fibonacci_sequence(limit):
"""Generate Fibonacci numbers up to a given limit."""
a, b = 0, 1
while a <= limit:
yield a
a, b = b, a + b
if __name__ == "__main__":
fib_gen = fibonacci_sequence(100)
for number in fib_gen:
print(number, end=" ")
print()
How to Create an Iterator Class with Dunder Methods in Python
A minimal Counter class implementing __iter__ and __next__ to act as a self-iterating iterator, yielding numbers from start to end-1.
class Counter:
def __init__(self, start=0, end=5):
self.current = start
self.end = end
def __iter__(self):
return self
def __next__(self):
if self.current >= self.end:
raise StopIteration
value = self.current
self.current += 1
return val…
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.