Home Lesson 1 Lesson 3 Lesson 4 Lesson 5 Lesson H

Lesson 2 - Loops and Control Structures

So far, we have seen some different kinds of variables and used some basic functions to manipulate them. Everything has been executed in a linear fashion (where line 3 follows line 2 follows line 1)

The real power of programming comes from the concepts of control structures and conditional loops. These are ways of dynamically answering the question “what line of code should be executed next”?

It is useful to understand the concept of a block before dealing with conditions. A block is a section of code that gets executed together. 

It can be a single line or many thousand lines. In many programming languages, blocks are demarcated with parentheses. In python, however, blocks are demarcated by indentation (tabbing). So, for example, all the code in the attached lesson1solution.py file is in a single block because it is all at the same tab-level.

For this lesson, instead of only running code from the python shell, we will run code from independant .py files.

Open the python shell and and go:

File-->New Window

Type in some code:

print 'test' (or whatever) and save the file wherever you want. It must have extension .py.

Now hit F5 or click Run-->Run Module. The output will still be in the python shell but now we can run multiline code much easier. Examples in this lesson should be followed in this fashion.

-----------------------------------------------------------------------------------------------------

Introduction to Functions 

Psuedo-code (this will not evaluate):

if somethingIsTrue:
    do everything at this
    level of
    indentation
else:
    this block will evaluate if somethingIsTrue
    is, in fact, not true

These are relatively easy to understand. The if keyword is a condition that says the following block of code will be executed if (and only if) something evaluates to being true (notice the semicolon after the “something”).

The block under the else statement will evaluate if whatever was tested in the if above it is not true (confused yet?)

It's worth breifly reflecting on what true means in python. As opposed to an abstract metaphysical principle, true in a pythonic context is very similar to the number 1 (and false to the number 0). In fact if you try the following line (/block) of code:

print True + True

You will retrieve an output of “2”. Python considers this identical to adding two integer 1 values together.

So, let's see if in action. Consider the following lines of code:

trueVal = True
falseVal = False
if trueVal:
    print 'trueVal seems to be true'
if falseVal:
    print 'so does falseVal'

This code is saying:

-First create a variable called 'trueVal' and set it contain the value 'True' (identical to the number 1)

-Next create a variable called 'falseVal' and set it contain the value 'False' (identical to the number 0) 

-if the value contained in the variable trueVal evaluates to being true, excecute everything in the child block (sectioned by everything under it at the same indentation level) 

-print 'trueVal seems to be true' is the block under 'if trueVal'

-same for the next 2 lines but with falseVal

You should see the output “trueVal seems to be true”. This means that the block under “if trueVal:” has executed but the block under “if falseVal:” has not executed (because falseVal is, um, false)

 

Other things that evaluate to being true:

-strings that are not empty: 'hello world'

-integers or floats that are not zero: 4.7

-arrays or dictionaries that are not empty: ['hello world', 4.7]

-two variables that are identical are compared with each other using the double equals operator:  'hey'=='hey'

-some mathematical test that is correct:  5<9 (this uses the 'less than' < operator)

-test for exclusion in an array using the not in keyword: 4.7 in ['hello world', 4.7]


Other things that evaluate to being false:

-strings that are empty: "";

-integers or floats that are zero: 0

-arrays or dictionaries that are empty: []

-two variables that are not identical are compared with using the double equals operator:  'hey'=='friend'

-some mathematical test is false:  34>109 (this uses the 'greater than' > operator)

-test for exclusion in an array using the not in keyword: 4.7 not in ['hello world', 4.7]


One more thing to mention at this stage is that blocks can be "nested" within each other. In other words we can have blocks within blocks within blocks.

Consider the following code:

trueVal = True 
falseVal = False 
if falseVal: 
    if trueVal:
        print 'trueVal seems to be true' 

This time, nothing will be outputted because the 'if trueVal' line of code exists in a block under 'if falseVal' which means it will never be executed.

-----------------------------------------------------------------------------------------------------

The For and While Loops

For and while loops are fundamental to programming.

They are fairly similar in functionality and both very simple to use in python. 

The for loop is really just a code saving version of the while loop.

What they both are saying is 'keep executing the block under this statement if something evaluates to being true'.

For this lesson we will just deal with the for loop. Consider the following code:

for x in range(4): 
    print x

You should see the ouput:

0

1

2

3

range(someNumber) is a function that returns an array of every number from 0 --> someNumber-1

This means that the highlighted exaple is therefore identical to:

for x in range([0, 1, 2, 3] ): 
    print x

The general syntax when using a for loop is therfore:

for variable in array

The variable (x in the highlighted example, will store the appropriate value as it iterates (steps through) the array.

So in the above example, in the first iteration x==0, in the second x==1 and so on.

Let's try a more complicate combination of some of the previously defined functions and conditons. Consider the following code:

aTinyVar = 0.001
if aTinyVar < 1:
    someWords = ['these', 'are', 'strings', 'in', 'an', 'array']
    for x in someWords:
        if len(x) > 3:
            print x
        else:
            print '<--'
    print 'finished'

This should output:

'these'

'<--'

'strings'

'<--'

'<--'

'array'

'finished'

First, a variable is declared with float 0.001. It is smaller than 1 so the if statement evaluates to being true.

Next an array called someWords is created. For every word/string in someWords, if the length of that word (remember strings can be tested for lengths just like arrays) then the string is printed, if not then '<--' is printed. The final line print 'finished' is on the same indentation level as the for loop, so it is the next line evaluated after the for loop has finished.

-----------------------------------------------------------------------------------------------------

LESSON 2 TASKS:

  • create an array or a string that contains all the vowels.

  • create code that prints all consonants in your name (hint, you should use a for loop and the keywords not in instead of just in)

  • adapt your code to print all vowels and print 'this was a consonant' if it hits a consonant (you may have noticed that there are multiple ways to achieve the same goal here)

-----------------------------------------------------------------------------------------------------

lesson2_tasks.py