Python Basics — Parameters & Return

2 minute read

Parameters & Return

Parameters are the inputs your function receives. Return values are the outputs it sends back.

Positional Parameters

Parameters are listed in the function definition. Arguments are the values passed when calling:

def greet(name, greeting):
    print(f"{greeting}, {name}!")

greet("Alice", "Hello")     # Hello, Alice!
greet("Hello", "Alice")     # Alice, Hello!  (order matters)

Return Statement

return immediately exits the function and sends a value back:

def absolute(n):
    if n >= 0:
        return n
    return -n

print(absolute(5))   # 5
print(absolute(-3))  # 3

Returning Multiple Values (Tuple Unpacking)

def min_max(numbers):
    return min(numbers), max(numbers)

low, high = min_max([3, 1, 4, 1, 5, 9])
print(f"Min: {low}, Max: {high}")
# Min: 1, Max: 9

# Or keep as tuple
result = min_max([3, 1, 4, 1, 5, 9])
print(result)  # (1, 9)

Early Return Pattern

Use early returns to handle edge cases first, keeping the main logic clean:

def divide(a, b):
    if b == 0:
        return None  # early return for edge case

    return a / b

print(divide(10, 3))  # 3.3333333333333335
print(divide(10, 0))  # None
def find_first_even(numbers):
    for n in numbers:
        if n % 2 == 0:
            return n  # exit as soon as found
    return None  # not found

print(find_first_even([1, 3, 4, 6]))  # 4
print(find_first_even([1, 3, 5]))     # None

Return vs Print (Common Beginner Confusion)

# ❌ This PRINTS but doesn't RETURN
def add_print(a, b):
    print(a + b)

# ✅ This RETURNS a value you can use
def add_return(a, b):
    return a + b

# Can't use the result of print version
result1 = add_print(3, 5)   # Prints: 8
print(result1)               # None

# Can use the result of return version
result2 = add_return(3, 5)  # Nothing printed
print(result2)               # 8
total = result2 * 2          # 16

Rule: Use return when you need the value later. Use print() only for displaying output to the user.

Parameters vs Arguments

Technically:

  • Parameters are the variables in the function definition
  • Arguments are the values you pass when calling
def greet(name):    # 'name' is a parameter
    print(f"Hi, {name}")

greet("Alice")      # "Alice" is an argument

In practice, the terms are often used interchangeably.

Required Parameters

All parameters without defaults are required:

def power(base, exponent):
    return base ** exponent

print(power(2, 10))  # 1024

# power(2)  # TypeError: power() missing 1 required positional argument: 'exponent'

Summary

  • Parameters receive input; return sends output
  • Positional arguments must match parameter order
  • Return multiple values as tuples: return a, b
  • Use early returns for edge cases
  • return gives a value; print() shows output — they are NOT the same
  • All non-default parameters are required

Next up: Default & Keyword Arguments →

Updated: