Cool Computer Science Thing of the Day
Reading Questions
Quiz
Emacs Tip of the Day
- M-/ auto complete
Fruitful Functions
- Functions are named code
- Parameters are the inputs to the named code
Return values are the output of the nameed code
def square(x): x_squared = x * x return x_squared;
Note, return is not a function, so there should not be parentheses around the value that is returned n* Call the function just like other functions we have learned
square(3)
- What is different about this compared to functions we learned in the last class with the turtle and graphics module, is that this function has no side effects, so calling it like this does nothing
Need to do something with the returned value
print(square(3))
- Note, this is function composition, we done this bunches of times already, it uses the output of one function as the input to anther function
Could also do it with a variable
result = square(3) print(result)
Fruitful Function Gotchas
Forgetting the return:
def square(x): y = x * x print(square(3))
- All functions return something, if you don’t explicitly specify the return value, it will return
None
. Dead code:
def square(x): return x y = x * x print(square(3))
- The function ends execution when the return statement is executed, all code after the return is never executed, it is dead code
Order matters:
print(square(3)) def square(x): return x y = x * x
- Just like with variables the order matters
- Can’t call a function before it is defined
- Typically we put all function definitions at the top of the file, after the import statements
Printing in the function:
def square(x): y = x * x print(y) var value = 3 var value_squared = square(value) print(value, 'squared is', squareed_value)
Printing in the function makes the function less flexible
Test Code
- Functions are a great tool for organizing code
- They allow you to break large programs up into small pieces
- They also make it easy to test the small pieces individually instead of the program as a whole
We test a function by calling it with multiple inputs and printing the result next to the expeced value
print('Input:', 3, Actual:', square(3), 'Expected:', 9) print('Input:', 2, Actual:', square(2), 'Expected:', 4) print('Input:', 1, Actual:', square(1), 'Expected:', 1) print('Input:', 0, Actual:', square(0), 'Expected:', 0) print('Input:', -1, Actual:', square(-1), 'Expected:', 1) print('Input:', -2, Actual:', square(-2), 'Expected:', 4)