Introduction to Python Programming

Andrew J. Pounds, Ph.D.

πŸ”§ Exercise Six: User Defined Functions

Python allows programmers to create functions that can be executed just like regular mathematical functions. This gives the programmer great flexibility and makes it much simpler to think about how to break a program apart into segments to be executed.

What You'll Learn:
  • How to define your own functions
  • How to use parameters (arguments) in functions
  • How to return values from functions
  • The importance of argument order
  • Proper indentation inside functions
🎯 Why Use Functions?

Think of a function like a recipe. Instead of writing out all the steps every time you want to make a cake, you write the recipe once and then just say "make a cake" whenever you need one. Functions let you write code once and reuse it as many times as you want!

πŸ“ 1. The User Defined Function

In Python, user defined functions have to be defined before they are used, so they normally appear at the top of a program. The definition of the function contains the name of the function and the list of arguments that the function takes.

Basic Structure of a Function

def function_name(parameter1, parameter2, ...):
    # Code that does something
    # ...
    return result

Anatomy of a Function

def The keyword that tells Python you're defining a new function
function_name The name you give your function (follow the same rules as variable names)
parameters Variables that receive values when the function is called (inside parentheses)
colon : Required at the end of the def line (just like if and while)
body The indented code that runs when the function is called
return Sends a value back to wherever the function was called (optional)

Your First Function

Here is a function with one argument:

import math

def myFunc(alpha):
    if alpha < 0:
        return math.exp(alpha)
    else:
        return math.exp(-alpha)

Then later in your code, to use the function you could do something like:

print(myFunc(1))
0.36787944117144233

How Does This Work?

  1. When Python sees myFunc(1), it jumps to the function definition
  2. The value 1 is assigned to the parameter alpha
  3. The function checks: is alpha < 0? No, 1 is not less than 0
  4. So it goes to the else branch and calculates math.exp(-1)
  5. The return statement sends this value back
  6. print() displays the returned value
πŸ’‘ Tip: The parameter name (alpha in this case) is just a placeholder. When you call myFunc(1), Python substitutes 1 everywhere alpha appears in the function.

🌟 2. Simple Function Examples

Example 1: A Greeting Function

def greet(name):
    return "Hello, " + name + "!"

# Using the function
message = greet("Alice")
print(message)

print(greet("Bob"))
Hello, Alice!
Hello, Bob!

Example 2: A Squaring Function

def square(x):
    return x ** 2

# Using the function
print(square(5))
print(square(3))
print(square(10))
25
9
100

Example 3: Function Without Return

Not all functions need to return a value. Some just perform an action:

def print_separator():
    print("=" * 40)

# Using the function
print_separator()
print("Welcome to my program!")
print_separator()
========================================
Welcome to my program!
========================================

πŸ“‹ 3. Argument Lists

User defined functions can have any number of arguments. For example, you could do something like this:

Example: Hypotenuse Calculator

import math

def hypotenuse(a, b):
    return math.sqrt(a**2 + b**2)

# Using the function
result = hypotenuse(3, 4)
print("The hypotenuse is:", result)
The hypotenuse is: 5.0

You can also call the function directly:

print(hypotenuse(1, 2))
2.23606797749979

This returns the square root of 5 (since 1Β² + 2Β² = 5).

Multiple Arguments Table

Number of Arguments Example Definition Example Call
0 arguments def sayHello(): sayHello()
1 argument def square(x): square(5)
2 arguments def add(a, b): add(3, 4)
3 arguments def volume(l, w, h): volume(2, 3, 4)

⚠️ 4. Argument Order is Critical!

What is critical is that the order of arguments in the call statement must match the appropriate variable in the function definition.

⚠️ Important: When you call a function, the arguments are matched to parameters by position. The first argument goes to the first parameter, the second to the second, and so on.

Example: Order Matters!

Consider a function like this:

import math

