Functions

A function packages up a piece of logic under a name, so you can run it again from anywhere in your program instead of copying and pasting the same lines every time you need them.

Defining and calling a function

def starts a function definition. Anything indented underneath it is the function's body, and it only runs when the function is called:

>>> a simple greeting
def greet(name):
    print("Hello, " + name + "!")

greet("Priya")
greet("Sam")
Output
Hello, Priya!
Hello, Sam!

Returning a value

return hands a value back to whatever called the function, so it can be stored in a variable or used in a larger expression rather than just printed:

>>> computing a value
def square(n):
    return n * n

result = square(7)
print(result)
print(square(3) + square(4))
Output
49
25

A function without an explicit return statement hands back None automatically — that's why greet() above was only ever called for its printed side effect, never assigned to a variable.

Default arguments

Giving a parameter a default value makes it optional — callers can leave it out and get the default, or supply their own to override it:

>>> an optional parameter
def power(base, exponent=2):
    return base ** exponent

print(power(5))
print(power(5, 3))
Output
25
125

Keyword arguments

You can also pass arguments by name instead of by position, which makes a call self-documenting and lets you skip earlier defaults without listing them:

>>> calling with keywords
def describe_pet(name, animal="dog"):
    print(name + " is a " + animal)

describe_pet("Rex")
describe_pet(name="Whiskers", animal="cat")
Output
Rex is a dog
Whiskers is a cat
Note: never use a mutable value like a list or dictionary as a default argument (def add_item(item, cart=[])). Python creates that default object exactly once, when the function is defined — not fresh on every call — so every call that relies on the default ends up sharing and mutating the same list. Use None as the default and create a new list inside the function body instead.