Introduction to Python
davidbpython.com
In-Class Exercises, 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. |
|
def return_ten():
# your function code here
val = return_ten()
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. |
|
# your function code here
a = 5
x = doubleme(a)
print(x) # 10
b = 100
y = doubleme(b)
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. |
|
# your function def here
a = 50
b = 10
c, d = doubletwo(a, b)
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. |
|
# make sure your function does not attempt to return anything
x = greet()
print(x) # 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):
valsum = val1 + val2
return valsum
r = get_sum(5, 10)
print(r)
|
|
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. |
|
# 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. 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. |
|
# your function def here
x = 50
y = 25
z = get_sum(x, y)
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. |
|
# your function def here
aa = 5
bb = 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. |
|
# your function def here
x = '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. |
|
# your function def here
line = '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. |
|
# your function def here
line = '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. |
def validate(uchoice):
valid_choices = ['buy', 'sell', 'hold']
if uchoice not in valid_choices:
" raise a ValueError exception here "
# 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"): ')
index = validate(choice)
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. |
def doubleit(arg):
if not isinstance(arg, int):
# your code here
return arg * 2
x = doubleit('5')
|
|
SET COMPARISONS |
|
Ex. 7.14 | 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. 7.15 | Show items common between two sets. Use set.intersection(). |
xx = {'a', 'b', 'c', 'd'}
yy = {'c', 'd', 'e', 'f'}
# your code here
|
|
Ex. 7.16 | 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. 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. |
|
x = [1, 2, 3, 4]
|
|
Expected Output:
[2, 4, 6, 8] |
|
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. |
temps = [86, 89, 93, 101, 92, 107, 90, 110]
|
|
Expected Output:
[101, 107, 110] |
|
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. |
aa = [-5, -3, 2, 0, 15, 73, -100]
|
|
Expected Output:
[4, 30, 146] |
|
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'}
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. 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'}
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. 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'}
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. 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.']
|
|
Expected Output:
["IT'S", 'IMPORTANT', 'TO', 'SPEAK', 'MODERATELY.'] |
|
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]
|
|
Expected Output:
[35.3, 49.11, 3.09, 99.98] |
|
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]
|
|
Expected Output:
[2.23606797749979, 1.7320508075688772, 3.0, 3.1622776601683795] |
|
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]
|
|
Expected Output:
['$35,392.74', '$100,353.95', '$98.22', '$1,035,392.99'] |
|
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. |
fh = open('../pyku.txt')
# your code here - resulting list of strings should
# be each line in 'pyku.txt' without newlines
|
|
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. |
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. 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. |
fh = open('../revenue.csv')
# your code here
|
|
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.'
]
|
|
Expected Output:
['2014-03-09,Wilson,Joe,Acme Inc.','2014-08-17,Fink,Bart,Beta LLC', '2014-07-01,Jones,Pete,Acme Inc.'] |
|
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.'
]
|
|
Expected Output:
['Wilson', 'Fink', 'Emerson', 'Rodgers', 'Jones'] |
|
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.'
]
|
|
Expected Output:
['2014-03-09,Wilson,Joe,Acme Inc.','2018-09-03,Emerson,Will,Acme Inc.', '2014-07-01,Jones,Pete,Acme Inc.'] |
|
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.'
]
|
|
Expected Output:
['Wilson', 'Emerson', 'Jones'] |
|
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.'
]
|
|
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.'] |
|