def specialFunc(a, b, c):
    if a > b:
        b = c * 2
        return math.sqrt(a**2 + b**4) - math.exp(c)
    else:
        b = a * 2
        return math.sqrt(a**4 + b**2) - math.exp(c)

If you call this function with different argument orders, you will get VERY different results:

result1 = specialFunc(1, 2, 3)
result2 = specialFunc(2, 1, 3)

print("specialFunc(1, 2, 3) =", result1)
print("specialFunc(2, 1, 3) =", result2)
specialFunc(1, 2, 3) = -17.953147925691677
specialFunc(2, 1, 3) = -3.8731471970108982

What's Happening?

Call a = b = c = Which branch?
specialFunc(1, 2, 3) 1 2 3 else (since 1 > 2 is False)
specialFunc(2, 1, 3) 2 1 3 if (since 2 > 1 is True)
πŸ’‘ Tip: When calling functions with multiple arguments, it can help to use descriptive variable names so you don't mix up the order:
length = 5
width = 3
height = 2

# Clear what each argument represents
volume = calculate_volume(length, width, height)

πŸ“ 5. Note the Indentation

It is also important to note that ALL of the statements inside of a function have to be indented and that even inside that indentation you will have to follow the additional indentation rules for conditional statements and loops.

πŸ“ Indentation Rules for Functions:
  • Everything inside the function must be indented (typically 4 spaces)
  • If you have an if statement inside the function, indent again (8 spaces total)
  • If you have a loop inside the function, same rule applies
  • The function ends when you return to the original indentation level (0 spaces)

Example: Multiple Levels of Indentation

def analyze_number(num):
    # First level of indentation (inside function)
    result = ""
    
    if num > 0:
        # Second level (inside if)
        result = "positive"
        if num % 2 == 0:
            # Third level (inside nested if)
            result = result + " and even"
        else:
            result = result + " and odd"
    elif num < 0:
        result = "negative"
    else:
        result = "zero"
    
    return result

# Back to no indentation - outside the function
print(analyze_number(6))
print(analyze_number(7))
print(analyze_number(-3))
print(analyze_number(0))
positive and even
positive and odd
negative
zero

Example: Loop Inside a Function

def sum_to_n(n):
    # Calculate the sum of 1 + 2 + 3 + ... + n
    total = 0
    counter = 1
    
    while counter <= n:
        total = total + counter
        counter += 1
    
    return total

# Using the function
print("Sum of 1 to 5:", sum_to_n(5))
print("Sum of 1 to 10:", sum_to_n(10))
print("Sum of 1 to 100:", sum_to_n(100))
Sum of 1 to 5: 15
Sum of 1 to 10: 55
Sum of 1 to 100: 5050

πŸ’» 6. Complete Examples

Example 1: Temperature Converter

# Define the conversion functions
def fahrenheit_to_celsius(f):
    return (f - 32) * 5 / 9

def celsius_to_fahrenheit(c):
    return c * 9 / 5 + 32

# Main program
print("=== Temperature Converter ===")
print()

temp_f = 98.6
temp_c = fahrenheit_to_celsius(temp_f)
print(str(temp_f) + "Β°F = " + str(round(temp_c, 2)) + "Β°C")

temp_c = 100
temp_f = celsius_to_fahrenheit(temp_c)
print(str(temp_c) + "Β°C = " + str(temp_f) + "Β°F")
=== Temperature Converter ===

98.6Β°F = 37.0Β°C
100Β°C = 212.0Β°F

Example 2: Grade Calculator

def calculate_average(score1, score2, score3):
    return (score1 + score2 + score3) / 3

def get_letter_grade(average):
    if average >= 90:
        return "A"
    elif average >= 80:
        return "B"
    elif average >= 70:
        return "C"
    elif average >= 60:
        return "D"
    else:
        return "F"

# Main program
print("=== Grade Calculator ===")
print()

