Python Programming

Lecture 3 Iteration, Strings

3.1 Iteration (1)

1+2+3+...+100=?

The while statement


n = 5
while n > 0:
    print(n)
    n = n - 1
print('Blastoff!')
  1. Evaluate the condition, yielding True or False.

  2. If the condition is false, exit the while statement and continue execution at the next statement.

  3. If the condition is true, execute the body and then go back to step 1.

  • This type of flow is called a loop because the third step loops back around to the top.

  • We call each time we execute the body of the loop an iteration.

  • The body of the loop should change the value of one or more variables so that eventually the condition becomes false and the loop terminates.

  • If the loop repeats forever, it results in an infinite loop.


n = 10
while True:
    print(n)
    n = n - 1
print('Done!')
  • What will happen if you run this?

  • Ctrl+C to terminate it.

  • Finishing iterations with break


while True:
    line = input('>')
    if line == 'done':
        break
    print(line)
print('Done!')
  • Finishing iterations with continue


while True:
    line = input('> ')
    if line[0] == '#':
        continue
    if line == 'done':
        break
    print(line)
print('Done!')
  • Example 1: classify a list of numbers


number=None
numbers = [12,37,5,42,8,3]
even = []
odd = []
while len(numbers)>0:
    number = numbers.pop()
    if (number%2==0):
        even.append(number)
    else:
        odd.append(number)
print(even)
print(odd)
  • Example 2: Greatest common divisor


a = int(input('Enter your first number:'))
b = int(input('Enter your first number:'))
if a >= b:
    x = a
    y = b
else:
    x = b
    y = a
while y!=0:
    r = y
    y = x%y
    x = r
print(x)
  • Least common multiple?

  • Example 3: Finding prime numbers


i = 2
while i < 100:
    j = 2
    while j <= (i/j):
        if not i%j : 
            break
        j = j + 1
    if j > i/j: 
        print(i)
    i = i + 1

Definite loops using for

  • for statement works on the lists.


friends = ['Joseph', 'Glenn', 'Sally']
for x in friends: 
    print('Happy New Year:', x)
print('Done!')

#output
Happy New Year: Joseph
Happy New Year: Glenn
Happy New Year: Sally
Done!
  • We call the while statement an indefinite loop because it simply loops until some condition becomes False, whereas the for loop is looping through a known set of items so it runs through as many iterations as there are items in the set.

  • In particular, x is the iteration variable for the for loop. The variable x changes for each iteration of the loop and controls when the for loop completes. The iteration variable steps successively through the three strings stored in the friends variable.

Loop patterns

These loops are generally constructed by:
  • Initializing one or more variables before the loop starts
  • Performing some computation on each item in the loop body, possibly changing the variables in the body of the loop
  • Looking at the resulting variables when the loop completes
  • The concept of looping is important because it's one of the most common ways a computer automates repetitive tasks.

  • The indentation errors are common.

  • Python uses indentation to determine when one line of code is connected to the line above it. Some languages require the "end" statement.

  • Always indent the line after the for statement in a loop.


friends = ['Joseph', 'Glenn', 'Sally']
for friend in friends: 
print('Happy New Year:', friend)
print('Done!')

#output
IndentationError: expected an indented block
  • Forgetting to indent additional lines


friends = ['Joseph', 'Glenn', 'Sally']
for friend in friends: 
    print('Happy New Year:', friend)
print('Looking forward to seeing you,', friend)

#output
Happy New Year: Joseph
Happy New Year: Glenn
Happy New Year: Sally
Looking forward to seeing you, Sally
  • This is a logical error.

  • Indenting unnecessarily


message = "Hello Python world!"
    print(message)

#output
IndentationError: unexpected indent
  • Indenting unnecessarily after the loop


friends = ['Joseph', 'Glenn', 'Sally']
for friend in friends: 
    print('Happy New Year:', friend)
    print('Looking forward to seeing you!')

#output
Happy New Year: Joseph
Looking forward to seeing you!
Happy New Year: Glenn
Looking forward to seeing you!
Happy New Year: Sally
Looking forward to seeing you!

