Booleans can be used in functions in several ways, including as return values, parameters, and for controlling logic within the function. Here are some examples:
1. Boolean Return Values
Functions can return boolean values to indicate success, failure, or the result of a condition.
Example:
def is_even(number):
return number % 2 == 0 # Returns True if even, False if odd
print(is_even(4)) # Output: True
print(is_even(5)) # Output: False
In this example, the function is_even returns True if the number is even and False if it is odd.
2. Boolean Parameters
Functions can accept boolean parameters to modify their behavior based on the input.
Example:
def greet(name, formal=True):
if formal:
print(f"Good evening, {name}.")
else:
print(f"Hey, {name}!")
greet("Alice") # Output: Good evening, Alice.
greet("Bob", False) # Output: Hey, Bob!
In this example, the formal parameter controls how the greeting is formatted.
3. Conditional Logic Inside Functions
Booleans can be used within functions to control the flow of execution using conditional statements.
Example:
def check_age(age):
if age < 18:
return "Minor"
else:
return "Adult"
print(check_age(15)) # Output: Minor
print(check_age(20)) # Output: Adult
In this example, the function check_age uses a boolean condition to determine whether the person is a minor or an adult.
Summary
- Return Values: Functions can return booleans to indicate conditions or states.
- Parameters: Functions can accept booleans to alter their behavior.
- Conditional Logic: Booleans can control the flow of execution within functions.
Using booleans in functions enhances their flexibility and allows for more complex logic.
