Functions
Defining Functions
Functions are reusable blocks of code that perform a specific task. They help organize programs into manageable sections.
Syntax of a Function Definition:
def function_name(parameters):
# Function body
# Indented code block
def
: Keyword that indicates the start of a function definition.function_name
: The name of the function used to call it later.parameters
: Optional variables that the function can accept as input.:
: Colon indicating the end of the function header.- Indentation: The function body must be indented consistently (usually 4 spaces).
Example:
Defining a simple greeting function:
def greeting(name):
print("Hello, " + name + "!")
Calling the function:
greeting("Alice")
Output:
Hello, Alice!
Functions with Multiple Parameters
Functions can accept multiple parameters:
def greeting(name, department):
print("Welcome, " + name + "!")
print("You are part of " + department + ".")
Calling the function:
greeting("Bob", "IT Support")
Output:
Welcome, Bob!
You are part of IT Support.
Built-in Functions
Python provides several built-in functions that are readily available for use.
print()
Outputs the specified message to the screen:
print("Hello, World!")
type()
Returns the data type of the specified object:
print(type("security")) # Output: <class 'str'>
print(type(7)) # Output: <class 'int'>
To display the type information, wrap type()
with print()
.
Passing One Function into Another
You can pass the output of one function as the input to another:
print(type(str(7))) # Output: <class 'str'>
str()
Converts a value to a string:
number = 12
print(str(number)) # Output: '12'
sorted()
Returns a sorted list from the items in an iterable:
time_list = [5.2, 3.8, 7.1, 2.4]
print(sorted(time_list)) # Output: [2.4, 3.8, 5.2, 7.1]
- The original list remains unchanged.
max()
And min()
max()
: Returns the largest item.min()
: Returns the smallest item.
sessions = [30, 45, 20, 55, 40]
print(max(sessions)) # Output: 55
print(min(sessions)) # Output: 20
Returning Values
Functions can send back values using the return
statement.
Single Return Value
Calculating the area of a triangle:
def area_triangle(base, height):
return (base * height) / 2
Using the function:
area = area_triangle(5, 4)
print(area) # Output: 10.0
Using Returned Values in Calculations
area_a = area_triangle(5, 4)
area_b = area_triangle(7, 3)
total_area = area_a + area_b
print("The total area is " + str(total_area))
Output:
The total area is 20.5
Returning Multiple Values
Functions can return multiple values as a tuple:
def convert_seconds(seconds):
hours = seconds // 3600 # Floor division
minutes = (seconds % 3600) // 60
remaining_seconds = seconds % 60
return hours, minutes, remaining_seconds
Using the function:
hours, minutes, seconds = convert_seconds(5000)
print(hours, minutes, seconds) # Output: 1 23 20
Functions Without a Return Value
If a function doesn't have a return
statement, it returns None
:
def greet(name):
print("Hello, " + name + "!")
result = greet("Alice")
print(result) # Output: None
None
is a special data type representing the absence of a value.
Code Reuse Principles
Avoiding Code Duplication
Functions promote code reuse and reduce duplication.
Before Refactoring:
name = "Alice"
number = len(name) * 9
print("Hello, " + name + ". Your lucky number is " + str(number))
name = "Bob"
number = len(name) * 9
print("Hello, " + name + ". Your lucky number is " + str(number))
After Refactoring:
def lucky_number(name):
number = len(name) * 9
print("Hello, " + name + ". Your lucky number is " + str(number))
lucky_number("Alice")
lucky_number("Bob")
- Benefits:
- Readability: Clear and concise code.
- Maintainability: Easier to update and manage.
- Efficiency: Less chance of errors.
Code Style
Writing code with good style enhances readability and collaboration.
Self-Documenting Code
Use meaningful variable and function names to make the code understandable.
Example:
def calculate_lucky_number(name):
lucky_number = len(name) * 9
print("Hello, " + name + ". Your lucky number is " + str(lucky_number))
Refactoring Code
Rewriting code to improve its structure without changing its functionality.
Adding Comments
Comments explain the purpose of code segments.
def calculate_lucky_number(name):
# Calculate lucky number based on name length
lucky_number = len(name) * 9
print("Hello, " + name + ". Your lucky number is " + str(lucky_number))
- Use
#
for single-line comments. - Comments should be concise and relevant.
Indentation and Formatting
- Consistency: Use consistent indentation (typically 4 spaces).
- PEP 8 Guidelines: Follow Python's style guide for best practices.
Study Guide: Functions
Key Terms
- Return Value: The output that a function provides using the
return
statement. - Parameter (Argument): A value passed into a function for use within the function.
- Refactoring Code: Modifying code to improve its structure without altering its functionality.
Knowledge Points
- Defining Functions: Use
def
keyword and provide parameters if needed. - Return Statement: Use
return
to send back a value from a function. - Best Practices:
- Reusable Functions: Write functions that can be used in multiple scenarios.
- Self-Documenting Code: Use clear names and structures.
- Comments: Add comments where necessary to explain complex logic.
Coding Skills
Skill Group 1
-
Using Functions with Multiple Parameters:
def rectangle_area(width, height):
return width * height
area = rectangle_area(5, 3) -
Returning a Result Value:
def cube(number):
return number ** 3
result = cube(4) # Output: 64
Skill Group 2
-
Measurement Conversion Function:
def miles_to_kilometers(miles):
return miles * 1.60934 -
Using Arithmetic Operators:
def calculate_time(seconds):
minutes = seconds // 60
remaining_seconds = seconds % 60
return minutes, remaining_seconds -
Combining Text with Function Calls:
print("Kilometers in 5 miles: " + str(miles_to_kilometers(5)))
-
Converting Return Value for Printing:
distance_km = miles_to_kilometers(10)
print("Distance in kilometers: " + str(distance_km)) -
Performing Calculations in Function Calls:
print("Total area: " + str(rectangle_area(5, 3) + rectangle_area(2, 4)))
Additional Resources:
- Python Standard Library Documentation: List of Built-in Functions