Class 37 — Wednesday, April 20
I know that you know that
Programming basics — Your semester achievement — Bask in the success
Look both ways
Agenda
- Taking stock
Downloads
- Module but_its_on_sale.py
- Module naming_names.py
- Module step_case.py
- Module the_average_thing.py
but_its_on_sale.py - functions and optional parameters
- This function takes one required parameter,
original_price
, and one optional parameter,percent_off
.
- The function then determines the final cost of the item, after subtracting the percent off sale from the original price.
- If the item is not on sale, then the percent_off parameter is equal to 100 by default.
- The tester code defined in the same file should run as follows:
A $ 50 item on sale for 40 % off will cost $ 30.0
A $ 10 item on sale for 15 % off will cost $ 8.5
A $ 50 item on sale for 15 % off will cost $ 42.5
A $ 10 item on sale for 40 % off will cost $ 6.0
A $ 10 item on sale for 0 % off will cost $ 6.0
naming_names.py - while looping
- The user will provide a specific desired name, then a list of names that includes the desired name, and a random seed. Then, the program will print a random names one by one from the list until it equals the chosen name/word, which will be the final name to be printed out.
- Some sample runs are as follows:
Enter desired name: Janine
Enter list of names: Laura Michael Elizabeth Isabelle Janine
Enter random seed: 52
Isabelle
Janine
Enter desired name: Michael
Enter list of names: Laura Michael Elizabeth Isabelle Janine
Enter random seed: 52
Isabelle
Janine
Laura
Elizabeth
Isabelle
Elizabeth
Isabelle
Janine
Laura
Laura
Janine
Elizabeth
Laura
Elizabeth
Janine
Laura
Laura
Laura
Michael
step_case.py - functions and strings
- The function will have a string as its only parameter.
- The function will then create a new string, which will be a copy of the parameter, except all characters in the first half of the string will be in upper-case, and all characters in the second half of the string will be in lower case.
- If there are an odd number of characters, then there will be one more lower-cased character than lower-case character.
- The provided tester code in the file will run as follows:
FLORIDA georgia = step_case("Florida Georgia")
MICHIGan ohio = step_case("MICHIGAN Ohio")
VA MAryland = step_case("va maryland")
the_average_thing.py - while loops and user-inputted dictionary
The user inputs pairs of grocery store items and costs, and the program creates a dictionary representation of this user-specified inventory. When the user enters the empty string, the dictionary is fully built. Next, the program will calculate and print out the average cost of all the items. Finally, the program will print out the item that costs closest to the average price, along with that item's price.
Past homework
- Solutions are available
Test taking
- Unless an accomodation has been granted students are expected to take the test in class on Friday.
What to expect for the test
- Knowledge of
if
,for
, andwhile
statements; along with the ability to use them when problem solving.
- Ability to write functions using numbers, strings, lists, dictionaries, datasets, and random values.
- Simple image manipulation
Built-in functions
id( v )
: returns indicator where in memory to findv
.
type( v )
: returns the type of value stored inv
.
abs( v )
: returns absolute value ofv
.
len( s )
: returns number of things making ups
.
min( s )
: returns minimum value ins
.
max( s )
: returns maximum value ins
.
sum( s )
: returns the sum ofs
.
int( s )
: returns an integer constructed froms
.
float( s )
: returns a decimal constructed froms
.
string( v )
: returns a string constructed froms
.
sorted( s )
: returns a sorted version ofs
.
Functions
- Functions can be invoked.
- The invocation identifies the function to be started up.
- The invocation includes the arguments. The arguments are evaluated. Copies of the values are used to initialize the parameters specified in the function definition.
- Functions must be defined. A function definition consists of a header followed by its body.
- Header:
def name ( parameters ) :
- Body: remaining lines in function. How can you tell? They are indented. Body is also known as the statement list
- A
return
is a special statement in the body of function. When areturn
statement is reached in a function, the function stops executing its instructions; that is, the function immediately stop its execution.
- A
return
statement can optionally have a return expression following the keywordreturn
. The expression is evaluated. A copy of that value is the return value of the function. The return value is said to be the value of the evaluation of the function invocation.
- All Python functions return values – if no
return
statement with a return expression is executed. The function returnsNone
.
- A local variable is a variable initialized/defined inside a function definition.
- Local variables only exist inside the function definition (limited scope)
- The parameters of a function are the variables listed with the parentheses in the function header.
- Parameters are local variables
- The arguments to a function are the values given within the parentheses of an invocation of the function.
- The Python way of handling the arguments is pass by value; that is, the arguments are evaluated to determine their values. Copies of those values are used to initialize the parameters.
- Because Python uses pass by value, the value of an argument is unchanged by a function invocation; that is, the value of an argument is the same after the invocation as it was before the invocation.
- Implication: not possible to write a swapping function in Python
- Because a parameter has the same value as its argument, if that argument is a list, the contents of that list can be modified. Such a change is called a side effect of the function. Functions with side effects generally have a return value of None.
List patterns — suppose alist
, blist
, and clist
are lists and that value v
is not a list
- To analyze a list use
result = ...
for element in alist :
...
return result
- To modify a list use
n = len( alist )
for i in range( 0, n ) :
element = alist[ i ]
...
alist[ i ] = element
- Important list operations
alist.append( v )
- Appends
v
to end ofalist
.
alist.remove( v )
- Removes first occurence of
v
fromalist
.
alist.index( v )
- Index of first occurrence of
v
inalist
.
clist = alist + blist
- Concatenates
alist
andblist
to makeclist
.
v = alist.pop( )
- Removes the last element from
alist
. The value of that former element is the return value assigned tov
.
v = alist.pop( i )
- Removes the element at index
i
fromalist
. The value of that former element is the return value assigned tov
.
- List gotchas
blist = alist + v # cannot add a list and a non-list
alist = alist.append( v ) # alist is no longer a list, it is None
Warnings
- A
print()
statement in a function is not supplying a return value. It is sending a message to the program user.
- An
input()
statement is wrong to include in a function body, information comes into a function through its parameters.
- No function you will be asked to implement should have a
print()
orinput()
statement.
FWIW
- Nested for-loops usually wrong unless using a list-of-lists (e.g., a dataset) or looking at one list in relation to another list or image manipulation
Function sort()
versus sorted():
x.sort()
modifies the contents ofx
to be in non-descending order and returnsNone
sorted( x )
creates a new list that has the elements ofx
in non-descending order, returns that new list, and does not modifyx
Dictionaries
- Unordered collection of key-value pairs
- Initialization examples
d = {} # empty dict
d = { 18 : 'voting', 67 : 'retirement', 'eighteen' : 18}
- Access values by key:
d[ 18 ]
- Means the same thing as 'voting'
- Access values by key:
d[ 21 ]
- Will be an error because 21 is not a key
- Access values by key:
d[ 'voting' ]
- Will be an error because
'voting'
is not a key
- Access values by key:
d.get( 18 )
- Means the same thing as
'voting'
- Access values by key:
d.get( 21 )
- Means the same thing as None (not an error)
- Access key by value: not easy, probably need a loop
- Collection of all keys:
d.keys()
- Collection of all values:
d.values()
- Indices: there are none (just keys)
- List of all keys:
list( d.keys() )
- Set the value of a key:
d[ 100 ] = 'centarian' # makes association for key
100
to be'centarian'
- How do we look at the keys a
dict
for key in d.keys():
# do something with key
- How do we look at the values of a
dict
for value in d.values():
# do something with value
- Trying to find and change a particular entry
- By key; e.g., change key
18
to'adult'
d[ 18 ] = 'adult'
- By value (find key for value 18)
found = None
for key in d.keys():
value = d[ key ]
if value == 18:
found = key
🦆 © 2022 Jim Cohoon Resources from previous semesters are available.