Functions and methods are the building blocks of reusable Python code. A function is a named block of code you define with def and call by name; a method is a function that belongs to an object (usually a class) and is called on that object. You need Python installed and a way to run code (the interactive interpreter, IDLE, or any editor). The steps below use only standard Python syntax that works in Python 3.
What You'll Need
- Python 3 installed (check with
python --versionorpython3 --versionin a terminal). - A place to write and run code: the interactive interpreter, IDLE, or an editor such as VS Code.
- Basic familiarity with variables, indentation, and calling
print().
Step-by-Step
- Define a simple function. Use
def, a name, parentheses, and a colon, then indent the body:
Nothing runs until you call it.def greet(): print("Hello") - Call the function. Write its name followed by parentheses:
greet(). Output:Hello. - Add parameters and arguments. Parameters are the names in the definition; arguments are the values you pass:
def greet(name): print("Hello, " + name) greet("Sam") - Return a value. Use
returnwhen you need the result later. A function withoutreturngives backNone:def add(a, b): return a + b total = add(2, 3) # total is 5 - Use default and keyword arguments. Defaults make a parameter optional; keyword arguments name the parameter at the call site:
Rule: parameters with defaults must come after those without.def greet(name, greeting="Hello"): return greeting + ", " + name greet("Sam") # Hello, Sam greet("Sam", greeting="Hi") # Hi, Sam - Understand scope. Variables created inside a function are local and disappear when it ends. To change a global variable, declare
globalinside the function, but prefer passing values in and returning results. - Define a class and a method. A method is defined inside a class and takes
selfas its first parameter, which refers to the instance:class Counter: def __init__(self): self.count = 0 def increment(self): self.count += 1 c = Counter() c.increment() print(c.count) # 1 - Call methods on an instance. Use
object.method(). Python passes the object asselfautomatically, so you do not supply it yourself. - Know the difference in practice. A function is called as
function(arg); a method is called asobject.method(arg). Built-in methods include string methods like"text".upper()and list methods likeitems.append(1). - Add a docstring. Put a triple-quoted string as the first line of the body to describe what the function does. It shows up in
help(your_function). - Keep functions small and single-purpose. If a function needs a comment to explain each block, split it. Name functions with verbs (
calculate_total) and classes with nouns (Invoice).
Common Mistakes
- Forgetting the parentheses when calling:
greetrefers to the function object;greet()runs it. - Confusing
printwithreturn. Printing shows a value; returning hands it back to the caller. - Leaving out
selfin a method definition, which causes aTypeErrorwhen called on an instance. - Putting a parameter with a default before one without, which is a
SyntaxError. - Mutating a default mutable argument (such as
def f(items=[])) and being surprised that the list persists between calls. UseNoneas the default and create a new list inside. - Indentation errors: the function body must be indented consistently, usually four spaces.
Tips
- Use
help(function_name)in the interpreter to see a function's docstring and signature. - Return values rather than printing inside functions; it makes them easier to test and reuse.
- Prefer keyword arguments for calls with several parameters to make the code readable.
- Use
@staticmethodonly when a method genuinely does not needself; otherwise keep it a normal method. - Test small functions in the interactive interpreter before wiring them into a larger script.
Troubleshooting
- NameError: name is not defined. The function or variable is defined after the call, misspelled, or in a different scope. Define it first and check spelling.
- TypeError: missing required positional argument. You called the function with fewer arguments than parameters. Check the definition and the call.
- TypeError: takes 0 positional arguments but 1 was given. A method is missing
selfin its definition. - IndentationError or unexpected indent. Mixed tabs and spaces or inconsistent indentation. Use four spaces per level throughout.
- The function runs but returns None. There is no
returnstatement, or the return is inside a branch that did not execute. - Changes to a variable do not stick. It is a local variable. Return the new value and assign it outside, or use
globalsparingly.
Frequently Asked Questions
What is the difference between a function and a method in Python?
A function is defined on its own with def and called by name. A method is a function defined inside a class and called on an instance, which is passed automatically as self.
Do I always need to use return?
No. Use return when the caller needs the result. Without it, the function returns None.
Can a function have no parameters?
Yes. Define it with empty parentheses and call it with empty parentheses.
What does self mean?
self is the instance the method was called on. Python supplies it automatically, so you do not pass it at the call site.
Can I define a function inside another function?
Yes. Nested functions are allowed and can access variables from the enclosing function's scope.
How do I see what arguments a function accepts?
Use help(function_name) in the interpreter, or read the definition and its docstring.