









Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!










What is a Python 3 program? - Answers - A Python 3 program is a file that only contains text that conforms to the syntax of the Python 3 programming language How is a Python 3 file created and edited? - Answers - Using a text editor, which is distinct from - and usually far less complex than - a word processing program like word. It is most common to use a text editor that includes features friendly to Python programming. These features might include:
Colourizing code to highlight certain common features of it;
Allowing for quick execution of a program using a "run" button;
Allowing the capture for analysis of any output from the program;
Debugging tools helpful for locating and fixing errors in programs; Integrated development environments (IDEs) - Answers - An IDE is a program that embodies some or all the features described on the previous slide and perhaps many more. An IDE called IDLE comes with downloads of Python 3. It's meant for beginners, and is usually not used by experience Python programmers, but it's free and readily available. Data vs code - Answers - We tend to think of code as being the unchanging part of a program that consists mostly of instructions that implement some algorithm, and data as the information those instructions act on. Data types - Answers - numbers, strings and booleans Numbers - Answers - Python's interpreter categorizes a number as either an int (integers, that is positive or negative whole numbers) or a float (positive or negative numbers that may contain a fractional portion) The way Python stores its floats means that they are usually just approximations of actual values. This is because the number of bits used for storing a number is fixed, so the number of available float values is finite, and values are stored internally in binary. Python places no arbitrary length on the number if digits used in its integers. Strings - Answers - Strings appear in Python programs as collections of zero or more characters surrounded by either single quotes or double quotes. A surprisingly useful entity in programming is the empty string, " ", that is, the string containing no characters, said to have a length of 0. Triple-quoted docstrings can be used for multi-line text, through using another escape code, \n, can also let you build a regular string that, when displayed, shows up on more than one line in the screen. There's a variety of text in Python 3 called an f-string that comes in handy when displaying various types of data. You can recognize them in code by a lower or uppercase letter "f" that precedes their opening quotation mark. f"Today is {day_name}."
Booleans - Answers - An expression that evaluates to True or False Variables - Answers - Variables in Python must be named as follows:
The name must start with a letter or an underscore
The rest of the name may contain letters, the numerals o through 9, or underscores, but no spaces.
Camel case
Snake case Assignment - Answers - When we give a value to a variable in the way, we are performing what's called an assignment. In Python, the equals sign, =, is used as the assignment operator. (count = 0) The value of one variable can be copied to another in an assignment. The creation of a new variable is called a declaration, and giving a variable its first value is often called initialization. Declaration and initialization always occurs in the same step in Python 3. Expressions - Answers - An expression is anything that is a literal, or a variable or has some computable value. In an assignment statement, the part on the right of the assignment operator is an expression. Expressions are frequently formed using data operands joined by operators. Arithmetic operators - Answers - + addition
The .append() method is used to add an element to the end of a list. It's common to initialize a list variable to its empty state, [], then to use .append() to build its content as required by the program. The .insert() method is used to insert an element at a specified position in a list. my_garden.insert(1, "tomatoes"). Other list methods are:
.remove()
.clear()
.index() Deletions from lists - Answers - The easiest way to remove an element from a list is by using the del statement. del my_list[2] Dictionaries - Answers - my_dict = {"name": "Alice", "birth_year": 2005}. The string literals before the colons (:) are called keys and the data items are called values. To retrieve a particular item in a dict we can use keys inside square brackets, they can also be used to change a value in a dict. Two frequently used dictionary methods allow the casting of all of a dictionary's keys and all its values into lists. my_dict.keys(), my_dict.values(). The keys in a dictionary are usually string literals, they can be of any data type. Keys are immutable, so once declared, they can't be altered, unlike their associated values. Keys can, however, be removed entirely, along with their associated value. Deleting from dictionaries - Answers - Removing a key:value pair from a dict is easily achieved using the del statement. Nesting dictionaries and lists - Answers - Dictionaries can contain dictionaries, dictionaries can contain lists, lists can contain lists, and lists can contain dictionaries. Nesting these structures too deeply within one another can cause a programmer headaches trying to figure out how to get at the data through layers, but it is possible and sometimes necessary for, say, storing complicated data in disk files. Multidimensional lists - Answers - A list that contains another list is a multidimensional list. a = [[10, 7, 18], [5, 2, - 6], [0, 12, - 14], [1, - 4, 13]] Tuples - Answers - Series of 0 or more values of any type separated by commas in round brackets. When creating a tuple with a single element, the programmer must include a comma after the element's value, (3,). As with lists and strings, the elements of a tuple may be referenced using a 0-based index in square brackets. my_fruit = ("cherry", "red", 1.05). Also, as with lists and strings, the len() function can be applied to tuples to determine the number of elements they contain. Like the characters in a string, the elements of a tuple are immutable.
There is no .append(0 method for tuples that would allow extending them, but tuples can be concatenated together with the plus sign to form new tuples. Unlike list elements, the elements of tuples cannot be deleted. Although tuples may seem a bit useless because of the restrictions places on them, the values of variables. Input and Output (I/O) - Answers - keyboard input - > processing - > screen output. Input - Answers - To get input from the keyboard, we use the input() function. name = input('What is your name? '). The input() always returns a str to a program. To get around this problem is to use a cast, that is, a conversion to type int on whatever the user types yob = int(input('What is your year of birth? ')) Arguments - Answers - The input function takes a single argument, that being the message displayed to the user. Other functions may take no arguments, more than one argument, or even a varying number of arguments. Arguments of types int, float, bool, str, and tuple cannot have their values changed by the workings of a function. The function just receives copies of their values to work with. Arguments of type list and dict may well have the values of their various elements changed by a function. Output - Answers - By default, the print() function completes its output with a newline ("\n"), causing the next call to print() to start its output line lower in the output window. However, print() has an optional, specialized end argument that can change the ending of its output to anything you might want to end a line with, or even nothing at all Slicing - Answers - alphabet = 'abcdefghijklmnopqrstuvwxyz' elemenopee = alphabet[11:16] print (elemenopee) The output from this is lmnop s = "abcde" print (s[2:]) # prints cde (from s[2] on) print (s[:2]) # prints ab (up to s[2-1]) Slicing a string doesn't affect the string being sliced; rather, it creates a new string Slicing a list does not affect the list being sliced; it creates a new list. It lets you copy one list into another list quickly and easily. Conditional Statements - Answers - The if statement evaluates an expression of type bool, and, if that expression is True, proceeds to execute a collection - or block - of one or more program statements. name = input("What is your name? ") if name == "Richard": print ("We have the same name!") Loops - Answers - A block of code that may execute 0 or more times.
f.write("Hello, world!\n") f.write("It's a nice day.\n") f.write("We should be outside.\n") The open () function causes a file, the name of which is given as open()'s first argument, to be made ready for input or output. mode is an optional parameter of the open() function. Its value tells the interpreter what sort of file operations to expect, "w", short for "write", indicates that the file should be open for output, that is, so that text can be added to the file. A mode of "r", short for "read", indicates that an existing file should be opened for input. "a", short for "append", indicates that an existing file should be opened to have content added what's already there. If the mode argument is left out, a read operation is assumed. The encoding optional parameter lets the programmer adjust the way text is represented in the opened file. A value of "utf-8" is recommended, though it is not the default. The as keyword is part of the syntax for with and precedes a variable name chosen by the programmer, f in this example. From this point forward, f refers to the open file. The colon is required. After this line, all statements using file object f must be indented. File input & output methods - Answers - The .write() method requires a string argument, and it is this string that is written into the open file. The .read() method is used to return a copy of all of the characters from a text file in a single string. You can use .read() to get a list of strings from a text file, but further processing is required. Exceptions - Answers - A situation that can cause a program to start acting erratically, or to crash entirely. Any time you feel that some code you are writing might cause an exception, you can place that code in a try block and put some recovery code in an except. If the whole thing is inside a loop, as in the previous example, you can keep the program running until whatever cause the exception to occur stops happening. ile_lines = [] try: with open("test.txt", encoding="utf-8") as f: line = f.readline()[:-1] while (line != ""): file_lines.append(line) line = f.readline()[:-1] print(file_lines) except: print("The file could not be opened.") Exception handling may also involve the presence of a finally block. So, what is program design? - Answers - A procedural decomposition is the breaking down of a large, broadly defined programming task into successively smaller, more
narrowly defined tasks. It is done is order to reduce the large task to a set of trivial tasks. How is it done? - Answers - The starting state for a procedural decomposition is a broad and abstract statement of the goal of an as-yet-unwritten software system. It says, briefly, what the system is expected to do once its completed. Following some analysis, a splitting of the broad task into a set of sub-tasks is made. These sub-tasks are also likely to be abstract, that is, they will lack detail and not be immediately implementable in code. Do it again, and keep doing it - Answers - Each of the newly identified subtasks is analyzed, and then decomposed into a new set of subtasks. These new subtasks are also likely to be abstract, but less so; that is, they will be a step closer to the stage at which a short coded solution - no more than a few program statements - become obvious. This pattern of analysis and decomposition continues until all subtasks can be readily coded into actual software. It's an example of a recursive process. Using function headers in refinement - Answers - These function prototypes could be written function headers, complete with parameters, and descriptive docstrings stating what the functions are meant to do. Though functions prototypes don't contain the code those functions will eventually need to do their work, they will provide guidance for the programmers completing those functions. They will also serve as documentation for designers working on other parts of a project. With a function prototype in hand, these other designers can proceed with their work as if the function already exists. How does this relate to algorithms? - Answers - An algorithm is a complete description of a process or processes that achieve a task or a set of tasks in finite time. Program design, then, may be seen as the development of an algorithm into a form suitable for implementation on a computer system. The foregoing implies that, as a designer, you won't be able to achieve a solid program design if you don't have a grasp of the underlying algorithm. Language-agnostic design? - Answers - A programmer should approach a procedural decomposition without consideration of the programming language or languages likely to be used at the end of the process. The designer should be able to hand off their design to a programmer or team of programmers without even knowing which language or languages they are to use in its implementation. Modular design - Answers - Module means "one of a set of separate parts that, when combined, form a complete whole."
Modularity and the distribution of tasks - Answers - For these medium-to-large systems, modularity also affords the benefit of allowing distribution of programming tasks among various independent programmers or programming teams. Waterfall Model - Answers - Requirements - Answers - The requirements for a software project are likely to identify:
System requirements, which are descriptions of the hardware needed to support the
eventual software.
Software requirements, which are specifications of what the completed software is supposed to do, as determined by consultation with the client paying for the software. The end product of the requirements process is a product requirements document (PRD). The PRD will have a lot to say about what's expected out of the finished software, but little or nothing to say about how any of it is to be accomplished. Design - Answers - The structure of a software system - one that would address all requirements laid out in the PRD - is established. Concepts used in the design process are likely to include:
Stepwise refinement
Modularity, that is, the organization of modules into a coherent program structure.
Data structure, that is, a description of the forms data will take and how data items will relate to one another.
Information hiding, implying tight control over data sharing among modules. Some considerations for a designer:
Each aspect of a design should be traceable to a requirement in the PRD, recognizing that some aspect of the design may meet more than one requirement.
If some existing aspect of a design can be used to meet more than one requirement in the PRD, then let it, rather than wasting additional development time and money.
A design is not code. It lays out a path for programmers but omits most of all small implementation details. Designs usually need not even take into account what programming language or languages are likely to be used in the project. A software architecture document is the end product of the design process. Development - Answers - This is the phase in which code is produced. For modular designs, this may be the phase at which unit testing takes place, that is, programmers will be doing testing on their functions and modules as they are created. This is also the phase where the modules are brought together, or integrated, into a working program. Those working on this phase are likely to include programmers and interface designers. In addition to code, the phase is also important for the delivery of user documentation. Testing - Answers - Testing is typically done by a quality assurance (QA) team. Tests are likely to be both functional and non-functional. Bugs and usability problems, as they are discovered, will be referred to the developers for fixing,
Deployment - Answers - This is the phase in which the program is released to the client or to the public. Note that there may have been limited releases of the program prior to deployment, either through interaction with the client during development and testing or perhaps through a "beta release" program. Maintenance - Answers - Bugs will elude the development and testing phases, so post- deployment maintenance will involve a cycle of bug reports - many from users - fixes for those bugs by developers, and the deployment of those fixes. Code that has been deployed to correct bugs of any kind in a program - and in our networked world these may well be security flaws - is called a patch, no doubt because a software fix is analogous to a fabric patch sewn onto a garment to cover a hole. Waterfall models - strengths - Answers - The work done in the early phases of the waterfall model may expose weaknesses in the requirements specification that are best addressed before any coding or deployment takes place. The process itself imposes a structure on development and thus makes measuring the progress of software projects easier. The structure may also suggest control mechanisms for projects. The emphasis on documentation in the waterfall model - particularly in the first two phases - mean that any new development team members can be brought up to date on a project by simply reading the documentation. Waterfall Models - Weaknesses - Answers - It's hard to reverse the "waterfall", and this makes the model inflexible. If, for example, the testing phase uncovers an fundamental flaw in the design, much work that has already been considered complete may have to be discarded with potentially devastating effects on the whole project. Feedback from users comes late in the process - too late for changes to the requirements and design - though this problem may be mitigated by opening up the early phases of waterfall to more input from eventual users. Agile Software Development - four values for software developers - Answers - 1. People and communication between people are more important than processes or tools.
overflow: the condition that exists when a push is attempted on a stack that has already filled all the memory space available to it. Queues: Some definitions - Answers - A queue, first in first out (FIFO) stack, is a mutable data structure consisting of a collection of elements that has (at minimum two operations defined for it: enqueue and dequeue. The word queue is used because the structure represents, conceptually, a queue of people waiting their turn at something. enqueue: appends an element to the back end of a queue. dequeue: fetches the value of the least recently enqueued element and removes that element from the queue. front: fetches the value of the least recently enqueued element. It's like dequeued but doesn't remove the element. is_empty: this operation on a queue is the same as is_empty for a stack. size: also identical to the same-named operation for a stack. Queues errors - Answers - underflow and overflow Applications of Stacks - Answers - Allowing functions to work. The evaluation of arithmetic expressions. Allowing "undo" and "redo" operations in apps. Allowing "Back" buttons to work in browsers. Allowing "recent" lists, like the call histories on phones. Applications of queues - Answers - Queuing documents for output to a printer. Queuing keystrokes waiting ti be processed by an app. Processing orders sent from the front counter in a fast-food restaurant to the people preparing the meals in the kitchen. Orderly delivery of messages in a messaging system. Testing - Answers - Proving that programs, even very small programs, do what they're intended to do is very hard, so developers rely instead on testing. Testing can also be hard and very few programs can be tested thoroughly on all conceivable input. Specification-based testing uses the specification of the program as the point of reference for the test data selection and accuracy. The name special variable is of type string. Its value is changed by the Python interpreter depending on the context in which it is used. By placing all the test code in this if statement, we ensure that it only runs when the fubar.py module is being executed directly because that's the only situation in which the module's special name variable will have the value"main" Tracing - Answers - To trace a program's execution is to examine how the execution of each of its statements affects the overall state of the program.
Debugging - Answers - The print()statements can show the programmer the content of specific variables at one point in the program's execution, and an empty input() statement placed immediately after the print() can then cause the running program to pause while the programmer considers the output to troubleshoot for errors. A debugger is a program that executes other programs in a highly controlled environment to facilitate the detection and correction of errors. All the tools I'll describe here are features of a typical debugger. Watches. A watch is a tool that allows a programmer to keep track of the value of specific variables during a program's execution in a debugger. Breakpoints. Setting a breakpoint on a specific statement in a program being debugged allows the programmer to have execution stop when it reaches that statement. Step. This tool will cause a program to execute one statement at a time in the debugger, pausing after each to allow the programmer to check the program's progress. Linear search - Answers - Linear search processes lists (or arrays in other programming languages) in sequence with the goal of locating the position in that list of a specific value; for example, discovering the index of the first 7 in this list to be 3: 11 43 25 7 17 32 9 7 5 29 def search(haystack, needle): """Return the position of value needle in list haystack, or return None if value needle is not in haystack.""" for i in range(len(haystack)): if haystack[i] == needle: return i def main(): a = [11, 43, 25, 7, 17, 32, 9, 7, 5, 29] for val in [7, 14]: pos = search(a, val) if pos is None: print(f"{val} not found.") else: print(f"{val} found at position {pos}.") if name == "main": main() 7 found at position 3. 14 not found. Binary search - Answers - It's called that because "binary" (from the Late Latin bini) implies two and every step of a binary search is a dividing of what still needs to be searched by two. haystack = [11, 15, 17, 22, 25, 27, 29, 32, 35,43] needle = 47f ound = False lower = 0
sorted sub-list of its elements at its left end, and this sub-list will have grown in length by one.'a''b''c' 'g''e''d''f 'sorted sub-list after three passes through the outer loop. The inner loop is where the search in the as-yet-unsorted(right) end of the list for its smallest value takes place.• Once the smallest (minimum) value in the unsorted part of the list is found, it is swapped with the first (left-most) value in the unsorted part, thus growing the sorted portion by one element. def selection_sort(a): """Sorts list a in ascending order by value.""" n = len(a) i = 0 while i < n-1: m = i j = i + 1 while j < n: if a[j] < a[m]: m = j j += 1 if m != i: a[i], a[m] = a[m], a[i] # swap i += 1