3.2 Iteration (2)

  • Now we answer the question. How to calculate 1+2+...+100?

  • First, we need to generate a series of numbers in a list.


for value in range(1,5): 
    print(value)

#output
1
2
3
4

type(range(1,5))

#output
range

numbers = list(range(1,6))
print(numbers)

#output
[1, 2, 3, 4, 5]

numbers = list(range(6))
print(numbers)

#output
[0, 1, 2, 3, 4, 5]

numbers = list(range(1, 10, 2))
print(numbers)

#output
[1, 3, 5, 7, 9]

numbers = list(range(10, 1, -2))
print(numbers)

#output
[10, 8, 6, 4, 2]

total=0
for value in range(1,101):
    total=value+total
print(total)
  • Make a list of even numbers


even_numbers = list(range(2,11,2))
print(even_numbers)

#output
[2, 4, 6, 8, 10]

squares = []
for value in range(1,11):
    square = value**2
    squares.append(square)
print(squares)

#output
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Example 1: len()


count = 0
for itervar in [3, 41, 12, 9]:
    count = count + 1
print('Count: ', count)

Example 2: sum()


total = 0
for itervar in [3, 41, 12, 9]:
    total = total + itervar
print('Total: ', total)

Example 3: max(), min()


largest = None
for itervar in [3, 41, 12, 9, 74, 15]:
    if largest is None or itervar > largest :
            largest = itervar
print('Largest:', largest)

#output
Largest: 74

Example 4: .reverse()


reverselist = []
count = 0
x = [3, 41, 12, 9, 74, 15]

for itervar in x:
    count = count + 1
for i in range(count-1, -1, -1):
    reverselist = reverselist + [x[i]]
print(reverselist)

#output
[15, 74, 9, 12, 41, 3]
  • Sorting is a much more complicated and interesting topic. We will study that at a later time.

Nested Loops


for iterating_var in sequence:
   for iterating_var in sequence:
      statements(s)
   statements(s)

while expression:
   while expression:
      statement(s)
   statement(s)

x = []
for i in range(1,4):
    x.append([])
    for j in range(1,4):
        x[i-1].append(1)
print(x)

#output
[[1, 1, 1], [1, 1, 1], [1, 1, 1]]

x = []
for i in range(1,4):
    x.append([])
    for j in range(1,i+1):
        x[i-1].append(1)
print(x)

#output
[[1], [1, 1], [1, 1, 1]]

for i in range(1,4):
    for j in range(i):
        print(i,end=" ")
    print()

#output
1 
2 2 
3 3 3 
  • The default value of end is \n meaning that after the print statement it will print a new line. So simply stated end is what you want to be printed after the print statement has been executed.


for i in range(1,4):
    for j in range(i):
        print(i,end="+")
    print()

#output
1+
2+2+
3+3+3+

3.3 Strings

  • We have learned some methods of strings: .upper(), lower(), .title(), .lstrip(), .rstrip(), .strip()

  • A string is a sequence of characters. The elements of a string are characters. Empty string ''. You can access the characters one at a time with the bracket operator:

  • 
    >>> fruit = 'banana'
    >>> letter = fruit[1]
    >>> print(letter)
    a
    
    >>> len(fruit)
    6
    
  • iteration and conditional execution

  • 
    fruit = 'banana'
    index = 0
    while index < len(fruit):
        letter = fruit[index]
        print(letter)
        index = index + 1
    
    for char in fruit:
        print(char)
    

Debugging


while True:
    line = input('> ')
    if line[0] == '#':
        continue
    if line == 'done':
        break
    print(line)
print('Done!')

> hello there
hello there
>  #blank
 #blank
> print this!
print this!
>
Traceback (most recent call last):
File "copytildone.py", line 3, in <module>
if line[0] == '#':
IndexError: string index out of range
  • Solution

while True:
    line = input('> ')
    if line.startswith('#'): 
        continue
    if line == 'done':
        break
    print(line)