test1 = float(input("Enter test 1 score: "))
test2 = float(input("Enter test 2 score: "))
test3 = float(input("Enter test 3 score: "))

avg = calculate_average(test1, test2, test3)
grade = get_letter_grade(avg)

print()
print("Average: " + str(round(avg, 2)))
print("Letter Grade: " + grade)
=== Grade Calculator ===

Enter test 1 score: 85
Enter test 2 score: 92
Enter test 3 score: 78

Average: 85.0
Letter Grade: B

Example 3: Circle Calculations

import math

def circle_area(radius):
    return math.pi * radius ** 2

def circle_circumference(radius):
    return 2 * math.pi * radius

def print_circle_info(radius):
    print("Circle with radius " + str(radius) + ":")
    print("  Area: " + str(round(circle_area(radius), 4)))
    print("  Circumference: " + str(round(circle_circumference(radius), 4)))
    print()

# Main program
print("=== Circle Calculator ===")
print()

print_circle_info(1)
print_circle_info(5)
print_circle_info(10)
=== Circle Calculator ===

Circle with radius 1:
  Area: 3.1416
  Circumference: 6.2832

Circle with radius 5:
  Area: 78.5398
  Circumference: 31.4159

Circle with radius 10:
  Area: 314.1593
  Circumference: 62.8319

Example 4: Using Functions with While Loops

def is_valid_age(age):
    return age >= 0 and age <= 120

def get_age_category(age):
    if age < 13:
        return "child"
    elif age < 20:
        return "teenager"
    elif age < 65:
        return "adult"
    else:
        return "senior"

# Main program with input validation
age = -1

while not is_valid_age(age):
    age = int(input("Enter your age (0-120): "))
    if not is_valid_age(age):
        print("Invalid age! Please try again.")

category = get_age_category(age)
print("You are classified as: " + category)
Enter your age (0-120): -5
Invalid age! Please try again.
Enter your age (0-120): 150
Invalid age! Please try again.
Enter your age (0-120): 25
You are classified as: adult

⚠️ Common Mistakes (And How to Fix Them)

Mistake 1: Calling a Function Before Defining It

❌ Wrong:
# Trying to use the function before defining it
result = square(5)  # ERROR! Python doesn't know what square is yet

def square(x):
    return x ** 2
βœ… Correct:
# Define the function first
def square(x):
    return x ** 2

# Now you can use it
result = square(5)

Mistake 2: Forgetting the Parentheses When Calling

❌ Wrong:
def greet():
    return "Hello!"

message = greet  # Missing parentheses - this doesn't call the function!
βœ… Correct:
def greet():
    return "Hello!"

message = greet()  # Parentheses call the function

Mistake 3: Forgetting to Return a Value

❌ Wrong:
def add(a, b):
    result = a + b
    # Oops! Forgot to return the result

total = add(3, 4)
print(total)  # Prints: None
βœ… Correct:
def add(a, b):
    result = a + b
    return result  # Don't forget to return!

total = add(3, 4)
print(total)  # Prints: 7

Mistake 4: Wrong Number of Arguments

❌ Wrong:
def greet(first_name, last_name):
    return "Hello, " + first_name + " " + last_name

message = greet("Alice")  # ERROR! Missing one argument
βœ… Correct:
def greet(first_name, last_name):
    return "Hello, " + first_name + " " + last_name

message = greet("Alice", "Smith")  # Provide all required arguments

Mistake 5: Incorrect Indentation

❌ Wrong:
def square(x):
return x ** 2  # ERROR! Not indented
βœ… Correct:
def square(x):
    return x ** 2  # Properly indented

Mistake 6: Forgetting the Colon

❌ Wrong:
def square(x)  # ERROR! Missing colon
    return x ** 2
βœ… Correct:
def square(x):  # Don't forget the colon!
    return x ** 2

✏️ Practice Exercises

Try writing these programs on your own!

Exercise 1: Area Calculator

