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 --version or python3 --version in 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

  1. Define a simple function. Use def, a name, parentheses, and a colon, then indent the body:
    def greet():
        print("Hello")
    Nothing runs until you call it.
  2. Call the function. Write its name followed by parentheses: greet(). Output: Hello.
  3. 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")
  4. Return a value. Use return when you need the result later. A function without return gives back None:
    def add(a, b):
        return a + b
    
    total = add(2, 3)  # total is 5
  5. Use default and keyword arguments. Defaults make a parameter optional; keyword arguments name the parameter at the call site:
    def greet(name, greeting="Hello"):
        return greeting + ", " + name
    
    greet("Sam")                 # Hello, Sam
    greet("Sam", greeting="Hi") # Hi, Sam
    Rule: parameters with defaults must come after those without.
  6. Understand scope. Variables created inside a function are local and disappear when it ends. To change a global variable, declare global inside the function, but prefer passing values in and returning results.
  7. Define a class and a method. A method is defined inside a class and takes self as 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
  8. Call methods on an instance. Use object.method(). Python passes the object as self automatically, so you do not supply it yourself.
  9. Know the difference in practice. A function is called as function(arg); a method is called as object.method(arg). Built-in methods include string methods like "text".upper() and list methods like items.append(1).
  10. 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).
  11. 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: greet refers to the function object; greet() runs it.
  • Confusing print with return. Printing shows a value; returning hands it back to the caller.
  • Leaving out self in a method definition, which causes a TypeError when 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. Use None as 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 @staticmethod only when a method genuinely does not need self; 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 self in 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 return statement, 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 global sparingly.

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.