Part 6: Functions

Kerry Back, Rice University

Built-in Functions

Python includes many built-in functions you can use immediately:

Mathematical: - abs(x), max(), min(), sum(), round()

Sequence: - len(), sorted(), reversed(), enumerate(), zip()

Type/Conversion: - type(), str(), int(), float(), bool(), isinstance()

These are optimized - use them instead of writing your own!

Built-in Functions Examples

numbers = [-5, 3, -1, 8, 2]

print("Max:", max(numbers))
print("Min:", min(numbers))
print("Sum:", sum(numbers))
print("Absolute value of -5:", abs(-5))
print("Round 3.14159 to 2 decimals:", round(3.14159, 2))
Max: 8
Min: -5
Sum: 7
Absolute value of -5: 5
Round 3.14159 to 2 decimals: 3.14

Practice: Built-in Functions

Exercise 1 (with Gemini): Ask Gemini to “write Python code that finds the maximum of a list of numbers”

Exercise 2 (on your own): Type print(abs(-10)) and run it.

Sequence Functions

fruits = ["banana", "apple", "cherry"]
scores = [85, 92, 78]

print("Sorted:", sorted(fruits))
print("Length:", len(fruits))

# Zip combines sequences
for fruit, score in zip(fruits, scores):
    print(f"{fruit}: {score}")
Sorted: ['apple', 'banana', 'cherry']
Length: 3
banana: 85
apple: 92
cherry: 78

Practice: Sequence Functions

Exercise 1 (with Gemini): Ask Gemini to “write Python code that sorts a list of names alphabetically”

Exercise 2 (on your own): Type print(sorted([3, 1, 4, 1, 5])) and run it.

Enumerate

enumerate() adds index numbers to items:

fruits = ["apple", "banana", "cherry"]

for index, fruit in enumerate(fruits):
    print(f"{index}: {fruit}")

# Start at 1 instead of 0
for num, fruit in enumerate(fruits, start=1):
    print(f"#{num}: {fruit}")
0: apple
1: banana
2: cherry
#1: apple
#2: banana
#3: cherry

Practice: Enumerate

Exercise 1 (with Gemini): Ask Gemini to “write Python code that uses enumerate to print index and value for a list”

Exercise 2 (on your own): Type for i, x in enumerate(['a', 'b']): print(i, x) and run it.

Creating Custom Functions

Define your own functions with def:

def add_numbers(a, b):
    """Add two numbers together."""
    return a + b

result = add_numbers(5, 3)
print(f"5 + 3 = {result}")
5 + 3 = 8

Components: - def keyword - Function name (lowercase_with_underscores) - Parameters in parentheses - Docstring (optional) - Indented function body - return statement (optional)

Practice: Creating Functions

Exercise 1 (with Gemini): Ask Gemini to “write Python code that creates a function to multiply two numbers”

Exercise 2 (on your own): Type def greet(): print("Hi") then greet() and run it.

Functions Examples

def greet_person(name):
    """Print a greeting."""
    print(f"Hello, {name}!")

greet_person("Alice")

def classify_temperature(temp):
    """Classify temperature as cold, moderate, or hot."""
    if temp < 70:
        return "cold"
    elif temp < 85:
        return "moderate"
    else:
        return "hot"

print(classify_temperature(75))
Hello, Alice!
moderate

Practice: Function Examples

Exercise 1 (with Gemini): Ask Gemini to “write Python code that creates a function to check if a number is even”

Exercise 2 (on your own): Type def double(x): return x * 2 then print(double(5)) and run it.

Variable Scope

Variables created inside functions are local - they only exist within the function:

def my_function(x):
    local_var = x * 2
    return local_var

result = my_function(5)
print("Result:", result)

# This causes an error - local_var doesn't exist outside the function
print(local_var)
Result: 10
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[6], line 9
      6 print("Result:", result)
      8 # This causes an error - local_var doesn't exist outside the function
----> 9 print(local_var)

NameError: name 'local_var' is not defined

Returning Multiple Values

Functions can return multiple values as a tuple:

def get_name_parts():
    return "John", "Smith"

# Unpack into variables
first, last = get_name_parts()
print(f"First: {first}, Last: {last}")

# Or receive as tuple
name = get_name_parts()
print(f"Tuple: {name}")
First: John, Last: Smith
Tuple: ('John', 'Smith')

Practice: Multiple Returns

Exercise 1 (with Gemini): Ask Gemini to “write Python code that creates a function returning two values and unpacks them”

Exercise 2 (on your own): Type def nums(): return 1, 2 then a, b = nums() then print(a, b) and run it.

Multiple Return Example

def rectangle_properties(length, width):
    """Calculate area and perimeter of a rectangle."""
    area = length * width
    perimeter = 2 * (length + width)
    return area, perimeter

area, perimeter = rectangle_properties(5, 3)
print(f"Area: {area}")
print(f"Perimeter: {perimeter}")
Area: 15
Perimeter: 16

Practice: Multiple Return Example

Exercise 1 (with Gemini): Ask Gemini to “write Python code that creates a function to calculate circle area and circumference”

Exercise 2 (on your own): Type def calc(): return 10, 20 then x, y = calc() then print(x + y) and run it.

Default Values

Parameters can have default values making them optional:

def greet(name, greeting="Hello"):
    """Greet someone with customizable greeting."""
    return f"{greeting}, {name}!"

# Use default greeting
print(greet("Alice"))

# Provide custom greeting
print(greet("Bob", "Hi"))
print(greet("Carol", greeting="Hey"))
Hello, Alice!
Hi, Bob!
Hey, Carol!

Best practice: Required parameters first, optional ones last.

Practice: Default Values

Exercise 1 (with Gemini): Ask Gemini to “write Python code that creates a function with a default parameter”

Exercise 2 (on your own): Type def say(msg="Hi"): print(msg) then say() and say("Hello") and run it.

Named Arguments

Call functions with named arguments for clarity:

def power(x, y=2):
    """Calculate x raised to the power y."""
    return x ** y

# Positional arguments
print(power(5, 3))

# Named arguments
print(power(x=5, y=3))
print(power(y=3, x=5))  # Order doesn't matter!

# Mixed
print(power(5, y=3))
125
125
125
125

Practice: Named Arguments

Exercise 1 (with Gemini): Ask Gemini to “write Python code that calls a function using named arguments”

Exercise 2 (on your own): Type def add(a, b): return a + b then print(add(b=5, a=3)) and run it.

The help() Function

Use help() to see function documentation:

help(round)
Help on built-in function round in module builtins:

round(number, ndigits=None)
    Round a number to a given precision in decimal digits.

    The return value is an integer if ndigits is omitted or None.  Otherwise
    the return value has the same type as the number.  ndigits may be negative.

Also works with methods:

help(str.replace)
Help on method_descriptor:

replace(self, old, new, /, count=-1) unbound builtins.str method
    Return a copy with all occurrences of substring old replaced by new.

      count
        Maximum number of occurrences to replace.
        -1 (the default value) means replace all occurrences.

    If the optional argument count is given, only the first count occurrences are
    replaced.

Summary

  • Built-in functions: max(), min(), sum(), len(), sorted(), enumerate(), zip(), etc.
  • Custom functions: Define with def, use descriptive names
  • Variable scope: Local variables only exist within functions
  • Multiple returns: Return tuples and unpack: a, b = func()
  • Default values: Make parameters optional
  • Named arguments: Call functions with param=value for clarity
  • help(): Get function documentation

Functions make code reusable, organized, and maintainable!