Python Programming

Lecture 5 Iteration, Function

5.1 Iteration with Dictionary, Tuple, String

  • Looping Through a Dictionary
  • Looping Through All Key-Value Pairs


user = {
    'first': 'enrico',
    'last': 'fermi',
    }
for key, value in user.items():
    print("Key: " + key, "Value: " + value)

#for key, value in list(user.items()):

#output
Key: first Value: enrico
Key: last Value: fermi
  • Looping Through All the Keys in a Dictionary


favorite = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil': 'python',
    }
for name in favorite.keys():
    print(name.title())

#for name in favorite:
#for name in list(favorite.keys()):

#output
Jen
Sarah
Phil
Edward

favorite = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil': 'python',
    }
friends = ['phil', 'sarah']

for name in favorite.keys():
    if name in friends:
        print(name.title()+" "+favorite[name])

#output
Sarah c
Phil python
  • Looping Through All Values in a Dictionary


favorite = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil': 'python',
    }
for language in favorite.values():
    print(language.title())

#for language in list(favorite.values()):

#output
Python
C
Python
Ruby

favorite_languages = {
    'jen': ['python', 'ruby'],
    'sarah': ['c'],
    'edward': ['ruby', 'go'],
    'phil': ['python', 'haskell'],
    }
for name, languages in favorite_languages.items():
    print(name.title() + "'s favorite languages are:")
    for language in languages:
        print("\t" + language.title())

#output
Jen's favorite languages are:
    Python
    Ruby
Sarah's favorite languages are:
    C
Edward's favorite languages are:
    Ruby
    Go
Phil's favorite languages are:
    Python
    Haskell
  • Summary


d = {'a':1, 'b':2}
for x,y in d.items():
    pass
for x in d.keys():
    pass
for y in d.values():
    pass

d = {'a':1, 'b':2}
print(list(d.items()))
print(list(d.keys()))
print(list(d.values()))

#output
[('a', 1), ('b', 2)]
['a', 'b']
[1, 2]
  • Example 1: Sorting Strings by their letters

  • Comparing lists, tuples and strings


>>> [0, 1, 2] < [0, 3, 4]
True
>>> (0, 1, 2) < (0, 3, 4)
True
>>> (0, 1, 2000000) < (0, 3, 4)
True
>>> 'apple' > 'banana'
False
>>> 'flow' > 'flight'
True
  • Sorting lists, tuples and strings


>>> t=[[2, 4], [0, 1, 2], [0, 3, 4]]
>>> t.sort()
>>> print(t)

[[0, 1, 2], [0, 3, 4], [2, 4]]

>>> t=[(2, 4), (0, 1, 2), (0, 3, 4)]
>>> t.sort()
>>> print(t)

[(0, 1, 2), (0, 3, 4), (2, 4)]

>>> t=['flight', 'flow', 'flask']
>>> t.sort()
>>> print(t)

['flask', 'flight', 'flow']
  • Mixture


>>> t=[(1,'flight'), (2,'flow'), (2,'flask')]
>>> t.sort()
>>> print(t)

[(1, 'flight'), (2, 'flask'), (2, 'flow')]
  • The length of lists, dictionaries tuples and strings
  • The len function works on all of them

  • 
    >>> x = ['apple', 'banana', 'orange']
    >>> len(x)
    3
    
    >>> x = {'one': 'apple', 'two': 'banana', 'three': 'orange'}
    >>> len(x)
    3
    
    >>> x = ('apple', 'banana', 'orange')
    >>> len(x)
    3
    
    >>> x = 'orange'
    >>> len(x)
    6
    

txt = 'but soft what light yonder window'
words = txt.split()
t = list()
for word in words:
    t.append((len(word), word))
print(t)

#output
[(3, 'but'), (4, 'soft'), (4, 'what'), (5, 'light'), 
(6, 'yonder'), (6, 'window')]

t.sort(reverse=True)
res = list()
for length, word in t: #double element iteration
    res.append(word)
print(res)

#output
['yonder', 'window', 'light', 'what', 'soft', 'but']
  • Example 2: counting letters

  • Suppose you are given a string and you want to count how many times each letter appears.


word = 'banana'
count = 0
for letter in word:
    if letter == 'a':
        count = count + 1
print(count)

word = 'brontosaurus'
d = dict()
for c in word:
    if c not in d:
        d[c] = 1
    else:
        d[c] = d[c] + 1
print(d)

{'b': 1, 'r': 2, 'o': 2, 'n': 1, 't': 1, 's': 2, 'a': 1, 'u': 2}
  • Dictionaries have a method called get that takes a key and a default value.


>>> counts = { 'chuck' : 1 , 'annie' : 42, 'jan': 100}
>>> print(counts.get('jan', 0)) #0 is the default value
100
>>> print(counts.get('anni', 1550))
1550
  • We can use get to write our histogram loop more concisely.


