ISYS90088
Introduction to Application
Development
Week 9 – Contd. from week 8 on Dictionaries;
Introduction to Functions
Week 10: Contd. with functions
Semester 2 , 2018
Dr Antonette Mendoza
s
1
Other Dictionary methods: pop
• Use the built in method called pop
• When executed, it outputs the value associated with the
specific key and removes it from the dict.
Syntax:
dictionary_name.pop(key, default)
Example:
>>> employee_record = {‘name’:’kevin’, ‘Age’: 43,
‘ID’:23145, ‘payrate’:24.99}
>>> employee_record.pop(‘name’)
‘kevin’
>>> employee_record
{‘payrate’: 24.99, ‘ID’: 23145, ‘Age’: 43}
>>>
2
apple
高亮
pop: 从dict 里面指定一个specific key 移除。
Other Dictionary methods: popitem
• Use the built in method called popitem
• When executed, it outputs a selected key-value pair, and it
removes that key-value pair from the dict. (front of the
list/dict)
Syntax:
dictionary_name.popitem()
Example:
>>> employee_record
{‘payrate’: 24.99, ‘name’: ‘kevin’, ‘ID’: 23145,
‘Age’: 45}
>>> employee_record.popitem()
(‘payrate’, 24.99)
>>> employee_record.popitem()
(‘name’, ‘kevin’)
>>> employee_record.popitem()
(‘ID’, 23145) 3
apple
高亮
popitem:从dict 里面指定一组key-value移除。
4
Recap -Traversing: using list and dict methods
>>> employee_record = {‘name’:’kevin’,
‘Age’: 43, ‘ID’:23145, ‘payrate’:24.99}
>>> list(employee_record.keys())
[‘payrate’, ‘name’, ‘ID’, ‘Age’]
>>> list(employee_record.values())
[24.99, ‘kevin’, 23145, 43]
>>> list(employee_record.items())
[(‘payrate’, 24.99), (‘name’, ‘kevin’),
(‘ID’, 23145), (‘Age’, 43)]
apple
高亮
如何做到dic covert to list
Note: defaultdict when working with lists
and dictionaries
• It is easy to group a sequence of key-value pairs into a dictionary of lists
using defaultdict from a collections library:
>>> from collections import defaultdict
>>> s = [(‘yellow’, 1), (‘blue’, 2), (‘yellow’, 3),
(‘blue’, 4), (‘red’, 1)]
>>> d = defaultdict(list)
>>> for k, v in s:
… d[k].append(v)
…
>>> d.items()
[(‘blue’, [2, 4]), (‘red’, [1]), (‘yellow’, [1, 3])]
• When each key is encountered for the first time, it is not already in the
mapping; so an entry is automatically created using the default_factory
function which returns an empty list.
• The list.append() operation then attaches the value to the new list.
When keys are encountered again, the look-up proceeds normally (returning
the list for that key) and the list.append() operation adds another value
to the list.
5
apple
高亮
defualtdict(?)
convert list to dic
apple
下划线
这算不算一个 list of tuples
Example: creating a dict from a list using
append
from collections import defaultdict
employee_list = [(‘yosh’,23,2001), (‘farah’, 22,
2010), (‘matt’, 34, 2000)]
#you can take a list of tuples and make it #into a
dict with key-value pairs
#start with an empty dict, start a for loop #and
append values to a key
d1 = defaultdict(list)
for key, age, start_date in employee_list:
d1[key].append(age)
d1[key].append(start_date)
print(d1, d1.items(), d1.values())
6
apple
高亮
output:
defaultdict(
dict_items([(‘yosh’, [23, 2001]), (‘farah’, [22, 2010]), (‘matt’, [34, 2000])])
dict_values([[23, 2001], [22, 2010], [34, 2000]])
apple
下划线
d1.items 应该是list的表达形式
Dictionary of dictionaries
• In general no matter how many dictionaries are there inside dictionary
like n level dictionaries but you can always get it by the path.
For example,
d[‘dictionary1’][‘dictionary2’][‘dictionary3’]….[‘item1’]
• Inner dictionary can be accessed as: dictA[primary key][secondary key]
Example:
>>> dictA = {‘a’:{‘b’:10,’c’:20},’d’:{‘b’:30,’c’:40}}
>>> dictA[‘a’][‘c’]
20
• So, dict[‘a’][‘b’] will give you the value corresponding to inner
dictionary’s ‘b’ key.
• Nested dictionaries can be accessed just like we access the nested lists
with the only difference that in lists, we use indexing whereas in
dictionaries we do it via keys.
7
apple
下划线
dic of dictionaries:
{‘key’:{‘inner key’:10,”inner key1″:20},’key 1′:{},etc}
apple
下划线
nested dic 和 nested list 的唯一不同是,list用index 而因为dict 没有order,所以用key
Functions
8
Functions
• What’s a function? It is a group of statements that
exist within a program for the purpose of performing
a task
Ø (much like in Maths) functions take a set of input
values, perform some calculation based on them,
and optionally return a value
Ø you have already seen and used many functions
by this stage, e.g.: str(), len(), sqr(), min(), max()…
9
apple
下划线
from p9, 我们开始讲functions
Functions: usefulness
• Simpler code
• Code re-use
• Better testing
• Faster development
• Easier facilitation of teamwork
10
apple
高亮
function 的五个好处
Functions: defining and calling
• The code for a function is known as a function
definition. To execute a function, you write a statement
that calls it.
• In order to define a function, we need:
Ø A function name (following same conventions as
other variable names)
Ø (optionally) a list of input variables
Ø (optionally) a UNIQUE output object (via return)
11
apple
下划线
写出functions的两个步骤:defining and calling
P12:
defining the code: 一个关键步骤是取名字,这个name通常是动词,有四个rules:
1. 禁止keywords
2. 没有空格
3. 以字母开始
4. case senstitive
P13
defining: example:
p14
calling: to execute a function when you define a function
for example:
defining:
def message():
print(‘this is a simple case’)
calling:
messge()
Functions: defining and calling
Function names should be:
• Descriptive enough so that anyone reading your code
can reasonably guess what the function does (prefer to
use verbs)
• Rules for naming:
Ø Cannot use python key words
Ø Cannot contain spaces
Ø First character must be letter; after the first character,
you may use leters, digits, underscore
Ø Case sensitive
12
Functions: defining
Basic syntax :
def
statement
statement
statement
Example:
def message():
print(‘this is a simple case’)
13
Functions: calling
• To execute a function, you must call the function.
Example:
def message():
print(‘this is a simple case’)
message()
14
Functions: main() and functions
# a function to perform something
#the main function that might use the function
def main():
message()
def message():
print(‘this is a simple case’)
#execute main function
main()
15
apple
下划线
main () and function
P16 examples:
output:
I have a message for you
this is Antonette
can you hear me
Good bye
# an alternative way #same output
def message():
print (“I have a message for you”)
print (“this is Antonette”)
print (“can you hear me”)
print (“Good Bye”)
message()
main () > def message() > message
p17 two functions example
这个例子就是说明了 我们为什么用 main:当我们有多个function同时需要excute的时候,in this case, melbourne and canberra are two messages, we define them and call main in the last.
Functions: simple examples
#This is a simple example to illustrate a function call
def main():
print(“I have a message for you”)
message()
print(‘Good bye’)
def message():
print(‘this is Antonette’)
print(‘can you hear me?’)
#call main program
main()
16
Example: two functions
Write two functions: one called melbourne() and another called
canberra(). The functions must accept from the user the number of
Small to Medium Enterprises (SME’s) in these two cities. It must
then print the number of SME’s in each of the cities.
def main():
melbourne()
canberra()
#defining the two function
def melbourne():
small_medium = input(“the no. in melbourne are:”)
print(‘SMES in melbourne =’, small_medium)
def canberra():
small_medium = input(“the no. in canberra are:”)
print(‘SMES in canberra =’, small_medium)
main()
17
Scope and local variables
• A variable’s scope is the part of a program in which
the variable may be accessed.
• Local variable: is created inside a function and
cannot be accessed by statements that are outside the
function.
– Different functions within a program can have same
variable names since the other functions cannot see or use
each others local variables.
– A local variable cannot be accessed by code that appears
inside a function at a point before the variable has been
created.
18
apple
下划线
local variable (?)
p19-p20 two examples
p19: 两个function可以重复使用同一个variable(birds)
p20: 但是一个local variable 不能使用其他的outside的statement(name)
name is the local variable of function get_name, so it cannot be accessed into the function main.
solution:
#p20 example:
def main ():
v = input (‘enter your name:’)
get_name(v)
def get_name(n):
print (‘hello’,n)
main()
#the incorrect coding
def main ():
get_name(v)
print (‘hello’,v)
def get_name(n):
n = input(‘enter your name:’)
get_name(n)
main()
这个回过头来看,其实就是为了引出 argument and parameter 的内容。
或者是已经被assign value 的variable (val)
the val =99 should be identified before print
solution: 两个statement 调换顺序
Example 1 (scope) – what happens here?
def main():
melbourne()
canberra()
#defining the functions
def melbourne():
birds = 1000
print(‘melbourne has’, birds, ‘birds’)
def canberra():
birds = 870
print(‘canberra has’, birds, ‘birds’)
# calling the main function
main() 19
Examples: 2 – what’s the problem here?
def main():
get_name()
print(‘hello’, name) #causes an error
def get_name():
name = input(‘enter your name:’)
main()
#another scope example – issue. A local variable cannot
be accessed by code that appears???? Why????.
def bad_function():
print(“the value is”, val) # causes an error
val = 99
bad_function()
20
Functions: passing arguments to functions
• A argument is any piece of data that is passed into a
function when the function is called.
• A parameter is a variable that receives an argument that
is passed into a function.
• Many times we send across pieces of information
(data) into a function and tasks are performed within
the function.
• And many times information is passed back from a
function to the main that called this function using a
return statement .
21
apple
下划线
argument:in the call sector ( always is the execute part (coding 从这里开始run). and then, pass through the argument to the
parameter:he parameter passes into function.
return: when we cannot use print statement, we can use return instead
p22: example:
the argument small_medium_melb is an argument (for example =20) pass into the parameter a and get the print () result.
p23 examples:
show_double(value): value is argument want to pass to function show_double, and in the function show_double(number):, number is the parameter that receive infor from value, and get the result.
p23-p26 的四个例子都是正序,就是从main function 运行到 sub function的
Another
way
of
wri8ng
the
previous
example
:
passing
argument
and
check
scope!
def melbourne(a):
print(‘SMES in melbourne =’, a)
def canberra(b):
print(‘SMES in canberra =’, b)
small_medium_melb = input(“the no. in melbourne are:”)
small_medium_canb = input(“the no. in canberra are:”)
melbourne(small_medium_melb)
canberra(small_medium_canb)
22
a
and
b
are
parameters
This
is
an
argument
that
is
passed
to
the
func8on
apple
附注
main():
后面四行是mian function
main()
这个example 是正序
Example: how to pass values
def main():
value = int(input(‘enter a number:’))
show_double(value)
def show_double(number):
result = number * 2
print(result)
main()
number
value
23
Functions: simple examples
# write a function to print the number of digits in a
number
def print_digits(n):
s = str(abs(n))
print (len(s) – (‘.’ in s))
# write a function to convert from Celsius to Fahrenheit:
def C2F(n):
print (9*n/5 + 32)
24
Functions: simple examples
# Print the number of digits in a number
def print_digits(n):
s = str(abs(n))
print (len(s) – (‘.’ in s))
def main():
v = float(input(‘enter a value:’))
print_digits(v)
main()
# Convert from Celsius to Fahrenheit:
def C2F(n):
print(9*n/5 + 32)
Now write the main function that calls this function?
25
Functions: simple examples
#Convert from Celsius to Fahrenheit:
def C2F(n):
print(9*n/5 + 32)
def main():
cels =
C2F(cels)
26
Functions and return statement
A value-returning function has a return statement that
returns a value back to the part of the program that called
it.
Syntax:
def
statement
statement
statement
return
27
apple
高亮
return statement
明天继续
end at 12.09pm/Thurs/week 10
start at 7.58am/Thurs/week 10
return statement:
return < expression>
P28
return 回来的东西:
string
boolean values
multiple values
P29 examples:
P30 example 2:
Functions and return statement
• The value of the expression that follows the key word
return will be sent back to part of the program that
called this function. This can be any value, expression,
or variable that has a value.
• A return statement can also send back:
– Strings
– boolean values
– multiple values
28
Examples 1: return statement
# write a program that converts
cenlius to farenheit
def C2F(n):
return 9*n/5 + 32
def main():
cels = int(input(‘enter a value in celcius:’))
f = C2F(cels)
print(f)
main() 29
apple
高亮
alternative(p26):
print(9*n/5 + 32)
apple
下划线
这个是最后一步么?这个顺序是怎么运行的
Examples 2: return statement
def main():
# get the user’s age
first_age = int(input(‘enter your age:’))
# get the users best friends age
second_age = int(input(‘enter your best friends age:’))
# get the sum of both ages
total = sum (first_age, second_age)
# display the total age
print(‘their total age is:’, total, ‘years old’)
#sum function accepts two int arguments & returns sum of those
arguments
def sum(num1, num2):
result = num1 + num2
return result
#call main function
main()
30
apple
下划线
apple
下划线
apple
附注
first age and second age are two arguments that pass into sum function, which means num1 and num2 are parameters. and then return the result back to arguments and then print the outcome.
Variables and “Scope” :
• Each function (call) defines its own local variable “scope”. Its
variables are not accessible from outside the function (call) – so
what happens in this example?
def subtract_one(k):
k = k – 1
return k
i = 0
n = subtract_one(i)
print(i)
print(n)
print(k)
31
Variables and “Scope” II
• Are
the
semantics
different
to
the
previous
slide?
def subtract_one(i):
i = i – 1
return i
i = 0
n = subtract_one(i)
print (i)
print(n)
print(k)
32
apple
高亮
local variable and scope
output:
-1
0
Traceback (most recent call last):
File “/Users/apple/Desktop/week 9 lecture .py”, line 159, in
print(k)
NameError: name ‘k’ is not defined
Try at home!
• What
is
printed
to
the
screen
here?
>>>def bloodify1(word):
return word[:3] + ‘-bloody-‘ + word[3:]
>>>print(bloodify1(‘fantastic’))
• What
is
printed
to
the
screen
here?
def bloodify2(word):
return word[:3] + ‘-bloody-‘ + word[3:]
print(bloodify2(’mendoza’)) 33
apple
插入号
apple
高亮
fantastic example:
output
fan-bloody-tastic
in the (bloodify1(‘fantastic’)), fantastic is the argument pass to parameter ‘word’ and run the code.
mendoza example:
output:
men-bloody-doza
Returning strings
def get_name():
name = input(‘enter your name:’)
return name
def main():
print(‘this example prints a name
given by user:’)
user_name = get_name()
print(‘my name is’ , user_name)
main() 34
apple
下划线
stop here: 8.26am/thurs/week 10
return strings
Returning boolean values
• You receive an integer from the user. Write a
function that checks whether or not this integer
is even or odd and returns a boolean.
• What are the tasks in this program?
– accept value from user
– checks whether the value is even
or odd and returns a boolean
– print back a response
35
Example: Returning boolean values
def main():
number = int(input(‘enter a number:’))
if XXX:
print(‘the number is even’)
else:
print(‘the number is odd’)
# how do you check if a number is even or odd
def is_even(num1):
if (XXX) == 0:
status = True
else:
status = False
return XXX
main()
36
Returning multiple values
Syntax:
return expr1, expr2, expr..etc…
Example:
#a function to accept first and last name and
then print out your full name
def get_name():
first = input(‘enter your first name:’)
last = input(‘enter your last name:’)
return first, last
def main():
first_name, last_name = get_name()
print(‘My name is:’, first_name, last_name)
main() 37
Returning multiple values: tuples
def checking_tuple(x):
sum = x + 1
mult = x * 3
exp = x ** 3
return (sum, mult, exp)
def main():
num = 5
(a, b, c) = checking_tuple(num)
print(a,b,c)
main() 38
• Break
–
con8nue
to
week
10
if
8me
does
not
permit
39
Key arguments
While generally , arguments are passed by position to
parameter variables in functions, you can also specify
which parameter variable the argument should be passed
to.
Syntax:
parameter_name = value
In this format, parameter_name is the parameter and
value is the value being passed to that parameter. A\
An argument written in this format is called a key
argument.
40
Key arguments: examples
def main():
show_interest(rate = 0.01, periods = 10,
principal = 100000.0)
def show_interest(principal, rate, periods):
interest = principal * rate * periods
print(‘The simple interest will be $%.2f’ %
interest)
main()
41
Mixing Key arguments with positional
arguments : examples
#mixing keyword arguments with positional
arguments. Positional arguments must come first
followed by keyword arguments.
def main():
show_interest(10000.0, periods = 20, rate =
0.01)
def show_interest(principal, rate, periods):
interest = principal * rate * periods
print(‘The simple interest will be $%.2f’ %
interest)
main()
42