🎉 Welcome to PyVerse! Start Learning Today

Understanding Functions Deeply

Understanding Functions Deeply (Parameters, Return Values)

1) Why functions?

  • A function is a reusable mini-program. You give it input (parameters), it does work, and it can give back an answer (return value).
  • Without return values, your function can print or change things, but the best reusable functions often return something you can use later.

2) Parameters: the inputs to your function

  • Parameter: the name inside the function definition.
  • Argument: the actual value you pass when you call the function.

Positional parameters (order matters):

def rectangle_area(width, height): return width * height area = rectangle_area(5, 3) # width=5, height=3 print(area) # 15

Keyword arguments (order doesn't matter when you name them):

area = rectangle_area(height=3, width=5) # same result

Default parameters (a value used if you don't pass one):

def greet(name, time_of_day="morning"): return f"Good {time_of_day}, {name}!" print(greet("Sam")) # Good morning, Sam! print(greet("Pia", "evening")) # Good evening, Pia! print(greet(time_of_day="afternoon", name="Ari")) # Good afternoon, Ari!

Tip: Put non-default parameters first, then default ones. Avoid using mutable objects (like lists or dicts) as defaults. Use None instead and create them inside the function if needed.

3) Return values: getting results out

  • return sends a value back to the caller. You can store it in a variable.
  • If you don't use return, Python returns None.

Print vs return:

def add_print(a, b): print(a + b) # shows the sum, but returns None def add_return(a, b): return a + b # gives back the sum x = add_print(2, 3) # prints 5, but x is None y = add_return(2, 3) # y is 5 print("x:", x) # x: None print("y:", y) # y: 5

Prefer returning values for functions that compute things. Use print for showing messages to the user.

Early returns: exit a function as soon as you know the answer or detect a problem.

def safe_divide(a, b): if b == 0: return None # or return "Cannot divide by zero" return a / b print(safe_divide(10, 2)) # 5.0 print(safe_divide(10, 0)) # None

Returning multiple values (really a tuple), and unpacking:

def stats(numbers): count = len(numbers) total = sum(numbers) average = total / count if count else 0 return count, total, average n, s, avg = stats([2, 4, 6, 8]) print(n, s, avg) # 4 20 5.0

Using one function's output as another's input (composition):

def c_to_f(c): return c * 9/5 + 32 def describe_temp_c(c): f = c_to_f(c) return f"{c}°C is {f}°F" print(describe_temp_c(25)) # 25°C is 77.0°F

4) Local variables and scope (quick note)

  • Variables created inside a function are local to that function.
  • To use data outside the function, return it and store it in a variable.

5) Easy practice snippets

A. Default parameter and keyword args:

def power(base, exp=2): return base ** exp print(power(5)) # 25 print(power(2, 5)) # 32 print(power(exp=3, base=4)) # 64

B. Early return:

def first_even(numbers): for n in numbers: if n % 2 == 0: return n return None # no even numbers found print(first_even([1, 3, 5, 10, 11])) # 10

C. Multiple returns:

def min_max(a, b, c): smallest = min(a, b, c) largest = max(a, b, c) return smallest, largest mn, mx = min_max(3, 9, 5) print(mn, mx) # 3 9

Mini Project: Snack Shop Checkout

Goal: Write small, reusable functions that take parameters and return values to compute a final bill.

Requirements:

  • Prices are per item. You'll receive a cart: a list of (name, price, quantity) tuples.
  • Calculate item totals, add tax, and optionally apply a coupon code.
  • Use functions that return values (don't print from inside your calculators).

Step-by-step starter:

# 1) Calculate total for a single line item def item_total(price, quantity, tax_rate=0.07): subtotal = price * quantity tax = subtotal * tax_rate return subtotal + tax # 2) Apply a coupon code to the total def apply_coupon(total, code): # Supported codes: # SAVE10 -> 10% off # TAKE5 -> $5 off if total >= $20 if code == "SAVE10": return total * 0.90 if code == "TAKE5" and total >= 20: return total - 5 return total # unknown code or not eligible # 3) Sum up the cart using the helper functions def checkout(cart, tax_rate=0.07, coupon_code=None): total = 0 for name, price, qty in cart: total += item_total(price, qty, tax_rate=tax_rate) if coupon_code: total = apply_coupon(total, coupon_code) return round(total, 2) # Example cart my_cart = [ ("Chips", 1.50, 2), ("Soda", 2.00, 1), ("Cookie", 0.99, 3), ] final_total = checkout(my_cart, tax_rate=0.06, coupon_code="SAVE10") print("Final total:", final_total)

Challenges to try:

  • Add a function free_item(total, threshold, credit) that returns a new total with a discount when total >= threshold.
  • Add default tax_rate at checkout but allow overriding per item (advanced: pass tax_rate in each tuple and handle it).
  • Return both pre-discount and final total from checkout and unpack them.

Optional extension returning multiple values:

def checkout_with_breakdown(cart, tax_rate=0.07, coupon_code=None): pre_discount = 0 for _, price, qty in cart: pre_discount += item_total(price, qty, tax_rate=tax_rate) final = apply_coupon(pre_discount, coupon_code) if coupon_code else pre_discount return round(pre_discount, 2), round(final, 2) before, after = checkout_with_breakdown(my_cart, 0.06, "TAKE5") print("Before coupon:", before, "After coupon:", after)

Common mistakes and tips

  • Printing inside functions vs returning: Return computed values so you can reuse them.
  • Forgetting to use the return value: If you don't store the result, it's lost.
  • Parameter order: Put required parameters first, then defaults.
  • Naming: Use clear, action-based names like calculate_total, apply_coupon.

Summary

  • Parameters are named inputs your function expects; you can use positional, keyword, and default parameters.
  • return sends a value back. Without return, your function gives back None.
  • You can return multiple values (as a tuple) and unpack them.
  • Use early returns for clearer logic.
  • Build small, focused functions and combine them to create larger programs.

Loading quizzes...