word = 'brontosaurus'
d = dict()
for c in word:
    d[c] = d.get(c,0) + 1
print(d)
  • .count()

aList = [123, 'Google', 'Runoob', 'Taobao', 123]
print(alist.count(123))

aList = (123, 'Google', 'Runoob', 'Taobao', 123)
print(alist.count(123))

x = 'Taobao'
print(x.count('a'))
  • Dictionary has no counting method. If you want to count something, please convert the dictionary to a list at first.

5.2 Functions (2)

return multiple values, mutable vs. immutable, variable scope

  • If we want to return multiple values, the function return a tuple.


def addtwo(a, b):
    added = a + b
    return a, b, added

x = addtwo(3, 5)
print(x)

#output
(3, 5, 8)
  • A function can return any kind of value you need it to, including more complicated data structures like lists and dictionaries.


def build_person(first_name, last_name):
    person = {'first': first_name, 'last': last_name}
    return person

musician = build_person('jimi', 'hendrix')
print(musician)

#output
{'first': 'jimi', 'last': 'hendrix'}
mutable vs. immutable
  • For immutable objects (number, string, tuple), the assignment inside a function cannot change the value of the variable outside the function even if the variable name inside is the same with the variable name outside.


def ChangeInt(a):
    a = 10

b = 2
ChangeInt(b)
print(b)

#output
2

############################
def ChangeInt(b):
    b = 10

b = 2
ChangeInt(b)
print(b)

#output
2

Examples


def ChangeInt(a):
    a = 10
    print(a)
    return a

b = 2
ChangeInt(b)
print(b) 
print(ChangeInt(b))

10
2
10
10
  • For mutable objects (list, dictionary), the assignment inside a function cannot change the value of the variable outside the function. (the same with immutable objects!)


def changeme(mylist):
   mylist = [1,2]
   print("inside: ", mylist)

 
x = [10,20]
changeme(x)
print("outside: ", x)

#output
inside:  [1, 2]
outside:  [10, 20]

  • However, the modification can change the value of the variable outside.


def changeme(mylist):
   mylist.extend([1,2])
   print ("inside: ", mylist)

 
x = [10,20]
changeme(x)
print ("outside: ", x)

#output
inside:  [10, 20, 1, 2]
outside:  [10, 20, 1, 2]

Variable Scope


def func():
    print(int) # build-in
func()

<class 'int'>

 
g_count = 0  # Global
def outer():
    o_count = 1  # Enclosing
    def inner():
        i_count = 2  # Local
  • Local$\rightarrow$Enclosing$\rightarrow$Global$\rightarrow$ Build-in

  • In Python, module, class, def, lambda can introduce new variable scope, if/elif/else/, try/except, for/while will not introduce new variable scope.


if True:
    msg = 'I am from Runoob'
print(msg) # We can use msg.

I am from Runoob

def test():
    msg_inner = 'I am from Runoob'
print(msg_inner) # error
  • local vs. global


total = 0 #global
def sum( arg1, arg2 ):
    total = arg1 + arg2 #local
    print ("Local variable: ", total)
    return total;

sum( 10, 20 )
print ("Global variable : ", total)

#output
Local variable:  30
Global variable :  0
  • The global and nonlocal keywords


num = 1
def fun1():
    global num  
    print(num) 
    num = 123
    print(num)
fun1()

#output
1
123

def outer():
    num = 10
    def inner():
        nonlocal num   
        # nonlocal keyword
        num = 100
        print(num)
    inner()
    print(num)
outer()

100
100

def outer():
    global num
    num = 10
    def inner():
        global num   
        num = 100
        print(num)
    inner()
    print(num)
outer()

100
100

num = 3                            
def outer():
    global num
    num = 10
    def inner():  
        num = 100
        print(num)
    inner()
    print(num)
outer()
print(num)

100
10
10

num = 3                            
def outer():
    num = 10
    def inner(): 
        nonlocal num 
        num = 100
        print(num)
    inner()
    print(num)
outer()
print(num)

100
100
3

a = 10
def test():
    a = a + 1
    print(a)
test()

Traceback (most recent call last):
  File "test.py", line 5, in 
    test()
  File "test.py", line 3, in test
    a = a + 1
UnboundLocalError: local variable 'a' referenced before assignment

a = 10
def test():
    global a 
    #or a=10 but it does not change the "a" outside
    a = a + 1
    print(a)
test()
print(a)

Example



if 1 == 1:
    name = "lzl"
print(name)

for i in range(10):
    age = i
print(age)

def func():
    name = "lzl"
print(name)

def func():
    name = "lzl"
func()          
print(name)
  • Two other examples for exercise.

Reminder: Pac-man game

Pac-man game

http://www.webpacman.com/

Summary

  • Iteration
  • Functions
  • Reading: Python for Everybody
    • Dictionaries Chapter 9.1, 9.3
    • Tuples Chapter 10.1-10.5, 10.7-10.8
    • Functions Chapter 4