Python Final

Ace your homework & exams now with Quizwiz!

l = [2, 4, 6, 8] l2 = [] for n in range(len(l)): l[n] = l[n] ** 2 l2.append(n) print(n) print('l=', l) print('l2=', l2) What does n represent

0 1 2 3 l= [4, 16, 36, 64] l2= [0, 1, 2, 3] range of length of l

for x in range(10, 0, -1): if x % 3 == 0: for y in range(x): print('=', end='') print('') else: print(x, 'is not a multiple of 3')

10 is not a multiple of 3 ========= 8 is not a multiple of 3 7 is not a multiple of 3 ====== 5 is not a multiple of 3 4 is not a multiple of 3 === 2 is not a multiple of 3 1 is not a multiple of 3

def adder(x1, x2): return x1 + x2 def multiplier(x1, x2): print('Multiplying {} * {}'.format(x1, x2)) return x1 * x2 def main(): x1 = 5 x2 = 10 x3 = adder(x1, x2) print(x3) x3 += multiplier(x3, x2) print(x3) main()

15 Multiplying 15 * 10 165

def func1(x): print(x, 'Inside of func1') x = func2(x * 2) return x / 2 def func2(x): print(x, 'Inside of func2') return x ** 2 def main(): a = func1(2) b = func1(4) print('a = {}, b = {}'.format(a, b)) main()

2 Inside of func1 4 Inside of func2 4 Inside of func1 8 Inside of func2 a = 8.0, b = 32.0

a) Write the output printed when the following code is executed. l = [2, 4, 6, 8] l2 = [] for n in l: n = n ** 2 l2.append(n) print(n) print('l=', l) print('l2=', l2) What does n represent

4 16 36 64 l= [2, 4, 6, 8] l2= [4, 16, 36, 64] values of l

b) How would you determine the length of a Python list named l? A) len(l) B) l.len() C) l.length D) l.size()

A

e) What data type would be best for representing currency values (such as a price)? A) float B) int C) money D) string

A

g) How would you determine the length of a Python list named l? A) len(l) B) l.len() C) l.length D) l.size()

A

b) If you wanted the boolean expression of an if/else statement to evaluate to True when x was an even number, which expression would you use? A) x / 2 == 0 B) x % 2 == 0 C) x % 2 == 1 D) None of the above

B

d) Which of the following would be printed to standard output when the following code was executed? x = (5 * 2) // (4 + 3) y = 5 * 2 / 4 + 3 print('x: {}, y: {}'.format(x, y)) A) x: 1, y: 1.42857 B) x: 1, y: 5.5 C) x: 1, y: 5, z: 7 D) None of the above

B

d) Which of the following exceptions would occur when you try to access an index that is beyond the acceptable boundaries of a list variable? A) ValueError B) IOError C) IndexError D) ListAccessError

C

f) Which of following would assign the 5th through 9th characters of the string variable s to the variable y? A) y = s[5:10] B) y = s[4:10] C) y = s[4:9] D) y = s(4, 10)

C

a) Which of the following is not a valid variable name in Python? A) my_var B) _49er C) var D) else

D

c) What mode would you want to open a file with if you wanted to write to the file and not truncate any existing contents? A) r B) w C) wb D) a

D

c) Which statement is the correct way of getting access to functions that can perform various mathematical operations inside of a Python program? A) <math> B) get math C) use math D) import math

D

The boolean expression x <= 5 or x > 6 is always True no matter the numeric value stored in x.

False

a) The boolean expression q == 5 or q > 6 is always False no matter the value stored in q.

False

a) When using if/else statements, both the if and else clauses are mandatory.

False

b) A Label is the best GUI widget to use when you need to accept text from a user.

False

c) Calling x.upper() on a string variable named x would change its contents to contain all uppercase letters.

False

c) The prompt function is used in a Python program to prompt the user for input.

False

d) For loops are examples of condition-controlled repetition structures.

False

d) Void functions should return values to their callers.

False

d) my_string[-4] would return all but the last 4 characters of the string variable my_string.

False

e) Lists, strings, and tuples are all immutable data objects in Python.

False

g) Calling x.upper() on a string variable named x would change its contents to contain all uppercase letters.

False

k = 5 print('Start: k =', k) if k % 2 == 0: print('Even') k += 1 else: print('Odd') k -= 1 print('End: k =', k)

Start: k = 5 Odd End: k = 4

k = 5 print('Start: k =', k) if k % 2 == 0: print('Even') k += 1 if k % 2 != 0: print('Odd') k -= 1 if k % 2 == 0: print('Even') k += 1 print('End: k =', k)

Start: k = 5 Odd Even End: k = 5

x = 27 print('Start: x =', x) while x > 1: x = x // 3 print('After dividing by 3...', x) print('End: x =', x)

Start: x = 27 After dividing by 3... 9 After dividing by 3... 3 After dividing by 3... 1 End: x = 1

The boolean expression (5 * 7) / 5 == 5 * 7 / 5 evaluates to True.

True

a) If uncaught, an exception will cause a Python program to terminate immediately.

True

b) The expression not (5 < 5.1 and 7 >= 8) evaluates to True

True

b) The range function is used in a Python program to return a sequenced list of integers.

True

c) Value-returning functions can be used on the right hand side of assignment statements just like literal values.

True

h) my_string[:-4] would return all but the last 4 characters of the string variable my_string.

True

a) Which of following would assign the 5th through 9th characters of the string variable s to the variable y? A) y = s[5:10] B) y = s[4:10] C) y = s[4:9] D) y = s(4, 10)

c

e) What is the name of the method you should define in a class definition that returns a value suitable for use with the print function? A) __get__ B) __init__ C) __str__ D) None of the above

c

Write a function called count_spaces. The function should accept a string argument named sentence. The function should count and return the number of space (' ') characters found in the sentence parameter. If there are no spaces, the function should return 0. (10 pts.)

def count_spaces(sentence): count = 0 for i in range(len(sentence)): if sentence[i] == ' ': count += 1 return count

A factorial of a number n is the product of all of the numbers from 1 to n. It is typically indicated by the exclamation point symbol. 4! = 4 * 3 * 2 * 1. Write a function called factorial. The function should accept one parameter named num. The function should calculate num's factorial and print the result to the console. You do not need to return anything from this function. (20 pts.)

def factorial(num): result = num for i in range(num - 1, 1, -1): result *= i print(result)

A file named names.txt exists in the same directory as your Python program. Write a function called get_and_sort_names. It should not accept any parameters. It should open names.txt, read each line in the file and add the content of the line (with any new line characters stripped) to a list. Then, it should sort the list in reverse alphabetical order and return it to the caller. Ex. If names.txt contained: Billy Jean Michael Christopher The function should return: ['Michael', 'Jean', 'Christopher', 'Billy']

def get_and_sort_names(): names = [] f = open('names.txt') for l in f: names.append(l.rstrip()) names.sort() names.reverse() return names

Write a function called merge_files. The function should not accept any parameters. It should read and combine the corresponding lines from each file and write them into a new file named merged.txt. The data in merged.txt should contain the name and ID on a single line separated by a comma like the following. merged.txt John,00001 Mary,00002 Eric,00003 (10 pts.)

def merge_files(): names = open('names.txt') ids = open('ids.txt') merged = open('merged.txt', 'w') n = names.readline().rstrip() i = ids.readline().rstrip() while n and i: merged.write('{},{}\n'.format(n, i)) n = names.readline().rstrip() i = ids.readline().rstrip() names.close() ids.close() merged.close()

Assume a file named file.txt contains numeric and non-numeric data. Write a function called process_data that does not accept any parameters. The function should read each line from the file. If it is numeric, it should add its value to a running total. If it is non-numeric, it should increment a count containing the number of non-numeric strings. The function should return a tuple with the total sum of values from all numeric lines as the first item, and the count of all non-numeric lines as the second value. (15 pts.)

def process_data(): f = open('file.txt') total = 0 count = 0 for l in f: l = l.rstrip() try: total += float(l) except ValueError: count += 1 return (total, count)

Write a function called record_checkbook_entry. The function should accept two parameters, name, and amount. It should open up a binary file named checkbook.dat in append mode. The function should build a dictionary object with two keys, 'name' and 'amount' and should assign the appropriate parameter value passed into the function to as each key's value. Then, the function should write the dictionary object to the file using pickle and then close the file. You can assume that import pickle was already done at the top of the file containing this function. (15 pts.)

def record_checkbook_entry(name, amount): entry = {'name': name, 'amount': amount} f = open('checkbook.dat', 'ab') pickle.dump(entry, f) f.close()

You've been given the not-so-fun task of updating your company's record files to reflect the change in name from Initech to Initrode. Fortunately, you remember what you learned in about files and strings in Python from CS0008. Write a function called rename_for_new_file. It should not accept any parameters. It should open a file named company.txt for reading and a file named company_new.txt for writing. It should read each line from company.txt. If 'Initech' is found anywhere in the line, it should be replaced with 'Initrode'. All lines from company.txt should be written to company_new.txt. Both files should be closed when you are done. You don't need to return anything.

def rename_for_new_file(): f1 = open('company.txt') f2 = open('company_new.txt', 'w') for l in f1: f2.write(l.replace('Initech', 'Initrode')) f1.close() f2.close()

Python's maintainers have decided that .reverse() and [::-1] are no longer going to be supported ways of reversing a string. You need to come up with your own function called reverse. It should accept a string parameter named s and return s after reversing its characters using a loop (ie. 'aardvark' should become 'kravdraa'). Note: You cannot use s.reverse() or s[::-1] in your function.

def reverse(s): new_s = '' # Count backwards from the end of the string to the beginning for c in range(len(s) - 1, -1, -1): new_s += s[c] return new_s

Pitt's mens' basketball team has all of their game statistics from last year in a file named stats.txt. The file has the following format: <player name>|<points scored>|<rebounds>|<assists> Each player will appear once for each game. Points scored, rebounds and assists will either be numbers, or will be left blank. Write a function called summarize_stats. It should not accept any parameters but should open stats.txt for reading. You should read each line and split it by the '|' character. You should try to convert the 2nd, 3rd, and 4th words in the split line into ints and add them to running totals for points, rebounds, and assists. You should be prepared to catch the potential problem that might occur if any of those values is left blank (remember, int('') doesn't work!). Once you've processed each line in the file and accumulated the total points, rebounds, and assists from the season, return a tuple with the values in that order.

def summarize_stats(): f = open('stats.txt') points = 0 rebounds = 0 assists = 0 for l in f: pieces = l.rstrip().split('|') try: points += int(pieces[1]) rebounds += int(pieces[2]) assists += int(pieces[3]) except ValueError as e: print(e) return (points, rebounds, assists)

Write a function called swap that accepts a string parameter named s. The function should swap the first and last characters of s and return the new string to its caller Example: swap('foo') would return 'oof'). (10 pts.)

def swap(s): return s[-1] + s[1:-1] + s[0]

Assume you have a two-dimensional list that looks like the following: [[1, 2, 3], [2, 4, 6], [3, 6, 9]] Your boss comes to you and says that she wants the outer list to be a list of 3 dict objects with 'A', 'B', and 'C' as the keys instead of a list of 3 list objects with indices 0, 1 and 2. Write a function called transform. The first line of your function should create a list object that looks exactly like the list above. Your function should build and print a new list object that looks like the following: [{'A': 1, 'B': 2, 'C': 3}, {'A': 2, 'B': 4, 'C': 6}, {'A': 3, 'B': 6, 'C': 9}] Note: Don't worry if the keys in your inner dict objects don't print in the same order. Remember, key order is not consistent or stable in Python3 for dicts and sets!

def transform(): a = [[1, 2, 3], [2, 4, 6], [3, 6, 9]] new_list = [] for row in a: d = {'A': row[0], 'B': row[1], 'C': row[2]} new_list.append(d) print(new_list)

Write a function called tuition_planner that accepts two parameters. The first should be named base_tuition and the second should be named pct_increase. The function should display the tuition for the current year and next 3 years applying the annual increase percentage to each figure. Each dollar value should be displayed using a comma as a thousands separator and two decimal places. Note that in year 1, the tuition printed should be the same as the base_tuition parameter, and the pct_increase percentage should be applied to each subsequent year's amount. Sample call: tuition_planner(10000, 0.05) should display Year 1: $10,000.00 Year 2: $10,500.00 Year 3: $11,025.00 Year 4: $11,576.25 (20 pts.)

def tuition_planner(base_tuition, pct_increase): print('Year 1: ${:,.2f}'.format(base_tuition)) for i in range(2, 5): base_tuition *= 1 + pct_increase print('Year {}: ${:,.2f}'.format(i, base_tuition))

my_list = ['apple', 'orange', 'banana'] for f in my_list: f = f.upper() print(f) print(my_list) my_list = ['apple', 'orange', 'banana'] for f in range(len(my_list)): my_list[f] = my_list[f].upper() print(my_list[f]) print(my_list)

f in question one is the specific string f in question two is the number in range len, acts as index

c) Write the output printed when the following code is executed. def main(): l = [] f1(l, 'A') f2(l, 'B') m = l f1(m, 'C') f2(m, 'D') n = m[:3] f1(n, 'E') print('l=', l) print('m=', m) print('n=', n) def f1(l, v): l.insert(0, v) def f2(l, v): l.append(v) main()

l= ['C', 'A', 'B', 'D'] m= ['C', 'A', 'B', 'D'] n= ['E', 'C', 'A', 'B']

a = set(list(range(1, 11))) b = set(list(range(2, 11, 2))) c = a.intersection(b) d = a.difference(b) print(a) print(b) print(c) print(d) print(b.issubset(a))

{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} {2, 4, 6, 8, 10} {2, 4, 6, 8, 10} {1, 3, 5, 7, 9} True


Related study sets

Chp 1 Self-Esteem study guide (Prof. Dev.)

View Set

network + ch 15 wireless networking

View Set

Genetics Final- homework questions

View Set

ch 18: findings for the breasts and axillae

View Set

Health Assessment Final Exam Practice

View Set

Human Nutrition Final Study Tool

View Set