Monday, October 22, 2012

PY-02: Elements of a Python Program, Part 2

Continuing from where I left off at the last post, "PY-01: Elements of a Python Program, Part 1", I will explain some more important elements that make up a Python program. These foundational elements MUST be learned, so pay attention!

Straight-line programs

These are the most basic of the programs that one could possibly code. A straight-line program is exactly what the name portrays -- a program that runs in a straight line, from start to finish. It does so by executing every command in order, one time. The alternatives to such programs would be one with conditionals which allow for options, or paths, for the program to follow; and branching programs, which are the limited cousins of conditionals.

Branching programs

This type of program is very similar to the straight-line program, with the exception that there are different paths available to choose from. When the program reaches a spot in the code where there are multiple options to choose from, we say it's branching off (like tree branches). Unfortunately, this means we have to manually code every single path it can take, and that it is bogged down by the size of data evaluated.


The conditional is huge in programming. Without it, we would have to program each and every possible variation that we could think of (and even then, we'd end up missing a ton of possibilities!). Not to mention, the program would be tedious and long. With a conditional, however, we can write a succinct piece of code that allows the program to execute that code for all possibilities.

Such conditionals are "if", "else", and "elif". They may not make much sense right now, but they will soon, trust me.


A looping construct is a piece of code that allows for expressions to be executed more than once. This is done by utilizing conditionals that redirect the program back to the beginning when certain conditions are met (usually, when trying to find a specific answer using a program, these "certain conditions" are when the answer has not been found). Loops need to have an end, or else they run until they crash.

Print command

The print command is a piece of code that will make expressions appear as they are in the shell. Here is an example of the print command:

>>>print "Text to be printed"
Text to be printed
Simple, right? This command is a tool that will be invaluable to your programming, so be prepared to use it often!

Next post, PY-03, I will go a bit more in-depth as to the use of programs for solving problems, utilizing most (if not all!) of the elements explained so far!

No comments:

Post a Comment