Introduction to Computer Programming

Loops

“Loops” is a generic term for a programming construct that repeats code until a given condition is met.  There are two main types we will look at:

For Loop:  Python’s for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence. For example:

More complicated For-Loops and Conditionals

myString = "Intro. Programming"

count = 0

for letter in myString:  

    if letter == "r":

        print "I found an ", "r", "in position ", count

        count +=1

    else:                                        

        count +=1

        print "'r' was not found at this location"


You can also specify how long you want something to repeat in with the list: range()

print range(0,10)

print "Here are the first powers of 3"

for i in range(0,10):

    print "3 to the ", i,"th power is", 3**i

While Loop:  Python’s while statement executes given code while a condition is met (be careful about infinite loops!).  A break statement executed in the first block terminates the loop without executing the else clause’s block A continue statement executed in the first suite skips the rest of the block and goes back to testing the expression.

Code

Output-Completed by student

myVariable = 1

while myVariable < 10:

    print myVariable

    myVariable +=1

1

2

3

4

5

6

7

8

9

Be careful about infinite loops (codeskulptor will timeout after about 3 seconds)- Ctrl + C in 2.7

Code

Output-Completed by student

myVariable = 1

while myVariable < 10:

    print myVariable

    myVariable -=1

Infinite Loop

While loops can work with conditionals and have different options for exiting the loop.  

Code

Output-Completed by student

myVariable = 1

while myVariable < 10:

    if myVariable %2 ==0:

        print myVariable, "is Even"

        myVariable +=1

    elif myVariable ==7:

        print "Break out now!"

        break   

    else:

        print myVariable, "is Odd"

        myVariable +=1

1 is Odd
2 is Even
3 is Odd
4 is Even
5 is Odd
6 is Even
Break out now!

How can loops help us design games?  A silly example….

Code

Output (5 “Y’s”) and 1 N

gameOn = True

score = 0

while gameOn == True:

    choice = input("Do you want to continue? (Y/N)")

   

    if choice.upper()[0] == "Y":

        print "Thanks for continuing"

        score +=1

        print "Your score is ,", score

        if score == 5:

            print "Winner!!"

            #gameOn = False

            break    

    else:

        print "Goodbye then..."

        #gameOn = False

        break

5Y

Thanks for continuing
Your score is , 1
Thanks for continuing
Your score is , 2
Thanks for continuing
Your score is , 3
Thanks for continuing
Your score is , 4
Thanks for continuing
Your score is , 5
Winner!!

4Y and 1N

Thanks for continuing
Your score is , 1
Thanks for continuing
Your score is , 2
Thanks for continuing
Your score is , 3
Thanks for continuing
Your score is , 4
Goodbye then...

Lists

Python knows a number of compound data types, used to group together other values. The most versatile is the list, which can be written as a list of comma-separated values (items) between square brackets. List items need not all have the same type.

Example:  

Code

Output-Completed by student

myList = [1, "cat", 3.5, True]

for thing in myList:

    print thing, "is a", type(thing)

1 is a <type 'int'>
cat is a <type 'str'>
3.5 is a <type 'float'>
True is a <type 'bool'>

We can turn things into lists with the list() method.

For example, start with the string:  "Computer"

print list("Computer"): ['C', 'o', 'm', 'p', 'u', 't', 'e', 'r']

This can also be indexed like a string:  list("Computer")[2] = _m_

There are lots of methods on lists:


Given the following list:  myList = ["a", "b", "c", "d"]

Method Name

What it does

Code

Output-Completed by student

Value index

Sets or calls (with = sign) list member value

myList[2] = “H”

print myList

['a', 'b', 'H', 'd']

Append

Adds an object to the end of a list

myList.append("e")

print myList

['a', 'b', 'c', 'd', 'e']

Extend

Adds multiple objects to the end of a list (will split up the object being added)

myList.append("dog")

print myList

myList.extend("dog")

print myList

['a', 'b', 'c', 'd', 'dog']
['a', 'b', 'c', 'd', 'dog', 'd', 'o', 'g']

Insert

Inserts an item into a list at a given position (changes the length)

myList.insert(0,"z")

print myList

['z', 'a', 'b', 'c', 'd']

Remove

Removes an item from a list (NOT all of them) remove the first b it finds.

myList.remove('b')

print myList

['a', 'c', 'd']

Pop

Removes an item at a given position (changes the length)

myList.pop(1)

print myList

['a', 'c', 'd']