π§ 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.
- 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
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 resultAnatomy of a Function
def line (just like if and while)
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))How Does This Work?
- When Python sees
myFunc(1), it jumps to the function definition - The value
1is assigned to the parameteralpha - The function checks: is
alpha < 0? No, 1 is not less than 0 - So it goes to the
elsebranch and calculatesmath.exp(-1) - The
returnstatement sends this value back print()displays the returned value
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, Bob!
Example 2: A Squaring Function
def square(x):
return x ** 2
# Using the function
print(square(5))
print(square(3))
print(square(10))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)You can also call the function directly:
print(hypotenuse(1, 2))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.
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(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) |
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.
- Everything inside the function must be indented (typically 4 spaces)
- If you have an
ifstatement 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 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 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")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)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 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)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
# 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# 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
def greet():
return "Hello!"
message = greet # Missing parentheses - this doesn't call the function!def greet():
return "Hello!"
message = greet() # Parentheses call the functionMistake 3: Forgetting to Return a Value
def add(a, b):
result = a + b
# Oops! Forgot to return the result
total = add(3, 4)
print(total) # Prints: Nonedef add(a, b):
result = a + b
return result # Don't forget to return!
total = add(3, 4)
print(total) # Prints: 7Mistake 4: Wrong Number of Arguments
def greet(first_name, last_name):
return "Hello, " + first_name + " " + last_name
message = greet("Alice") # ERROR! Missing one argumentdef greet(first_name, last_name):
return "Hello, " + first_name + " " + last_name
message = greet("Alice", "Smith") # Provide all required argumentsMistake 5: Incorrect Indentation
def square(x):
return x ** 2 # ERROR! Not indenteddef square(x):
return x ** 2 # Properly indentedMistake 6: Forgetting the Colon
def square(x) # ERROR! Missing colon
return x ** 2def 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:
rectangle_area(length, width)- returns the area of a rectangletriangle_area(base, height)- returns the area of a trianglecircle_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:
- Asks the user for two numbers
- Asks which operation to perform
- 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 # OptionalCommon Patterns
def say_hello():
print("Hello!")def double(x):
return x * 2def add(a, b):
return a + bdef absolute(x):
if x < 0:
return -x
return xChecklist: Creating Functions
- β Does the function definition start with
def? - β Is there a colon
:at the end of thedefline? - β Is the function body properly indented?
- β Is the function defined before it's called?
- β Does the function
returna 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
defkeyword to define a function - β Don't forget the colon
:after the function definition - β All code inside a function must be indented
- β Use
returnto 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()notfunc - β Functions make code reusable, readable, and organized
β Need Help?
If your program doesn't work, check these common issues:
- NameError: name 'function_name' is not definedβIs the function defined before you call it?
- TypeError: function() takes X positional arguments but Y were givenβCheck the number of arguments
- Function returns NoneβDid you forget the
returnstatement? - IndentationErrorβIs all your function code properly indented?
- SyntaxErrorβDid you forget the colon after
def function_name()?
def my_function(x):
print("DEBUG: x =", x) # See the input value
result = x * 2
print("DEBUG: result =", result) # See the result
return resultπ 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: