• Wrong document? Swap it for free
  • Written by students who passed
  • Immediately available after payment
  • Read online or as PDF
Sell
Where do you study
Your language
Document preview thumbnail
Preview 3 out of 20 pages
Exam (elaborations)

Python C859 Questions and Complete Solutions Graded A+

Document preview thumbnail
Preview 3 out of 20 pages

Python C859 Questions and Complete Solutions Graded A+ Minimum field width with strings - Answer: print('Student name (%5s)' % 'Bob' the 5 specifies that there are a minimum of 5 characters and thus the print out would be ( Bob) Conversion flags - Answer: alter the output of conversion specifiers %08d adds leading zeros to the minimum width of 8 characters precision components(Rounding) - Answer: Indicates how many digits to the right of the decimal should be included '%.1f' % 1.725 indicates a precision of 1 resulting in 1.7 .replace() - Answer: replace(old,new,count) count replaces only the first occurrence count can be left out translation = ce('one', 'uno') .find(x) - Answer: Returns the position of the first occurrence of item x in the string if my_str is 'Boo Hoo!' my_('!') Returns 7 ('Boo') Returns 0 my_('oo') returns 1 find(x, start) - Answer: Same as find(x) but begins the search at position start find(x, start, end) - Answer: Same as find(x,start) but stops the search at position end rfind(x) - Answer: Same as find but searches the string in reverse, returning the last occurrence in the string count(x) - Answer: Returns the number of times x occurs in the string using in operator to check if a character or substring is contained in the string - Answer: if 'b' in my_string Comparing Strings - Answer: may be compared using relational operators ( = etc..) equality operators (==,!=) membership operators (in,not in) identity operators (is, is not) my_str = 'Hello' my_str == 'Hello" evaluates to True relational comparison will compare the ASCII unicode values. if a string is shorter with all the same characters then the shorter is considered less than Do not use identity operators where you should be using an equality operator comparisons are case sensitive isalnum() - Answer: Returns True if all characters int he string are lowercase or uppercase letters, or the numbers 0-9 isdigit() - Answer: Returns True if all characters are the numbers 0-9 islower() - Answer: Returns True if all characters are lowercase letters isupper() - Answer: Returns True if all characters are uppercase letters isspace() - Answer: Returns True if all characters are whitespace startswith(x) - Answer: Returns True if the string starts with x endswith(x) - Answer: Returns True if the string ends with x capitalize() - Answer: Returns a copy of the string with the first character capitalized and rest lowercased lower() - Answer: Returns a copy of the string with all characters lowercased upper() - Answer: Returns a copy of the string with all characters uppercased strip() - Answer: Returns a copy of the string with leading and trailing whitespace removed can be used to turn a string literal into a list of items by using the whitespace character as the default separator if it was strip(/) the default separator would be the / character. If the string contained a double // then an empty list element would be created title() - Answer: Returns a copy of the string with the first letters of words capitalized Good practice for input() data transformations - Answer: apply the transformations when reading in data as opposed to later in the program join() - Answer: Works in reverse to split() It joins a list of strings together to create a single string my_str = '@'.join(['billgates', 'microsoft']) binds the name my_str to a new string object with the value 'billgates@microsoft' each element from left to right is concatenated together. The separator can be any string including multiple characters or an empty string charater. ''.join will return the list as a string w/out separators. string format method - Answer: positional= 'The {1} in the {0}'.format('hat','cat') The cat in the hat Inferred positional 'The {} in the {}'.format("cat",'hat') The cat in the hat Named 'The {animal} in the {headwear}.format(animal = 'cat', headwear='hat') The cat in the hat lists - Answer: Container object that groups related objects together. Has a sequence that is maintained left to right Elements of the list can be accessed through indexing Each element can be a different data type inclusive of nested lists within the list. Lists are mutable (In place modification) Creating a list - Answer: my_list = [1,2,3] list(iterable) Retrieving an element from a list - Answer: my_list[list element index] Get a new list containing some of another list's elements - Answer: my_list[start:end] retrieves the indexed values of my_list Add a list to the end of another list - Answer: my_list1 + my_list2 Change the value of an element within a list - Answer: my_list[index number] = x Delete an element from a list - Answer: del my_list[index number] create a copy of a list - Answer: your_list = my_list[:] my_list is the original list Add an item to the end of a list - Answer: d(x) add all items in [x] to a list - Answer: d([x]) insert x into list before position i - Answer: t(i,x) Remove the first item from list with value x - Answer: e(x) Remove and return last item in list - Answer: () Remove and return item at position i in list - Answer: (i) Sort the items of list in place - Answer: () Reverse the elements of list in place - Answer: se() Return index of first item in list with value x - Answer: (x) Count the number of times value x is in list - Answer: (x) Finding an odd number - Answer: i % 2 == 1 enumerate() - Answer: iterates over a list and provides an iteration counter for pos, token in enumerate(tokens): d(int(token)) print('%d: %s' % (pos, token)) pos would be the enumerated value all(list) - Answer: True if every element in list is TRUE (!=0) , or the list is empty print(all([1, 2, 3])) True print(all([0, 1, 2])) False any(list) - Answer: True if any element in the list is True print(any([0, 2])) True print(any([0, 0])) False max(list) - Answer: Get the maximum element in the list print(max([-3, 5, 25])) 25 min(list) - Answer: Get the minimum element in the list print(min([-3, 5, 25]))- 3 sum(list) - Answer: Get the sum of all elements in the list print(sum([-3, 5, 25])) 27 Accessing a nested list - Answer: my_list = [ ['a', 'b'], ['c', 'd'], ['e', 'f'] ] my_list[0] = 'a' 'b' mylist[0][1] = 'b' Iterating a nested loop with multiple rows - Answer: Iterating through multidimensional lists using enumerate() - Answer: slicing - Answer: [1:5} Beginning at index 1 and continuing up to but not including index 5 negative slicing - Answer: [3:-1} start one index position from end of the list and include the three elements prior to it. stride of slice - Answer: [0:5:2] The 2 indicates it has a stride of two which would skip every other element Get a list from starting point to end of list - Answer: my_list[start:end] Get a list from start to end of the list - Answer: my_list[start:] Get a list from the beginning of list to end (minus 1) - Answer: my_list[:end] Get a copy of list - Answer: my_list[:] Modifying a list with loop iteration - Answer: # Change negative values to 0 for pos in range(len(nums)): if nums[pos] 0: nums[pos] = 0 The square brackets must be included in the latter half of the loop. it is best to make a copy of a list if you are deleting items from it with the iteration. This is because as an item is deleted, the remaining elements are indexed to the left which would skip over the next element Copying a list within a for loop - Answer: for item in my_list[:] List comprehensions - Answer: new_list = [expression for name in iterable] expression evaluates each item of the list name provides the variable component to bind iterable is a list or something else to iterate over Always surrounded by brackets Builds and returns a new list object rather than the modification that is available with a for loop list comprehension for converting every element to a string within a list - Answer: my_list = [str(i) for i in my_list] list comprehension for converting user input into a list of integers - Answer: inp = input('Enter numbers:') my_list = [int(i) for i in ()] The split() method converts the input into an iterable list list comprehension to find the sum of each row in a two dimensional list - Answer: my_list = [[5, 10, 15], [2, 3, 16], [100]] sum_list = [sum(row) for row in my_list] list comprehension for finding the sum of the row with the smallest sum in a two dimensional table - Answer: my_list = [[5, 10, 15], [2, 3, 16], [100]] min_row = min([sum(row) for row in my_list]) print(min_row) square root function - Answer: () conditional list comprehensions - Answer: new_list = [expression for name in iterable if condition] in the condition, make sure to use the list comprehension variable name in the condition Create a new sorted list - Answer: sorted_numbers = sorted(numbers) This is different than the .sort() method in that .sort() will sort a list in place without creating a new list Key function with both sorting methods - Answer: Specifies a function to be applied to each element prior to being compared key_sort = sorted(list_name, key=) sorted_list = sorted(my_list, key=max) Reverse sorting a list - Answer: sorted_list = sorted(my_list, reverse=True) Dictionaries - Answer: {'key': 'Value', 'key': 'Value} dict(Bobby='', Johnny='') Container object key-value pairs each key is associated with a value mutable retrieve the value associated with a dictionary key - Answer: my_dict[key] Add an entry into a dictionary or modify the existing entry - Answer: my_dict[key] = value Delete the key entry from a dictionary - Answer: del my_dict[key] Test for existence of key in my_dict - Answer: key in my_dict Remove all items from a dictionary - Answer: my_() Read the value of the key entry from a dictionary and return default if no value exists - Answer: my_(key,default) Merge a dictionary with another dictionary. Dictionary one will have existing entries overwritten if the same keys exist in dictionary two - Answer: my_e(my_dict2) Remove and return the key value from the dictionary. If key deos not exist, then default is returned - Answer: my_(key,default) Iterating over the key and values of a dictionary - Answer: num_calories = dict(Coke=90, Coke_zero=0, Pepsi=94) for soda, calories in num_(): .items() is the keyword that allows for both items to be iterated over iterating over the keys in a dictionary - Answer: num_calories = dict(Coke=90, Coke_zero=0, Pepsi=94) for soda in num_(): .keys() is the keyword that allows for both items to be iterated over iterating over the values in a dictionary - Answer: num_calories = dict(Coke=90, Coke_zero=0, Pepsi=94) for soda in num_s(): .values() is the keyword that allows for both items to be iterated over nested dictionary - Answer: {'D1': {'D2': 'x'}} music = { 'Pink Floyd': { 'The Dark Side of the Moon': { 'songs': [ 'Speak to Me', 'Breathe', 'On the Run'], 'year': 1973, 'platinum': True }, etc.. } Code that potentially may produce an exception should be placed in a - Answer: Try Block except block - Answer: A block of code that is executed if the prior try block causes an exception except block with no type handles any unspecified exception type. Sort of a catch all. an except block can also specify the error type except ValueError: except ZeroDivisionError: etc.. Multiple Exception Handlers - Answer: The addition of more than one except block following a try block to try and handle a wide variety of errors that could occur within a try block AttributeError - Answer: occurs if a function does not exist in an imported module IOError - Answer: A file cannot be opened Raising exceptions - Answer: The introduction of error-checking code Do not introduce if else statements to do this user_input = '' while user_input != 'q': try: weight = ... if weight 0: raise ValueError('Invalid weight.') height = ... if height = 0: raise ValueError('Invalid height.') raise ValueError - Answer: creates a new exception within the try block of code except ValueError as excpt - Answer: creates a new variable except that the exception handling code might inspect for details about the exception instance. Printing the exception prints the string argument passed to the exception when raised. exceptions within functions - Answer: raise Valuerror() can be placed within a function as long as the executed code below the function is placed within a try block execution of the raise statement within the function causes automatic exiting of the function finally - Answer: a clause of a try statement that allows a programmer to specify clean-up actions that are always executed this is always the last code executed before the try block finishes if no exception occurs, then execution continues in the finally clause and then proceeds to the rest of the program Custom exception type - Answer: an exception type that is defined by the programmer outside of the built in exceptions good practice is to include error at the end of the custom name a new class must be defined class LessThanZeroError(Exception): def ____init____(self,value): = value module - Answer: a file containing Python code that can be imported and used by scripts, other modules, or the interactive interpreter filename should end with .py Importing a module - Answer: executing the code contained by the module and making the definitions within the module available for use by the importing program good practice is to place import statements at the top of a file import "filename" without the .py extension The filename is case sensitve overriding the definitions of an imported function - Answer: module_ this is only temporary in your existing script and will not change the imported file permanently built in module - Answer: one that comes pre-installed with python environmental variable - Answer: stored in the computers operating system and can be accessed by every program running on the computer changing PYTHONPATH - Answer: set PYTHONPATH="c:dir1;c:otherdirectory". importing specific names from a module - Answer: from module_name import name1, name2, ... adds only the specified names to the global namespace and not the whole modue __name__ - Answer: is a global string variable automatically added to every module that contains the name of the module checking if a file is the executing script or an imported module - Answer: if __name__ == "__main__" if this is true then the file is being executed as a script otherwise the file was imported and the name is equal to the module name reload - Answer: from imp import reload causes the imported module to reload without this the module is only loaded once so any changes to the module will not be reflected without reloading it package - Answer: a directory that when imported gives access to all of the modules stored in the directory. Large projects will use these directory must include a file called __init_.py __init_.py - Answer: Contains code to initialize a package when imported can often be empty but will still identify the directory as a package open() - Answer: built in function with one argument used for opening files f = open('') This would open a file in the same directory as the executing script full path names can also be specified such as open('C:UsersBWaynetax_') () - Answer: closes a file to where no more reads or writes to the file are allowed () - Answer: returns the file contents as a string my_(500) this would read the first 500 bytes of text ines() - Answer: returns a list of strings where the first element is the contents of the first line, second element is the contents of the second line and so on my_file = open('') lines = my_ines() print (lines[1]) This would print the 2nd line of text ine() - Answer: returns a single line at a time useful with large files where contents may not fit into the available system memory iterating over a file - Answer: f = open('') for line in f: print(line) () () - Answer: used to store data permanently Only accepts a string argument other data types must be first converted into string f = open('', 'w') # Open file ('Example string:n test...') # Write string () # Close the file num1 = 5 num2 = 7.5 num3 = num1 + num2 f = open('', 'w') (str(num1)) (' + ') (str(num2)) (' = ') (str(num3)) () 'r' - Answer: open the file for reading if file is missing then error will occur 'w' - Answer: open the file for writing if file does not exist then the file is created contents of an existing file are overwritted 'a' - Answer: open the file for appending if file does not exist then the file is created writes are added to the end of existing file contents 'r+' - Answer: specifies to handle the file in update mode this allows for both reading and writing of a file at the same time the r is arbitrary, it could be 'w+' or 'a+' as well buffering - Answer: f = open('','w', buffering=100) this will write the output buffer to disk every 100 bytes flush() - Answer: used to flush the output buffer to disk module - Answer: contains many portable functions for handling file paths () - Answer: concatenates the arguments using the correct path separator for the current operating system eliminates the path separators instead of path = "subdirbat_" it should be path = ('subdir', 'bat_') (path) - Answer: splits a path into a 2-tuple (head, tail) where tail is the last token in the path string and head head is everything else ('C:UsersBWayne', '') s(path) - Answer: Returns true if path exists, else returns False e(path) - Answer: Returns True if path is in an existing file, and false if otherwise import os p = ('C:', 'Users', 'BWayne', 'bat_chopper') if e(p): print('Found a file...') else: print('Not a file...') ze(path) - Answer: Returns the size in bytes of the path (The file size) () - Answer: walks a directory tree, visiting each subdirectory in the specified path used to search for specific files within a directory tree where the exact path is unknown and / - Answer: file separators windows will accept either of these bytes() - Answer: used to represent a sequence of single byte values such as binary data These are immutable with statement - Answer: this is considered good practice for opening files to ensure that it is closed when complete can be used to open a file, execute a block of statements, and automatically close the file when complete with open('', 'r') as myfile: r - Answer: used to read an imported csv file can also be used to write if the 'r' is changed to 'w' import csv with open('', 'r') as csvfile: grades_reader = r(csvfile, delimiter=',') row_num = 1 for row in grades_reader: print('Row #%d:' % row_num, row) row_num += 1

Content preview

Python C859 Questions and Complete
Solutions Graded A+
Minimum field width with strings - Answer: print('Student name (%5s)' % 'Bob'

the 5 specifies that there are a minimum of 5 characters and thus the print out would be ( Bob)



Conversion flags - Answer: alter the output of conversion specifiers

%08d adds leading zeros to the minimum width of 8 characters



precision components(Rounding) - Answer: Indicates how many digits to the right of the decimal should
be included

'%.1f' % 1.725 indicates a precision of 1 resulting in 1.7



.replace() - Answer: replace(old,new,count)

count replaces only the first occurrence

count can be left out

translation = translation.replace('one', 'uno')



.find(x) - Answer: Returns the position of the first occurrence of item x in the string

if my_str is 'Boo Hoo!'

my_str.find('!') Returns 7

my-str.find('Boo') Returns 0

my_str.find('oo') returns 1



find(x, start) - Answer: Same as find(x) but begins the search at position start



find(x, start, end) - Answer: Same as find(x,start) but stops the search at position end

,rfind(x) - Answer: Same as find but searches the string in reverse, returning the last occurrence in the
string



count(x) - Answer: Returns the number of times x occurs in the string



using in operator to check if a character or substring is contained in the string - Answer: if 'b' in
my_string



Comparing Strings - Answer: may be compared using relational operators (<> <= etc..)

equality operators (==,!=)

membership operators (in,not in)

identity operators (is, is not)

my_str = 'Hello'

my_str == 'Hello" evaluates to True



relational comparison will compare the ASCII unicode values. if a string is shorter with all the same
characters then the shorter is considered less than



Do not use identity operators where you should be using an equality operator



comparisons are case sensitive



isalnum() - Answer: Returns True if all characters int he string are lowercase or uppercase letters, or the
numbers 0-9



isdigit() - Answer: Returns True if all characters are the numbers 0-9



islower() - Answer: Returns True if all characters are lowercase letters



isupper() - Answer: Returns True if all characters are uppercase letters

, isspace() - Answer: Returns True if all characters are whitespace



startswith(x) - Answer: Returns True if the string starts with x



endswith(x) - Answer: Returns True if the string ends with x



capitalize() - Answer: Returns a copy of the string with the first character capitalized and rest lowercased



lower() - Answer: Returns a copy of the string with all characters lowercased



upper() - Answer: Returns a copy of the string with all characters uppercased



strip() - Answer: Returns a copy of the string with leading and trailing whitespace removed



can be used to turn a string literal into a list of items by using the whitespace character as the default
separator



if it was strip(/) the default separator would be the / character. If the string contained a double // then
an empty list element would be created



title() - Answer: Returns a copy of the string with the first letters of words capitalized



Good practice for input() data transformations - Answer: apply the transformations when reading in
data as opposed to later in the program



join() - Answer: Works in reverse to split()

It joins a list of strings together to create a single string

Document information

Uploaded on
March 26, 2025
Number of pages
20
Written in
2024/2025
Type
Exam (elaborations)
Contains
Questions & answers
$14.99

Wrong document? Swap it for free Within 14 days of purchase and before downloading, you can choose a different document. You can simply spend the amount again.
Written by students who passed
Immediately available after payment
Read online or as PDF

Seller avatar
Reputation scores are based on the amount of documents a seller has sold for a fee and the reviews they have received for those documents. There are three levels: Bronze, Silver and Gold. The better the reputation, the more your can rely on the quality of the sellers work.
YourExamplug
4.1
(74)
Sold
228
Followers
27
Items
18118
Last sold
1 day ago



Why students choose Stuvia

Created by fellow students, verified by reviews

Quality you can trust: written by students who passed their tests and reviewed by others who've used these notes.

Didn't get what you expected? Choose another document

No worries! You can instantly pick a different document that better fits what you're looking for.

Pay as you like, start learning right away

No subscription, no commitments. Pay the way you're used to via credit card and download your PDF document instantly.

Student with book image

“Bought, downloaded, and aced it. It really can be that simple.”

Alisha Student

Working on your references?

Create accurate citations in APA, MLA and Harvard with our free citation generator.

Working on your references?

Frequently asked questions