print('Done!')

while True:
    line = input('> ')
    if len(line) > 0 and line[0] == '#': 
        continue
    if line == 'done':
        break
    print(line)
print('Done!')
  • String slices


>>> fruit = 'banana'
>>> fruit[1:3]
'an'
>>> fruit[3:]
'ana'
  • Strings are immutable


>>> greeting = 'Hello, world!'
>>> greeting[0] = 'J'
TypeError: 'str' object does not 
support item assignment
  • The in operator


>>> 'a' in 'banana'
True
>>> 'seed' in 'banana'
False
  • Some useful string methods


>>> stuff = 'Hello world'
>>> dir(stuff)

['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__',
 '__eq__', '__format__','__ge__', '__getattribute__', '__getitem__', '__getnewargs__', 
 '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__',
 '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__',
 '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__',
 '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 
 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 
 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 
 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust',
 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 
 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith',
 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

>>> help(str.title)

Help on method_descriptor:

title(...)
    S.title() -> str
    
    Return a titlecased version of S, i.e. words start with title case
    characters, all remaining cased characters have lower case.
  • .find() searches for the position of a string in another string


>>> word = 'banana'
>>> index = word.find('a')
>>> print(index)
1
>>> word.find('na')
2
>>> word.find('na', 3)
4
  • .startwith() returns the boolean value


>>> line = 'Have a nice day'
>>> line.startswith('h') 
False
>>> line.lower()
'have a nice day'
>>> line.lower().startswith('h')
True
  • Parsing strings


>>> data = 'From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008'
>>> atpos = data.find('@')
>>> print(atpos)
21
>>> sppos = data.find(' ',atpos)
>>> print(sppos)
31
>>> host = data[atpos+1 : sppos]
>>> print(host)
uct.ac.za
  • .split() break a sentence into words and make a list


>>> s = 'pining for the fjords'
>>> t = s.split()
>>> print(t)
['pining', 'for', 'the', 'fjords']
>>> print(t[2])
the
  • One can break a word into letters.


>>> s = 'spam'
>>> t = list(s)
>>> print(t)
['s', 'p', 'a', 'm']
  • Format operator $%$

    It allows us to construct strings, replacing parts of the strings with the data stored in variables.


number = 42
print('I have spotted %d camels.' % number)

#output
I have spotted 42 camels.
  • What if we do not use format operator?


number = 42
print('I have spotted number camels.') #it is wrong.
print('I have spotted '+str(number)+' camels.') #not simple
  • If there is more than one format sequence in the string, the second argument has to be a tuple.


print('In %d years I have spotted %g %s.' % (3, 0.1, 'camels'))

#output
In 3 years I have spotted 0.1 camels.
  • The number of elements in the tuple must match the number of format sequences in the string. The types of the elements also must match the format sequences:


'%d %d %d' % (1, 2)
#output
TypeError: not enough arguments for format string

'%d' % 'dollars'
#output
TypeError: %d format: a number is required, not str'
  • .format()

print('In {} years I have spotted {} {}.' .format(3, 0.1, 'camels'))
#output
In 3 years I have spotted 0.1 camels.

print('In {0} years I have spotted {1} {2}.' .format(3, 0.1, 'camels'))
#output
In 3 years I have spotted 0.1 camels.

print('In {1} years I have spotted {0} {2}.' .format(3, 0.1, 'camels'))
#output
In 0.1 years I have spotted 3 camels.

String: Summary

  • The elements of a string are characters. Empty string ''

  • Features: Ordered, Immutable, Repeatable

  • Index and slice are the same with that of lists.

  • in operator shows the boolean value for whether a string contains a given string.

  • .upper(), lower(), .title(), .lstrip(), .rstrip(), .strip()

    .find(), .startwith(), .split() (list('string') and list())

  • Format operator: %d integer, %g float, %s string (use () for more than one format sequence), .format()

Summary

  • Iteration
  • Strings
    • Reading: Python for Everybody Chapter 5, 6