代写 math python ISYS90088 Introduction to Application Development

ISYS90088 Introduction to Application Development
Week 9 – Contd. from week 8 on Dictionaries; Introduction to Functions
Week 10: Contd. with functions
s
Semester 2 , 2018
Dr Antonette Mendoza
1

Other Dictionary methods: pop • Usethebuiltinmethodcalledpop
• 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

Other Dictionary methods: popitem • Usethebuiltinmethodcalledpopitem
• 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

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)]
4

Note: defaultdict when working with lists and dictionaries
• Itiseasytogroupasequenceofkey-valuepairsintoadictionaryoflists 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])]
• Wheneachkeyisencounteredforthefirsttime,itisnotalreadyinthe 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

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

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
}

Functions
8

Functions
• What’safunction?Itisagroupofstatementsthat 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

Functions: usefulness
• Simpler code
• Code re-use
• Better testing
• Faster development
• Easier facilitation of teamwork
10

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

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 (INPUTLIST):
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

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

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

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)
a and b are parameters
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)
This is an argument that is passed to the func8on
22

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()
value number
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

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

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

Variables and “Scope” :
• Eachfunction(call)definesitsownlocalvariable“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

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

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

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