LPTHW Exercises 35 - 39 


While loops, Lists, Tuples, and Dictionaries

Review


  1. Boolean Expressions
  2. IF/ELSE Statements
  3. Lists
  4. For Loops
  5. List Indexing and slicing

Exiting a For Loop


We can abruptly exit a for loop or alter it's flow
with break and continue statements respectively

 for i in range(10):     if i == 2:        continue    elif i == 5:        break    print i

WHILE LOOPS


Hybrid of Conditional Statements (IF/ELSE and LOOPS)

 while [boolean expression ==True]:
    # execute this loop body
    # over and over again 


While loops are not used very often.
Typically implemented when we want to loop 
an undefined number of times

Extra info: List Mutability


Integers, Strings, and Booleans are immutable
This means that their value can't be changed
To update variables, values must be reassigned

   a = "Some random string"   a[0] = "z"    ### This will fail because strings can't be changed   a = "z" + a[1:]     ### we must create a new string and re-assign to a


Lists, on the other hand, are mutable
Can be changed (items added, removed, changed, etc)
sort, append, remove, etc all change the actual list

Extra Info:  Tuples


A very similar data type to Lists

A tuple is an ordered sequence of items

Instead of brackets, tuples are created with parentheses

We've seen tuples before with string interpolation
"This is %s an example of %s"  % ("good", "tuples")  my_sample_tuple = (1, "sample", 4, 9)

Difference with lists is that tuples are IMMUTABLE

Exercise 39:  Dictionaries


Dictionaries are similar to Lists
They are mutable
Assignment and indexing is similar

They are NOT ordered

Instead they are lookup tables with keys and values
Each key is associated with a value
With the key, you "look up" that value


Exercise 39 Continued

  chores = {"Monday": "rake yard", "Tuesday": "dentist appointment"}  print chores["Monday"]    # dictionaries have built-in functions, just like Lists  print chores.keys()  print chores.items()
for day, assignment in chores.items(): print "On %s, I will %s" % (day, assignment)
chores["Wednesday"] = "wash clothing" print chores
thursday_chore = chores.get("Thursday", "I have nothing planned") print thursday_chore

Object Oriented Programming: classes and objects

By benjaminplesser

Object Oriented Programming: classes and objects

  • 917