22.22222222222222
0c: Python Basics II
Functions, methods, and control structures let us create a procedure and reuse it.
We’re moving a bit closer to actual programming: define a small procedure, make decisions, and repeat work. It’s sometimes instructive to contrast with physical terms: imagine a machine that could perfectly process an input, scale practically infinitely for relatively little cost, and have any part easily changed.
Functions
Input, procedure, return.
Methods
Functions attached to objects.
Control structures
If-then statements and loops.
Much like math, functions are objects that take input and map that input to a particular output.
In programming, we tend to refer to input as arguments, and output as returns.
There are many built in, and we can make our own.
Definition
def creates the function and gives it a name.
Parameters
The parentheses define what input the function expects.
Body
The indented block is the procedure to execute.
Return
return sends a value back to where the function was called.
Remember that everything in Python is an object.
Objects have methods, which are functions attached to objects and defined with their type in mind.
Mutability describes whether objects themselves can be changed.
This is different from changing the object that a name points to.
Basic types
Often immutable.
Example: text = text.lower()
Data structures
Often mutable.
Example: items.append("new")
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
True
Both names point to the same object. If we need a separate list, we make a copy.
Control structures allow code to make decisions and repeat procedures.
In Python, spacing is part of the syntax.
This is inside the if statement.
This prints either way.
In some other languages, code blocks use braces. Python uses indentation.
While some condition is true, do something.
The condition needs to somehow become false, or this will run forever.
For each item in some sequence, do something.
This has a natural end point, unlike the more general while loop.
We often use the same control structures in the same ways.
Language designers sometimes give us syntax that makes common patterns easier.
['this', 'list', 'has', 'items', 'in', 'caps']
Open notebooks/0c_python2.ipynb.
You now know all of the basics of programming. (Whoa!)
The core set of things that we need to do to write computations is surprisingly short. There’s a lot beyond this, but it’s about efficiency, productivity, convenience, and style.