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
Noneis 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.