Recent - Posts

Python Functions Explained: def, return, and Default Parameters

Welcome back. If you followed the QBasic series, this one will feel familiar from a different angle, remember SUB and FUNCTION? Python only has one word for both ideas, function, whether it just does something or hands back a value depends entirely on whether you write a return line inside it.

1. Why bother with functions at all

Analogy: a function is a recipe card. You write the steps once, "how to make tea," and from then on you just say "make tea" whenever you want it, without re-explaining every step each time. If you later decide to add more sugar to your recipe, you only change the card itself, every future cup automatically follows the update.

2. Defining a function with def

syntax.py
def greet(name):
    print("Namaste, " + name + "!")

greet("Diwakar")
greet("Sapana")

name here is a parameter, a placeholder waiting for a real value. "Diwakar" and "Sapana" are the actual arguments we hand it each time we call the function.

3. return, giving a value back

square.py
def square(n):
    return n * n

result = square(5)
print(result)   # 25
print() and return are not the same thing. print() just displays something on screen, the function itself still hands back nothing useful. return actually sends a value out of the function, so you can store it, compare it, or use it somewhere else. If you've ever called a function and gotten "None" back unexpectedly, this is almost always why.

4. Default parameter values

You can give a parameter a fallback value, used only when the caller doesn't supply one.

default_param.py
def greet(name="friend"):
    print("Namaste, " + name + "!")

greet("Diwakar")   # Namaste, Diwakar!
greet()            # Namaste, friend!

5. The function machine

Try it: pick a function, send a number through it

Same number, different function, different answer. That's the whole point of writing them separately.

5
→
square(n)
→
?
square.py
def square(n):
    return n * n

6. Scope, what happens inside stays inside

Analogy: a function is like a closed room. Variables you create inside it only exist inside that room, the moment the function finishes, they're gone. If you want something out of the room, you have to hand it out explicitly, with return.
scope.py
def square(n):
    result = n * n
    return result

print(square(4))
print(result)   # NameError: result only exists inside square()

7. Example 1 (Easy): A greeting function

greet.py
def greet(name):
    print("Welcome, " + name + "!")

greet("Rojina")
greet("Bikash")

8. Example 2 (Medium): A function that returns a value

is_even.py
def is_even(n):
    return n % 2 == 0

num = int(input("Enter a number: "))
if is_even(num):
    print("Even")
else:
    print("Odd")

is_even(n) directly returns True or False, which is exactly what an if needs, no extra comparison required.

9. Example 3 (Harder): Default parameters in action

power.py
def power(base, exponent=2):
    return base ** exponent

print(power(5))       # 25, uses default exponent
print(power(5, 3))    # 125, overrides it

10. Example 4 (Hero level): Functions calling functions

grade_report.py
def grade(marks):
    if marks >= 90:
        return "A+"
    elif marks >= 75:
        return "A"
    elif marks >= 60:
        return "B"
    elif marks >= 40:
        return "C"
    else:
        return "Fail"

def report(names, marks_list):
    for i in range(len(names)):
        g = grade(marks_list[i])
        print(f"{names[i]} scored {marks_list[i]} -> Grade {g}")

names = ["Sunita", "Ramesh", "Anita"]
marks = [78, 55, 92]
report(names, marks)

report() calls grade() once for every student, inside its own loop. This is exactly what the QBasic FUNCTION Grade$ example did in Post 10 of that series, write the rule once, call it as many times as needed.

11. Common mistakes

  1. Forgetting return, and being confused when the function gives back None.
  2. Using print() where you actually needed return, print only shows something, it doesn't hand the value anywhere else in your program.
  3. Trying to use a variable from inside a function, outside it, that's the scope rule from section 6.
  4. Calling a function with the wrong number of arguments. If def expects two parameters, you generally need to supply two, unless defaults are involved.

12. Practice tasks

  1. Write a function cube(n) that returns n raised to the power of 3.
  2. Write a function is_vowel(letter) that returns True if the letter is a vowel.
  3. Write a function greet(name, greeting="Namaste") with a default greeting, then call it both with and without the second argument.
  4. Challenge: write a function max_of_three(a, b, c) that returns the largest of three numbers, without using Python's built-in max().

Functions are really the first proper step toward organizing real programs instead of writing one long script top to bottom. Next in the rotation, we're back to DBMS for Part 5, where we finally connect two tables together with JOINs. After that, Python Part 7, reading and writing files.

— Diwakar

Comments