Write three functions:

  1. rectangle_area(length, width) - returns the area of a rectangle
  2. triangle_area(base, height) - returns the area of a triangle
  3. circle_area(radius) - returns the area of a circle

Test each function with sample values.

Exercise 2: Temperature Checker

Write a function check_temperature(temp) that:

  • Returns "freezing" if temp < 32
  • Returns "cold" if temp is 32-50
  • Returns "comfortable" if temp is 51-75
  • Returns "warm" if temp is 76-90
  • Returns "hot" if temp > 90

Exercise 3: Factorial Function

Write a function factorial(n) that calculates n! (n factorial).

Remember: 5! = 5 Γ— 4 Γ— 3 Γ— 2 Γ— 1 = 120

Hint: Use a while loop inside your function.

Exercise 4: Prime Number Checker

Write a function is_prime(n) that returns True if n is a prime number, False otherwise.

Hint: A prime number is only divisible by 1 and itself.

Exercise 5: Password Validator

Write a function is_valid_password(password) that returns True if the password:

  • Is at least 8 characters long

Use the function len(password) to get the length of a string.

Exercise 6: Mini Calculator

Write four functions: add(a, b), subtract(a, b), multiply(a, b), and divide(a, b).

Then write a program that:

  1. Asks the user for two numbers
  2. Asks which operation to perform
  3. Calls the appropriate function and displays the result

Bonus: Make the divide function handle division by zero gracefully.

πŸ“š Quick Reference

Function Definition Syntax

def function_name(param1, param2, ...):
    # Function body (indented)
    # Do something...
    return value  # Optional

Common Patterns

Function with no arguments:
def say_hello():
    print("Hello!")
Function with return value:
def double(x):
    return x * 2
Function with multiple parameters:
def add(a, b):
    return a + b
Function with conditional:
def absolute(x):
    if x < 0:
        return -x
    return x

Checklist: Creating Functions

  • βœ“ Does the function definition start with def?
  • βœ“ Is there a colon : at the end of the def line?
  • βœ“ Is the function body properly indented?
  • βœ“ Is the function defined before it's called?
  • βœ“ Does the function return a value (if needed)?
  • βœ“ Are you calling the function with the correct number of arguments?
  • βœ“ Are the arguments in the correct order?

⭐ Key Takeaways

  • βœ“ Functions must be defined before they are used
  • βœ“ Use the def keyword to define a function
  • βœ“ Don't forget the colon : after the function definition
  • βœ“ All code inside a function must be indented
  • βœ“ Use return to send a value back to the caller
  • βœ“ Argument order mattersβ€”arguments are matched by position
  • βœ“ Nested structures (if/while inside functions) require additional indentation
  • βœ“ Call functions with parentheses: func() not func
  • βœ“ Functions make code reusable, readable, and organized

❓ Need Help?

If your program doesn't work, check these common issues:

  1. NameError: name 'function_name' is not definedβ€”Is the function defined before you call it?
  2. TypeError: function() takes X positional arguments but Y were givenβ€”Check the number of arguments
  3. Function returns Noneβ€”Did you forget the return statement?
  4. IndentationErrorβ€”Is all your function code properly indented?
  5. SyntaxErrorβ€”Did you forget the colon after def function_name()?
πŸ’‘ Debugging Tip: Add print statements inside your function to see what's happening:
def my_function(x):
    print("DEBUG: x =", x)  # See the input value
    result = x * 2
    print("DEBUG: result =", result)  # See the result
    return result
Remember: Functions are one of the most powerful tools in programming! They let you write code once and reuse it many times, making your programs shorter, cleaner, and easier to understand. Start with simple functions and gradually build up to more complex ones. Every professional programmer uses functions extensively!

πŸ”— Additional Resources

For more information on Python's built-in math functions that you can use inside your own functions, check out the official Python documentation:

https://docs.python.org/3.8/library/math.html