Functions in Python
def, arguments, return values, default and keyword arguments, and what scope actually means.
5 minute read · Free · Taught properly in our Python Training in Amritsar
A function is a piece of code with a name, so you can run it from more than one place without copying it.
def greet(name):
return f"Hello, {name}"
print(greet("Simran")) # Hello, Simran
def, a name, arguments in brackets, a colon, then an indented body. return hands a value back.
return vs print
These are not the same thing, and mixing them up is the single most common beginner bug:
def add(a, b):
print(a + b) # shows it on screen
def add(a, b):
return a + b # gives it back to the caller
With print, total = add(2, 3) sets total to None — the number went to the screen and nowhere else. If you plan to use the answer, return it. A function with no return returns None.
Default and keyword arguments
def enrol(name, course="Python", months=4):
return f"{name}: {course}, {months} months"
enrol("Ravi") # Ravi: Python, 4 months
enrol("Ravi", "Django") # Ravi: Django, 4 months
enrol("Ravi", months=6) # Ravi: Python, 6 months
enrol(course="IoT", name="Simran") # order stops mattering
Arguments with defaults must come after arguments without them. And keep defaults immutable — None, a number, a string — never a list or dictionary, for the reason covered in the lists lesson.
Scope
A name made inside a function lives only inside it:
def calculate():
total = 100 # local
return total
calculate()
print(total) # NameError — there is no 'total' out here
You can read an outer name from inside a function, but assigning to it makes a new local one instead of changing the outer. If you find yourself reaching for global, stop and pass the value in as an argument and return the result instead. Code that talks to its caller only through arguments and return values is the code you can still understand in March.
Docstrings
def monthly_fee(months):
"""Total fee for a given number of months."""
return months * 4500
A single line in triple quotes, first thing in the body. help(monthly_fee) will print it, and so will your editor when you hover the name.
Stuck on this in your own code?
That is what a class is for. Sit one for free at WebPrims on Majitha Road, Amritsar — write some Python, ask the mentor why yours is not working, and decide afterwards.