Intro to Computer Science / Unit 7: Functions
7.5 Designing with Functions
Notes
Break programs into small functions, each with one clear purpose, and give them descriptive names.
- Write a function when you repeat the same steps or when a task can be named clearly.
- Functions can call other functions.
def is_even(n):
return n % 2 == 0
def describe(n):
if is_even(n):
return "even"
return "odd"
print(describe(7))
is_even(7)is False, sodescribe(7)returnsoddand the program printsodd.- A function returning True or False is often called a predicate.
- Test each function on its own with several inputs, including edge cases like 0.
Practice
What does
print(is_even(10)) display using the code above?10 % 2 is 0, so the comparison is True.
What does
print(describe(0)) display using the code above?0 % 2 == 0, so 0 is even.
Why is
calculate_tip a better function name than f1?Descriptive names make programs easier to understand and maintain.
Ready for more? Take the Unit 7 test.