A function is a named, reusable block of code that runs only when called. Defining one with def gives it a name and a body; calling it by that name (with parentheses) actually runs the code inside. Functions let you write a piece of logic once and reuse it anywhere in a program, instead of repeating the same code every time it's needed.
#how it works
1
def name(parameters):
Starts the definition, followed by an indented body.
2
The body runs only when called
Defining a function does not execute it β that happens only at the call site.
3
Call it with parentheses
function_name() actually runs the code inside.
4
Parameters become local variables
Filled in with whatever values are passed at call time.
5
No return means None
A function with no explicit return statement returns None automatically.
#example
def greet(name):
print(f"Hello, {name}!")
Β
greet("Ada")
greet("Grace")
Output
Hello, Ada!
Hello, Grace!
1def greet(name): defines a function named greet, taking one parameter, name.
2Nothing runs yet β defining a function only creates it, ready to be called later.
3greet("Ada") calls the function, binding name to "Ada" for this run, and the body executes.
4greet("Grace") calls it again with a different value β the same code runs, but with name bound to "Grace" this time.
#use cases
Wrapping a piece of logic that's needed in more than one place, avoiding repeated code
Breaking a large program into smaller, named, testable pieces
Giving a complex calculation a clear, descriptive name instead of an inline expression
Building the basic unit that almost every other Python feature (modules, classes, decorators) is built on top of
Practice Python interview questions
Every Python lesson maps to the matching interview topic, with answers written for current Python versions.
Recommended resourcesAffiliate links Β· may earn us a commission
Recommended for learners
Structured coding coursesVideo courses that pair well with visual practice β pick one language and go deep.Browse courses βPro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free βClassic DSA interview booksThe reference books interviewers themselves learned from β great next to the visualizers.See the books β