← Back to Blog

Functions — The Full Picture

The idea!

You've covered def, parameters, default parameters, return, scope, multiple return values, try/except, and raise.

This is your reference. Everything in one place.

Come back here whenever you need a reminder.

def — defining a function

def greet(name, role="developer"):
    print(f"Hello, {name}. You are a {role}.")

greet("Bull")               # Hello, Bull. You are a developer.
greet("Horn", "student")    # Hello, Horn. You are a student.

Define once. Call anywhere. Default parameters — optional but always available.

return — sending a value back

def calculate_bmi(weight, height):
    return weight / height ** 2

bmi = calculate_bmi(70, 1.75)
print(f"{bmi:.1f}")    # 22.9

return stops the function and sends the value out. Without it — the function returns None.

Multiple return values

def first_and_last(word):
    return word[0], word[-1]

first, last = first_and_last("RedHorn")
print(first, last)    # R n

scope — where variables live

name = "Bull"         # global — readable everywhere

def greet():
    message = "Hello."    # local — gone when function ends
    print(name)           # can read global
    print(message)

greet()
# print(message)    # NameError — doesn't exist here

try / except / else / finally

try:
    age = int(input("Enter your age: "))
except ValueError:
    print("Numbers only.")
else:
    print(f"Your age is {age}.")    # only if try succeeded
finally:
    print("Done.")                  # always runs

raise — throwing your own errors

def get_input(prompt):
    while True:
        try:
            value = float(input(prompt))
            if value <= 0:
                raise ValueError("Must be greater than zero.")
            return value
        except ValueError as e:
            print(f"Invalid: {e}")

Common Mistakes

  • Define before calling — Python reads top to bottom
  • Parentheses required — greet() not greet
  • print inside a function is not return
  • return stops the function — nothing after it runs
  • Default parameters always come last
  • Use parameters and return — avoid modifying globals

What you should understand now

  • def — define once, call anywhere
  • Parameters — values in. return — value out.
  • Default parameters — optional, always available
  • Local scope — lives and dies with the function
  • try / except — handle errors gracefully
  • raise — enforce your function's own rules
[ login to bookmark ] // copied! 21 views · 1 min
// resources
Cheatsheet Functions — The Full Picture
← prev Common Functions Mistakes next → This One's Yours — Functions
// 0 comments
// No comments yet. Be the first.
// leave a comment

// Your comment will appear after approval.