Function Basics
- It is possible to write a short Python script as a simple
sequence of Python statements.
- (That’s what we did during the last class)
- However, for all but the smallest programs, it is better to
organize code into
functions
- Functions are named chunks of code that can be used repeatedly
- Why?
- Allows us to re-use code rather than re-typing it.
- e.g., say
math.sqrt
rather than repeating the code to compute a square root every time you need one.
- e.g., say
- It’s easier to reason about smaller problems.
- We can break a large, complex problem into many smaller, easier problems.
- General coding principle: _D_on’t _R_epeat _Y_ourself: If you have multiple groups of identical code, then find a bug in one, you have to fix that same bug in all the copies.
- Allows us to re-use code rather than re-typing it.
- Write a basic function like
say_hello
- Notice that the contents of the function are determined by the indentation.
- This is different from most languages!
-
As with variables, the convention is to use
snake_case
with functions - Work through tasks 1 and 2 from IC 2.