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:
def greet(name):
print("Hello, " + name + "!")
greet("Priya")
greet("Sam")
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:
def square(n):
return n * n
result = square(7)
print(result)
print(square(3) + square(4))
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:
def power(base, exponent=2):
return base ** exponent
print(power(5))
print(power(5, 3))
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:
def describe_pet(name, animal="dog"):
print(name + " is a " + animal)
describe_pet("Rex")
describe_pet(name="Whiskers", animal="cat")
Rex is a dog Whiskers is a cat
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.