Hello World! An Invitation to Computer Science
Lecture Slides
Functions in Python
Monday April 7, 2008
- interpreters v. compilers
- Python designed for ease of use, readability
- case sensitivity of identifiers
- basic datatypes and expressions
- simple examples
Functions
- function definitions v. function calls
- another source of non-linear control flow
- abstraction: hiding details (and potential complexity)
provides readability
can save lots of space - avoids repetition
make changes, fix errors only once
Function input
- formal parameters v. actual arguments
- arguments can be arbitrary expressions
- argument names independent from parameter names
- parameter names act as local variables
Function output
- return values more general than "print"
- output often designed to be input to another function
rather than for human reader
- common for one function to call another
Incremental development
top-down approach
example: generate list of prime numbers
- overview:
for each number n up to limit
if n is prime then print n
- testing a number is prime:
while we have not found a factor
and we have not gone past square root
if number is divisible by i
then factor has been found
otherwise increase i by 1
- divisibility & square-root comparison