Introduction to Python
davidbpython.com
In-Class Exercises, Session 8
|
PLEASE REFER to pythonreference.com for syntax to follow in coding these Exercises |
|
|
FUNCTION ARGUMENTS AND RETURN VALUES |
|
| Ex. 8.1 | Write a function that returns a value. |
|
Define a demonstration function return_ten() that returns the value 10. |
|
def return_ten():
# your function code here
val = return_ten()
print(val) # 10
|
|
| Ex. 8.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. |
|
# your function code here
a = 5
x = doubleme(a)
print(x) # 10
b = 100
y = doubleme(b)
print(y) # 200
|
|
| Ex. 8.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. |
|
# your function def here
a = 50
b = 10
c, d = doubletwo(a, b)
print(c) # 100
print(d) # 20
|
|
| Ex. 8.4 | Write a function that returns None, without explicitly returning it. |
|
Write function greet(), which simply prints 'Hello, world!'. Printing x should show None. |
|
# make sure your function does not attempt to return anything
x = greet()
print(x) # None
|
|
| Ex. 8.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):
valsum = val1 + val2
return valsum
r = get_sum(5, 10)
print(r)
|
|
|
LAB 1 |
|
| Ex. 8.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. |
|
# code to place inside your function:
# randval = random.randint(1, 10)
import random
# your function code here
num = get_rand()
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. 8.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. |
|
# your function def here
x = 50
y = 25
z = get_sum(x, y)
print(z) # 75
|
|
| Ex. 8.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. |
|
# your function def here
aa = 5
bb = 9
c = get_prod(aa, bb) # int, 45
print(c) # 45
|
|
| Ex. 8.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. |
|
# your function def here
x = 'hello'
y = get_upper(x) # str, 'HELLO'
print(y) # HELLO
|
|
| Ex. 8.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. |
|
# your function def here
line = 'this,that,other'
items = get_split(line) # list, ['this', 'that', 'other']
print(items) # ['this', 'that', 'other']
|
|
| Ex. 8.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. |
|
# your function def here
line = '2017-09-03,Alpha Corp.'
first = get_first_item(line) # str, '2017-09-03'
print(first) # 2017-09-03
|
|
|
TRAPPING EXCEPTIONS: TRY/EXCEPT |
|
| Ex. 8.12 | Trap a "bad dict key" error. If the user's key can't be found in the dict, an error occurs -- test this by inputting a key of 'XXX'. Once you have observed the exception and exception type, use a 'try/except' statement to trap the exception and instead print 'key does not exist'. Make sure to put your 'try' block around just one line of code. |
z = {'a': 1, 'b': 2, 'c': 3}
ukey = input('please enter a key: ')
print(z[ukey])
|
|
Sample program run:
please enter a key: XXX key does not exist |
|
| Ex. 8.13 | Trap a "bad list index" error. If the user's index can't be found in the list, an error occurs -- test this by inputting an index of 9. Once you have observed the exception and exception type, use a 'try/except' statement to trap the exception and instead print 'no value at that index'. Make sure to put your 'try' block around just one line of code. |
x = ['a', 'b', 'c', 'd']
uidx = int(input('please enter an index: '))
print(x[uidx])
|
|
Sample program run:
please enter an index: 9 no value at that index |
|
| Ex. 8.14 | Trap a "bad int value" error. Add another except: block to the one below that will trap the exception that occurs if the user doesn't type a number. If this exception is trapped, print 'please enter a number'. |
x = ['a', 'b', 'c', 'd']
try:
uidx = int(input('please enter an index: '))
print(x[uidx])
except IndexError:
print('no value at that index')
|
|
Sample program run:
please enter an index: hey please enter a number |
|
|
SET COMPARISONS |
|
| Ex. 8.15 | Show items in one set that are not in another set. Use set.difference(). |
xx = {'a', 'b', 'c', 'd'}
yy = {'b', 'd'}
# your code here
|
|
| Ex. 8.16 | Show items common between two sets. Use set.intersection(). |
xx = {'a', 'b', 'c', 'd'}
yy = {'c', 'd', 'e', 'f'}
# your code here
|
|
| Ex. 8.17 | Show all items that are in either of two sets. Use set.union(). |
xx = {'a', 'b', 'c', 'd'}
yy = {'c', 'd', 'e', 'f'}
# your code here
|
|
|
LIST COMPREHENSIONS |
|
| Ex. 8.18 | Use a list comprehension to modify each item from a list. |
|
The new list should have each value from the old list doubled. |
|
x = [1, 2, 3, 4]
|
|
Expected Output:
[2, 4, 6, 8] |
|
| Ex. 8.19 | Use a list comprehension to filter items from a list. The new list should have only those values that are greater than 100. |
temps = [86, 89, 93, 101, 92, 107, 90, 110]
|
|
Expected Output:
[101, 107, 110] |
|
| Ex. 8.20 | Use a list comprehension to both modify and filter items from a list. The new list should have each value above 0 doubled. |
aa = [-5, -3, 2, 0, 15, 73, -100]
|
|
Expected Output:
[4, 30, 146] |
|
|
LAB 2 |
|
| Ex. 8.21 | 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'}
second_round = {'Adams, Abdul', 'Pollinator, Jim', 'Freeman, Kalley', 'Boom, Boom'}
|
|
Expected Output:
{'Adams, Abdul', 'Pollinator, Jim'}
|
|
|
(Note that set results may be in any order.) |
|
| Ex. 8.22 | 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'}
second_round = {'Adams, Abdul', 'Pollinator, Jim', 'Freeman, Kalley', 'Boom, Boom'}
|
|
Expected Output:
{'Miller, George', 'Feiner, Billy'}
{'Freeman, Kalley', 'Boom, Boom'}
|
|
|
(Note that set results may be in any order.) |
|
| Ex. 8.23 | 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'}
second_round = {'Adams, Abdul', 'Pollinator, Jim', 'Freeman, Kalley', 'Boom, Boom'}
|
|
Expected Output:
{'Miller, George', 'Adams, Abdul', 'Feiner, Billy', 'Pollinator, Jim',
'Freeman, Kalley', 'Boom, Boom'}
|
|
|
(Note that set results may be in any order.) |
|
| Ex. 8.24 | 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.']
|
|
Expected Output:
["IT'S", 'IMPORTANT', 'TO', 'SPEAK', 'MODERATELY.'] |
|
| Ex. 8.25 | 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]
|
|
Expected Output:
[35.3, 49.11, 3.09, 99.98] |
|
| Ex. 8.26 | 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]
|
|
Expected Output:
[2.23606797749979, 1.7320508075688772, 3.0, 3.1622776601683795] |
|
|
Note that there may be small fractional differences on your computer. |
|
| Ex. 8.27 | 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]
|
|
Expected Output:
['$35,392.74', '$100,353.95', '$98.22', '$1,035,392.99'] |
|
|
LIST COMPREHENSIONS: WORKING WITH FILES |
|
| Ex. 8.28 | 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. |
fh = open('pyku.txt')
# your code here - resulting list of strings should
# be each line in 'pyku.txt' without newlines
|
|
| Ex. 8.29 | 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. |
fh = open('pyku.txt')
# your code here
|
|
|
The resulting list of ints should be [20, 30, 30], assuming the lines have not been stripped or divided with splitlines() |
|
| Ex. 8.30 | 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. |
fh = open('revenue.csv')
# your code here
|
|
|
The resulting list of strings should be each company listed in 'revenue.csv' |
|
|
LAB 3 |
|
| Ex. 8.31 | 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.'
]
|
|
Expected Output:
['2014-03-09,Wilson,Joe,Acme Inc.','2014-08-17,Fink,Bart,Beta LLC', '2014-07-01,Jones,Pete,Acme Inc.'] |
|
| Ex. 8.32 | 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.'
]
|
|
Expected Output:
['Wilson', 'Fink', 'Emerson', 'Rodgers', 'Jones'] |
|
| Ex. 8.33 | 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.'
]
|
|
Expected Output:
['2014-03-09,Wilson,Joe,Acme Inc.','2018-09-03,Emerson,Will,Acme Inc.', '2014-07-01,Jones,Pete,Acme Inc.'] |
|
| Ex. 8.34 | 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.'
]
|
|
Expected Output:
['Wilson', 'Emerson', 'Jones'] |
|
| Ex. 8.35 | 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.'
]
|
|
Expected Output:
['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.'] |
|