Introduction to Python
davidbpython.com
In-Class Exercise Solutions, Session 7
PLEASE REFER to pythonreference.com for syntax to follow in coding these Exercises |
|
FUNCTION ARGUMENTS AND RETURN VALUES |
|
Ex. 7.1 | Write a function that returns a value. |
Define a demonstration function return_ten() that returns the value 10. |
|
Suggested Solution:
def return_ten():
return 10 # return int, 10
val = return_ten() # int, 10
print(val) # 10
|
|
Ex. 7.2 | Write a function with one argument and one return value. |
Define function 'doubleme' that takes one argument, doubles the value, and returns the doubled value. Note: you must not use 'a' or 'b' inside the function, and you must not print inside the function -- value must be returned. |
|
Suggested Solution:
def doubleme(arg): # arg: int, 5 (when first called)
darg = arg * 2 # int, 10
return darg # return int, 10
a = 5 # int, 5
x = doubleme(a) # int, 10
print(x) # 10
b = 100 # int, 100
y = doubleme(b) # int, 200
print(y) # 200
|
|
Ex. 7.3 | Write a function with two arguments and two return values. |
Define function 'doubletwo' that takes two numeric arguments, doubles each of them, and returns the two doubled values. Note: you must not use 'a' or 'b' inside the function, and you must not print inside the function - values must be returned. |
|
Suggested Solution:
def doubletwo(x, y): # x: int, 50; y: int, 10
dx = x * 2 # int, 100
dy = y * 2 # int, 20
return dx, dy # return int 100, int 20
a = 50 # int, 50
b = 10 # int, 10
c, d = doubletwo(a, b) # int 100, int 20
print(c) # 100
print(d) # 20
|
|
Ex. 7.4 | Write a function that returns None (without explicitly returning it). |
Write function greet(), which simply prints 'Hello, world!'. Printing x should show None. |
|
def greet():
print('Hello, world!')
x = greet()
print(x) # None
|
|
The function does not need to do anything more to return None. In fact, when a function does not return anything, it returns None. |
|
Ex. 7.5 | Demonstration: remove a return statement and note the value. |
The below function returns the sum of its arguments. First run the program and note the printed value, then remove the return statement to see the printed value. |
|
def get_sum(val1, val2): # val1: int 5; val2: int 10
valsum = val1 + val2 # int, 15
r = get_sum(5, 10) # int, 15
print(r) # None
|
|
This exercise is intended to emphasize that a function without a return statement will always return None. You can know that in most cases if you see None returned from a function, this means it was not intended to return a value and so should be called without an assignment (e.g., without r = above). |
|
LAB 1 |
|
Ex. 7.6 | Write a function that returns a value. |
Define function 'get_rand()' that uses the following code to generate a random number between 1 and 10, then returns that number. Note: you must not print inside the function -- value must be returned. |
|
Suggested Solution:
import random
def get_rand():
randval = random.randint(1, 10) # int, 7 (sample value)
return randval
num = get_rand() # int, 7
print(num)
|
|
If you see None printed, then you did not return anything from the function, but are printing the value returned from the function. Make sure not to print inside the function. |
|
Ex. 7.7 | Write a function with two arguments and one return value. |
Define function 'get_sum' that takes two numeric arguments and returns the values summed. Note: you must not use 'x' or 'y' inside the function, and you must not print inside the function - value must be returned. |
|
Suggested Solution:
def get_sum(a, b): # a: int 50; b: int 25
return a + b # return int 75
x = 50 # int, 50
y = 25 # int, 25
z = get_sum(x, y) # int, 75
print(z) # 75
|
|
Ex. 7.8 | Write a function with two arguments and one return value. |
Define function get_prod() that takes two numeric arguments and returns their values multiplied together. |
|
def get_prod(arg1, arg2): # arg1: int 5; arg2: int 9
prodarg = arg1 * arg2 # int, 45
return prodarg
aa = 5 # int, 5
bb = 9 # int, 9
c = get_prod(aa, bb) # int, 45
print(c) # 45
|
|
Ex. 7.9 | Write a function with one argument and one return value. |
Define function get_upper() that takes a string argument and returns the value uppercased. |
|
def get_upper(val): # val: str, 'hello'
uval = val.upper() # str, 'HELLO'
return uval
x = 'hello' # str, 'hello'
y = get_upper(x) # str, 'HELLO'
print(y) # HELLO
|
|
Ex. 7.10 | Write a function with one argument and one return value. |
Define function get_split() that takes a string argument for a comma-separated CSV string line and returns a list of values from the split. |
|
def get_split(this_line): # this_line: str, 'this,that,other'
items = this_line.split(',') # list, ['this', 'that', 'other']
return items
line = 'this,that,other' # str, 'this,that,other'
items = get_split(line) # list, ['this', 'that', 'other']
print(items) # ['this', 'that', 'other']
|
|
Ex. 7.11 | Write a function with one argument and one return value. |
Define function get_first_item() that takes a string argument for a comma-separated CSV string line and returns just the first comma-separated item from the line. |
|
def get_first_item(csv_line): # csv_line: str, '2017-09-03,Alpha Corp.'
items = csv_line.split(',') # list, ['2017-09-03', 'Alpha Corp.']
return items[0] # return '2017-09-03'
line = '2017-09-03,Alpha Corp.' # str, '2017-09-03,Alpha Corp.'
first = get_first_item(line) # str, '2017-09-03'
print(first) # 2017-09-03
|
|
EXCEPTIONS: RAISE STATEMENT |
|
Ex. 7.12 | Raise an exception. Test to see if the user's input matches one of the values in the valid_choices list (use if uchoice not in valid_choices). If not, raise a ValueError exception. |
Suggested Solution:
def validate(uchoice): # uchoice: str, 'no'
valid_choices = ['buy', 'sell', 'hold'] # list, ['buy', 'sell', 'hold']
if uchoice not in valid_choices: # bool, True
raise ValueError('choices must be "buy", "sell" or "hold"')#
# return 1, 2 or 3 based on choice
idx = valid_choices.index(uchoice) + 1 #
return idx
choice = input('please enter an action ("buy", "sell", "hold"): ') # str, 'no' (sample value)
index = validate(choice) # raises ValueError
print(f'action index is {index}')
|
|
Ex. 7.13 | Detect object type and raise TypeError. Use the isinstance() function to see if the argument to this function is an integer. If it isn't, raise your own TypeError exception. |
Suggested Solution:
def doubleit(arg): # arg: str, '5'
if not isinstance(arg, int): # bool, False
raise TypeError('arg must be an int') #
return arg * 2
x = doubleit('5') # raises TypeError
print(x)
|
|
SET COMPARISONS |
|
Ex. 7.14 | Show items in one set that are not in another set. Use set.difference(). |
Suggested Solution:
xx = {'a', 'b', 'c', 'd'} # set, {'a', 'b', 'c', 'd'}
yy = {'b', 'd'} # set, {'b', 'd'}
diff = xx.difference(yy) # set {'a', 'c'}
print(diff)
|
|
Ex. 7.15 | Show items common between two sets. Use set.intersection(). |
Suggested Solution:
xx = {'a', 'b', 'c', 'd'} # set, {'a', 'b', 'c', 'd'}
yy = {'c', 'd', 'e', 'f'} # set, {'c', 'd', 'e', 'f'}
common = xx.intersection(yy) # set, {'c', 'd'}
print(common)
|
|
Ex. 7.16 | Show all items that are in either of two sets. Use set.union(). |
Suggested Solution:
xx = {'a', 'b', 'c', 'd'} # set, {'a', 'b', 'c', 'd'}
yy = {'c', 'd', 'e', 'f'} # set, {'c', 'd', 'e', 'f'}
complete = xx.union(yy) # set, {'a', 'b', 'c', 'd', 'e', 'f'}
print(complete)
|
|
LIST COMPREHENSIONS |
|
Ex. 7.17 | Use a list comprehension to modify each item from a list. The new list should have each value from the old list doubled. |
Suggested Solution:
x = [1, 2, 3, 4] # list, [1, 2, 3, 4]
dx = [ item * 2 for item in x ] # list, [2, 4, 6, 8]
print(dx)
|
|
Ex. 7.18 | Use a list comprehension to filter items from a list. The new list should have only those values that are greater than 100. |
Suggested Solution:
temps = [86, 89, 93, 101, 92, 107, 90, 110] # list, [86, 89 ... ]
higher_temps = [ item for item in temps if item > 100 ] # list, [101, 107, 110]
print(higher_temps)
|
|
Ex. 7.19 | Use a list comprehension to both modify and filter items from a list. The new list should have each value above 0 doubled. |
Suggested Solution:
aa = [-5, -3, 2, 0, 15, 73, -100] # list, [-5, -3, 2 ... ]
hda = [ item * 2 for item in aa if item > 0 ] # list, [4, 30, 146]
print(hda)
|
|
LAB 2 |
|
Ex. 7.20 | Show common items between two sets. |
In a single statement, show what is common between the two sets. |
|
first_round = {'Miller, George', 'Adams, Abdul',
'Feiner, Billy', 'Pollinator, Jim'} # set
second_round = {'Adams, Abdul', 'Pollinator, Jim',
'Freeman, Kalley', 'Boom, Boom'} # set
common = first_round.intersection(second_round) # set, {'Adams, Abdul', 'Pollinator' ... }
print(common)
|
|
Ex. 7.21 | Show difference between two sets. |
In a single statement, show what is in set first_round that is not in set second_round; then show the reverse. |
|
first_round = {'Miller, George', 'Adams, Abdul',
'Feiner, Billy', 'Pollinator, Jim'} # set
second_round = {'Adams, Abdul', 'Pollinator, Jim',
'Freeman, Kalley', 'Boom, Boom'} # set
first_diff = first_round.difference(second_round) # set, {'Miller, George, 'Feiner, Billy'}
print(first_diff)
second_diff = second_round.difference(first_round) # set, {'Freeman, Kalley', 'Boom, Boom'}
print(second_diff)
|
|
Ex. 7.22 | Show all values in two sets. |
In a single statement, show a complete set of values contained in both sets. |
|
first_round = {'Miller, George', 'Adams, Abdul',
'Feiner, Billy', 'Pollinator, Jim'} # set
second_round = {'Adams, Abdul', 'Pollinator, Jim',
'Freeman, Kalley', 'Boom, Boom'} # set
together = first_round.union(second_round) # set (containing all items in both sets)
print(together)
|
|
Ex. 7.23 | Modify each item in a list using a list comprehension. |
Write a list comprehension that uppercases each word in the list. Print the list. |
|
x = ["It's", 'important', 'to', 'speak', 'moderately.'] # list, ["It's", 'important' ... ]
y = [ item.upper() for item in x ] # list, ["IT'S", 'IMPORTANT' ... ]
print(y)
|
|
Ex. 7.24 | Modify each item in a list using a list comprehension. |
Write a list comprehension that returns the list of numbers showing their percentage value as a whole number (i.e., multiplied by 100). |
|
pcts = [.353, .4911, .0309, .9998] # list, [.353, .4911, .0309, .9998]
pcent = [ item * 100 for item in pcts ] # list, [35.3, 49.11, 3.09, 99.98]
print(pcent)
|
|
Ex. 7.25 | Modify selected items in a list using a list comprehension. |
Write a list comprehension that returns the square root of each number greater than 0. To calculate square root, you can raise to the power of 0.5, or num ** 0.5 (where num is the variable holding the number). |
|
x = [5, 3, -3, 9, -7, 0, 10] # list, [5, 3, -3, 9 ... ]
xsq = [ item ** 0.5 for item in x if item > 0 ] # list, [2.5, 1.5, 4.5 ... ]
print(xsq)
|
|
Note that there may be small fractional differences on your computer. |
|
Ex. 7.26 | Modify each item in a list using a list comprehension. |
Write a list comprehension that returns a list of strings that show each number as a currency value with comma separators (use the f'${num:,} format string, where num is the variable holding the number). Also round each item to 2 decimal places. |
|
aa = [35392.7381, 100353.949, 98.2203, 1035392.9942] # list, [35392.7381, 100353.949 ... ]
dolvals = [ f'${round(num, 2):,}' for num in aa ] # list, ['$35,392.74', '$100,353.95' ... ]
print(dolvals)2
|
|
LIST COMPREHENSIONS: WORKING WITH FILES |
|
Ex. 7.27 | Use a list comprehension to strip each line of a file. Reading 'pyku.txt', use a list comprehension to generate a list of lines, each one stripped of the newline. Print the list as a whole - do not loop through it. |
Suggested Solution:
fh = open('../pyku.txt') # 'file' object
slines = [ line.rstrip() for line in fh ] # list, ["We're out of gouda.",
'This parrot has ceased to be.',
'Spam, spam, spam, spam, spam.']
print(slines)
|
|
Ex. 7.28 | Use a list comprehension to derive information about each line of a file. Looping through 'pyku.txt', generate a new list with integers - the string length of each line in the file. Print the list. |
Suggested Solution:
fh = open('../pyku.txt') # 'file' object
ilist = [ len(line) for line in fh ] # list, [20, 30, 30]
print(ilist)
|
|
The resulting list of ints should be [20, 30, 30], assuming the lines have not been stripped or divided with splitlines() |
|
Ex. 7.29 | Use a list comprehension to extract a field from each row in a CSV file. Reading 'revenue.csv', use a list comprehension to generate a list of company names. Print the list as a whole. |
Suggested Solution:
fh = open('../revenue.csv') # 'file' object
names = [ line.split(,)[0] for line in fh ] # list, ["Haddad's", 'Westfield', ... ]
|
|
The resulting list of strings should be each company listed in 'revenue.csv' |
|
LAB 3 |
|
Ex. 7.30 | Select items from a list using a list comprehension. |
Write a list comprehension that returns a list of lines that start with the year '2014' |
|
lines = [ '2014-03-09,Wilson,Joe,Acme Inc.',
'2014-08-17,Fink,Bart,Beta LLC',
'2018-09-03,Emerson,Will,Acme Inc.',
'2020-12-09,Rodgers,Mary,Gamma Co.',
'2014-07-01,Jones,Pete,Acme Inc.'
] # list
yearlines = [ this for this in lines if this[0:4] == '2014' ]
# list, ['2014-03-09,Wilson,Joe,Acme Inc.',
# '2014-08-17,Fink,Bart,Beta LLC']
# alt test
yearlines = [ this for this in lines if this.startswith('2014') ]
print(yearlines)
|
|
Ex. 7.31 | Modify selected lines from a list using a list comprehension and a compound statement. |
Write a list comprehension that returns a list of last names from each line. |
|
lines = [ '2014-03-09,Wilson,Joe,Acme Inc.',
'2014-08-17,Fink,Bart,Beta LLC',
'2018-09-03,Emerson,Will,Acme Inc.',
'2020-12-09,Rodgers,Mary,Gamma Co.',
'2014-07-01,Jones,Pete,Acme Inc.'
] # list
names = [ line.split(',')[1] for line in lines ] # list, ['Wilson', 'Fink' ... ]
print(names)
|
|
Ex. 7.32 | Select lines from a list using a list comprehension and a compound statement. |
Write a list comprehension that returns a list of only 'Acme Inc.' lines. |
|
lines = [ '2014-03-09,Wilson,Joe,Acme Inc.',
'2014-08-17,Fink,Bart,Beta LLC',
'2018-09-03,Emerson,Will,Acme Inc.',
'2020-12-09,Rodgers,Mary,Gamma Co.',
'2014-07-01,Jones,Pete,Acme Inc.'
] # list
acmes = [ thisline.split(',') for thisline in lines if thisline.split(',')[-1] == 'Acme Inc.']
# list, [ '2014-03-09,Wilson,Joe,Acme Inc.',
# '2018-09-03,Emerson,Will,Acme Inc.',
# '2014-07-01,Jones,Pete,Acme Inc.']
print(acmes)
|
|
Ex. 7.33 | Modify selected lines from a list using a list comprehension and a compound statement. |
Write a list comprehension that returns a list of last names only from 'Acme Inc.' lines. |
|
lines = [ '2014-03-09,Wilson,Joe,Acme Inc.',
'2014-08-17,Fink,Bart,Beta LLC',
'2018-09-03,Emerson,Will,Acme Inc.',
'2020-12-09,Rodgers,Mary,Gamma Co.',
'2014-07-01,Jones,Pete,Acme Inc.'
] # list
acmes = [ thisl.split(,)[1] for thisl in lines if thisline.split(',')[-1] == 'Acme Inc.']
# list, ['Wilson', 'Emerson', 'Jones']
print(acmes)
|
|
Ex. 7.34 | Supreme Challenge!. |
Write a list comprehension that returns the list of lines with only the last name uppercased. (Splitting the line, you can uppercase the first element, make a list out of it, append it to the list of remaining values, and use ','.join() with the list to reconstitute the comma-separated values.) |
|
lines = [ '2014-03-09,Wilson,Joe,Acme Inc.',
'2014-08-17,Fink,Bart,Beta LLC',
'2018-09-03,Emerson,Will,Acme Inc.',
'2020-12-09,Rodgers,Mary,Gamma Co.',
'2014-07-01,Jones,Pete,Acme Inc.'
] # list
uname_lines = [ ','.join([ li.split(',')[0], li.split(',')[1].upper() ] +
li.split(',')[2:]) for li in lines ]
# list, ['2014-03-09,WILSON,Joe,Acme Inc.',
# '2014-08-17,FINK,Bart,Beta LLC', ... ]
print(uname_lines)
|
|