Subsection 1.5.2 Preview of Control Structures
We won’t get too much into Python control structures yet, but it is good to mention them early to give you a taste for what you can do with the language! If these make sense to you now, that’s great! However, we don’t expect you to understand these yet - understanding will come later.
First we have structures that allow us to iterate over something. We can look at strings character-by-character or lists item-by-item until we’ve reached the end of them by using something called a
for
loop. This is a type of repetition instruction. Run the program below to see what the output to the console is:
We can also iterate without a definite stopping point with
while
loops (another type of repetition instruction). You might use this if you want to receive input from the user in your program but you don’t know how long it’ll take for them to be done entering new input. Run the program below and add some items to a grocery list:
Note that in the example above, you could run this program repeatedly and give it a different number of items each time you run it. Also note the cancel button does not do anything at this time. That is because we haven’t programmed it to do anything!
Other structures will allow us to only run parts of our programs or only do some task if a certain set of conditions are found. Conditionals, as they’re called, allow us to do that. Check out how adding conditionals to our code can change what we can write about regarding grocery shopping.
Checkpoint 1.5.1.
a sequence of instructions that specifies how to perform a computation.
It is just step-by-step instructions that the computer can understand and execute. Programs often implement algorithms, but note that algorithms are typically less precise than programs and do not have to be written in a programming language.
something you follow along at a play or concert.
True, but not in this context. We mean a program as related to a computer.
a computation, even a symbolic computation.
A program can perform a computation, but by itself it’s not one.
the same thing as an algorithm.
Programs often implement algorithms, but they are not the same thing. An algorithm is a step by step list of instructions, but those instructions are not necessarily precise enough for a computer to follow. A program must be written in a programming language that the computer knows how to interpret.