0% found this document useful (0 votes)
158 views16 pages

Python Midterm Exam Study Guide

The CS 112 Midterm Exam Review Guide outlines the key topics and concepts covered throughout the semester, emphasizing the importance of understanding programming through practice rather than rote memorization. The exam will consist of a mix of multiple-choice and coding questions, focusing on definitions, code comprehension, and practical coding skills. Preparation strategies include reviewing lectures, zyBooks, and lab tasks, as well as practicing coding examples discussed in class.

Uploaded by

prestonnguyen244
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
158 views16 pages

Python Midterm Exam Study Guide

The CS 112 Midterm Exam Review Guide outlines the key topics and concepts covered throughout the semester, emphasizing the importance of understanding programming through practice rather than rote memorization. The exam will consist of a mix of multiple-choice and coding questions, focusing on definitions, code comprehension, and practical coding skills. Preparation strategies include reviewing lectures, zyBooks, and lab tasks, as well as practicing coding examples discussed in class.

Uploaded by

prestonnguyen244
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Midterm Exam Review Guide CS 112

This is a somewhat overly detailed description of the different things we've learned and explored this
semester. If you'd prefer a shorter laundry-list of topics, just read the section headers to get an idea of what
topics we'll cover; the extra detail is to give more information when you want it, but we're not saying you're
supposed to be memorizing this document at all! It's about performing programming, not rote memorization.
The tests will spend some time testing your knowledge of definitions and terminology, but will primarily be
interested in your ability to either look at code samples and show understanding of what happens, or to
write small code samples that achieve a simple effect. The test will be 70%/30% split between multiple-
choice questions and applied coding questions. The multiple-choice portion will be some theory/concepts
but will also attempt to test concepts by asking questions such as "which option matches the correct output
of the following code?", or "what is the output of running the following code?".

How to prepare:
• Lectures, zyBook, PAs, Lab tasks are excellent for preparation.
• You should also spend some time looking through the examples we’ve been modifying in class.
• If you only read the text and try to memorize stuff from slides, you will definitely not be prepared for
this test: practice writing programs, practice coding! That's a major focus; this simply isn't a
memorization test.
Python Interpreter
• "chat window" between you and Python
o type python (PC) or python3 (mac) at a terminal/command window.
o the >>> symbol means Python is ready for you to type expressions and commands.
• give it work and it does it for you.
o expressions: interpreter reduces to value, reports back (by representing the value on the next
line)
o statements: does the command, is then ready for more
• contrast with module/source mode, where Python simply executes all the lines in a file and then can
quit immediately (never offering the >>> prompt for us to type in extra values—the program does
exactly what the lines of code state, and no more)
• type python sourcefile.py (or python3 sourcefile.py for macs) at terminal/command window.
o Python opens the file, executes all the code in it, and once it finishes, Python quits.

Numbers
• Python uses plain old decimal numbers (base 10). These are called ints.
• we also can approximate real numbers (numbers with a part after the decimal point). These are
called floats.
• difference between integers (ints) and reals (floats): understand when python tries to use one versus
the other.

Expressions
• representations of values. E.g.:
• 3+4 "hi" True 2+(3*int(input("num plz:")))
o can then be 'reduced' down to some value (7 in the first example above).
• expressions can include lots of things that we can reduce to a value: function calls, operators, sub-
expressions, variables, literal values, etc.
• some math operators: + - * / // % **
+EX: example usage of each in chart.
o Precedence: Python obeys PEMDAS. There are many other operators that also have related
precedences, so that we can skip some parentheses if we also remember the order of
precedence. When in doubt, add enough parentheses to be sure what happens first.
+ EX: precedence chart.
+ EX: large expression; show each step of evaluation.
+ EX: use Python's precedence to evaluate some mathematical expressions.
• variables: variables are names that refer to spots in memory. When we see a variable in an
expression, Python looks up its current value in memory and 'reduces' the variable to its current
value.
+ EX: >>>x=5 # let's create the variable first, so we can use it soon.
→ Assignment statement. If the variable x didn't already exist, python obtains a spot in
memory for x to refer to. Python stores the value 5 at that memory location.
>>> x+4
→ Expression. Python looks up x, finds out that its value is 5, and then simplifies the
expression down to 5+4.
→ Python continues, reducing 5+4 to 9. Since Python is done with reducing the expression,
and we're in interactive mode, it prints 9 back to us so we can see the result.
• function calls: lets us use code written elsewhere by others (and later ourselves)
o We must always have the trailing open/close parentheses, even when there are no
arguments.
o just like math expressions, they are 'simplified': simplify any argument expressions to values,
then run the code in the function, resulting in a value (returning with a value).
Variables / Assignment
• when we want to store values for later.
o don't have to write a single, large, complex expression
• by giving a new name and ASSIGNING a value to it, Python takes care of choosing a spot in memory,
storing the value, and recalling the correct value for us when we ask for it later on.
• assigning a value to a variable:
variableName = expression
o get the value of the expression on the right, and store it into the variable named variableName.
o read it as "assign the value of this expression to the variable named 'variableName'".
+ EX: assign some values; then use them in an expression.
o can ONLY have a memory location (like a variable name) on the left of =; and can have any
expression on the right-hand side.
+ EX: some valid and illegal assignment statements
o = is not like in math! Not a statement of equality, but a command to assign a value to memory.
+ EX: x = x+1 is valid code. It increments x (x now stores a number one greater than before).
• TIME flows ever forward--all we ever know about a variable is its *current* value. We can update
(replace) its value with another assignment statement.
+ EX: x=5; y=10; print(x); print(y); x=y+3; print(x); print(y);
• Create a variable by assigning to a variable the first time
• Programming TRAP: if you misspell a variable name when assigning to it, Python treats this as a new
variable creation, and happily/obediently creates the quite-similarly-named variable. Your code will look
right but perform oddly until you notice the typo!
• "Augmented" Assignment: +=, -=, *=, etc.
o x += expr means x = x + (expr)
o note the parentheses in the expanded version!

Identifiers
• the names we create and use in Python. Used for variables, function names, modules
• Rules: start with a letter or underscore. Can continue indefinitely with any letters, digits, or underscores.
• keywords are identifiers that already have meaning in Python; we can't re-use them for our own
identifiers.
+EX: chart of Python keywords.
• Built-in stuff: Python already has lots of functions and things defined--each has its own identifier.
o e.g.: input(), int(), str()...
o you can actually redefine these identifiers. But it's a bad idea to reuse these names
• user-defined: as you create your own variables, you are creating new (user-defined) identifiers.
• convention: (a great idea, but Python doesn't enforce this)
o use identifiers that are descriptive or meaningful for their usage.
+ EX: current_age instead of a
o this helps make your code 'self-documenting'.
+ EX: self-documenting code example. (gallons-to-mpg)
+ EX: lots of identifiers; which ones are valid and well-named? Which are valid, but poorly
chosen? Which ones aren't even allowed by Python?
• case (upper/lower) is significant.
+ EX: all these identifiers are different/distinct: myvar MyVar myVar my_var myVar1 MyVaR
Statements
• a command for Python to do something.
• different than an expression. While Python will reduce expressions down to values for us, an
expression doesn't say what to do with it. (In the interactive interpreter, Python assumes we want to see
the results so expressions' values are printed for us. This is a special case).
• Assignment (e.g., x = 2 + 3) is a statement: "reduce this expression on the righthand side to a value,
and STORE IT to the variable with this name on the lefthand side."
• compound statements: grouping multiple statements into one unit. Used in functions and control
structures when we create an indented block of code.
o control-flow statements are compound.

Input/Output
• let’s code be more general
o simplest input: ask user to type input
+ EX: input(..) function in Python gets a string from user.
+ EX: int(input(..)) gets an integer from the user
o output: printing things to the screen
always prints characters, including the 'characters' 0-9, punctuation, newlines ("\n"),
etc.
representing a string is different than printing a string!

Writing Nice Code


• comments: anything following a hash # until the end of that line of text is ignored by Python.
o you can explain in English what the nearby code is trying to do.
o multiline comments: a triple-quoted string expression (not part of a statement) will be ignored by
Python, like a comment. (Actually creates a docstring; prefer writing many #-comment lines.)
• good (descriptive) identifier names: helps self-document your code.
• breaking up long lines of code:
o can't just put part of a statement on next line: Python will assume the lines are separate
statements.
o If one line of code is really long, consider using multiple assignment statements to get the job
done.
o If a line of code must contain enough stuff that it gets long, you can end the line with a backslash
\ to indicate the statement continues on the following line as well.
+ EX: example of building up a long string.

Errors
• when we ask Python to do something that doesn't make sense somehow, we get an error.
• syntax errors: like spelling errors, missing operators (for example, *). Python couldn't even figure out
what we were trying to say.
+ EX: 2(3+4) should have been 2*(3+4)
+ EX: (1+2) * (3+4)-5) has unbalanced parentheses. Should have been (1+2) * ((3+4)-5)
• run-time errors: Python understood what we asked it to do, but it turned out that it couldn't do it.
+ EX: dividing by zero
+ EX: int("eh, steve!") we expected numerical characters instead of "eh, steve!".
Python couldn't get us a number.
• logic errors: The code we wrote is valid/legal, but doesn't do what we intended.
+ EX: inches = feet * 10 Even though this is valid code, we meant 12 instead of 10.
Algorithms and Flowcharts
• algorithm: approach to a task/problem
o the idea or concept behind solving the task/problem
o can be recorded different ways--written English, flow chart, code, pseudocode, pictures...
• flow chart: a drawing with boxes (actions), diamonds (branching questions), and arrows. Represents
algorithm.
o Branches translate to selection statements(if-elif-else). Cycles translate to loops (for, while).
o suggestion: draw a flowchart first to solve a problem, then translate it to code
• what's the difference?
→ An algorithm is the idea, while flow charts are a means of writing out an algorithm.
o so algorithms are often written/recorded by flow charts.

Booleans
• the bool type is just the set {True,False}.
• Boolean operators: and, or, not.
• Can write Boolean expressions with relational operators: < > <= >= == (which is not the same as the
single =), != (the "not-equal-to" check)
+ EX: relational operator examples. Parentheses recommended.
• can use variables to store Booleans – very useful at times

Program Flow
• sequential: lines of code are executed in order, top-down. "waterfall" style.
o This is the default, and is implicit (happens because multiple code lines at same indentation).
• selection statements: Boolean values are evaluated, and different blocks of code run based on whether
the value was True or False.
o we use if, elif, and else blocks to create the branches and conditions.
+ EX: show an if-else example's code, run it with different inputs to reach each branch.
• repetition: the same block of code is run over and over, either a set number of times, or until some
condition is met.
o Definite loop: use for loops to do task a set number of times (or for each element in a sequence).
o Indefinite loop: use while loops to check a condition between each iteration, and as long as the
condition is true each time, we execute the body of the loop again.
+ EX: show a while-loop example's code and run it.
"What's the Password?"
"enter an even number."
"keep dividing a number by 2 until the remainder is zero. ('How odd is this number?')"
Control Structures: CONDITIONALs (Selection/Decision/Branching)
• let us write code that does different things when given different inputs.
• different, meaning "different lines of code" and not just like evaluating a mathematical expression with
different inputs. That would be the same expression or code being executed.
+ EX: show flowchart with conditionals (diamonds).
• IF: contains a Boolean expression and an indented body of code.
o syntax: if bool ean Exp ress io n :
indented St at em en ts
areThe Body
o semantics:
evaluate the Boolean expression. if it's True, execute the body of indented code and then
continue. If it's False, SKIP the body of code and continue.
→ decision whether or not to run a block of code.
• IF-ELSE:
o syntax:
if booleanExpression:
indentedCode
runWhenBooleanExprWasTrue
else:
secondCodeBlock
whichIsRunWhenBooleanExprWasFalse
o semantics: given a boolean expression and TWO blocks of code, if the Boolean expression is
True execute the first block. If it is False, execute the second block.
→ decision which block of code to run.
o notice that exactly one of the two blocks will run.

• IF-ELIF(-ELSE):
o syntax: • semantics: the block of code with the first True
if boolExpr1: Boolean expression is run, and all the others
block1 are skipped (both False ones before and any
elif boolExpr2:
block2
blocks after this True Boolean's block).
elif boolExpr3: o exactly one else block is allowed at the
block3 end; if present, and ALL boolean
... expressions in if- and elif- blocks were
elif boolExprN: False, this block will run. If there is no
blockN
else:
else block, then (just like a simple if-
blockElse statement) when all boolean
expressions are False, none of the code
(the last two lines-- else: blockElse--are blocks will execute.
optional). • the else block is known as the 'default' block.
+ EX: Branching Summary table 3.2.

Sequences: Brief Intro (to be often used with for-loops)


• sequences are anything Python knows how to think of as an ordered set of values.
o we already know strings are sequences of characters.
o we can generate lists of numbers with the range(..) function. range(start,stop,step). First
value (leftmost in resulting list) will be the start value; we add more values by adding step
each time. As soon as we reach or surpass the stop value, we are done. The stop value is
not included in the resulting list.
+ EX: range(10) == range(0,10,1) → [0,1,2,3,4,5,6,7,8,9]. Note: has10 elements,
0-9
+ EX: range(3,7)== range(3, 7,1) → [3,4,5,6]. Again, note stop value (7) isn't in the
list!
+ EX: range(0, 50, 10) → [0,10,20,30,40]. Step (10) is the increment
value.
Control Structures: REPETITIONs
• let us write a block of code that will be repeated multiple times, based on some condition (a
Boolean expression that is evaluated each time).
• some repetition structures are executed a specific number of times (definite loops).
• some repetition structure are executed indefinitely, as many times as the condition is True
(indefinite loops).
• "iteration": one single execution of the loop's body. A loop usually performs multiple iterations.
• WHILE:
o syntax: w h ile b oo lExp r:
bo d y O f W h ile L o o p
o semantics: given a Boolean expression and a body, Python checks the Boolean
expression. If it was True, Python executes the body and then comes back to check the
Boolean expression again. Each time the condition is True, we run the body again. The
first time that the Boolean expression is False, Python is done executing the while-loop,
skips to after the entire while-structure, and continues with the code after it.
it's possible that the body runs zero times, if the Boolean expression is False the first
time.
so we'd better be sure that the body of the loop actually has code that could make
the condition False eventually! (If not, the loop is 'infinite').
→ We want our "sentinel" variable to be modified.
Interactive mode: CTRL-C tells Python to stop executing the code, and return control
to you with a new >>> prompt.
file interpretation mode: CTRL-C forces Python to quit when we get stuck in a loop.
• in Windows cmd: you might need to use CTRL-Z.

• FOR-Loop:
o syntax: fo r varN am e in so m e Seq u en ce:
bo d y O f F o rStmt
o semantics: given a sequence of values and a name to use for each value, run the body of
code where that variable name holds one specific value from the sequence. Do this for
each item in the sequence.
o to run the body of code a set number of times, use range(#) to say how many times to
evaluate the body.
+EX: for i in range(10): sum=0
print(i) for val in [10,5,3,2]:
sum += val
o we can use our loop variable (called i, in the above code) to know which time is currently
running
+ EX: print something 10 times
+ EX: calculate something by inspecting each value in the sequence, like sum in the 2nd
example.
+ EX: print the numbers 1-1000 NOT on separate lines (use an 'accumulator' string
variable)

• special control flow in repetition blocks


o continue statement: tells Python to stop going through the current loop iteration, and start
the next iteration (checking the condition on a while loop, getting the next item in the
sequence for a for-loop).
o break statement: tells Python to immediately stop going through the current iteration, as
well as to just exit the whole loop once and for all. (doesn't check while loop's conditional,
doesn't go back for more elements in for-loop).
o both continue and break are associated with the closest-nested while or for loop.
o they almost always show up inside some conditional block (if/elif/else).
It's kindof pointless to 'always' have it in a loop, because otherwise we'd never reach
code after it in the loop (continue), and we'd never reach a second iteration (break).

Sequence Operations (i.e., things you can do to lists, strings, and other (ordered) sequences of values.)
indexing:
o zero-based indexing: from left to right, spots are numbered 0,1,2,3,4…
o negative indexing: from right to left, spots are also numbered -1, -2, -3, -4, …
o +EX: >>> tup = (5,2,True,"hello world", 7,9)
>>> tup[-1]
9
>>> tup[2]
True
>>> tup[-3]
"hello world"
o index position must exist, or else it's an error.
• slicing: xs[ starting_index : stopping_index : step_amount ]
o allows us to grab a sub-sequence. We give start:stop:step values, much like the range
function's arguments.
o grabs a 'slice' of the sequence, resulting in a new sequence of the same type (tuple, string,
list, etc).
even if the length of a slice is one or zero, the type is preserved
o include starting index, increment by step_amount, until you reach/pass the
stopping_index. (Don't include stopping_index in result, just like the range function).
default step_amount is 1, default starting_index is 0. (just like range())
EX: xs = [2,4,6,8,10,12,14,16,18,20]
xs[1:6:2] == [4,8,12]
step_amount can be negative
• Only way for slice to go right-to-left. (neg. starts/stops alone aren't sufficient)
o if start/stop/step request more than tuple contains, we just get back the portion that did
exist -- it's not an error.
o you can indicate "from beginning" and "to end" by omitting either start or stop index:
o xs[:5] ==> from beginning up to but not including index 5. Same as xs[0:5]
o xs[2:] ==> from index 2 to very end of sequence Same as
xs[2:len(xs)]
o xs[:] ==> from beginning to end Same as
xs[0:len(xs)]
o xs[∷-1] ==> generates a reversed copy of the list! same as xs[len(xs):-
(len(xs)+1):-1]
slice syntax as lefthand side of assignment:
• replace those spots in slice with given new sequence (without
changing id).
• only possible for mutable values (lists)
• this is an *update* of the sequence, not a re-assignment.
entire slice on righthand side of assignment:
• generate a *copy* of the entire sequence.
you can perform slices/indexes one after another to 'reach' deeper into some
data structure:
xs = [0,5,12,[0,1,2,3,4,(2,5,"hello there", True),6,7], 45, 4, 2]
# notice the stop value isn't included:
xs[3][3:6] == [3,4,(2,5,"hello there", True)]
xs[3][5][2] == "hello there"
xs[3][3:6][2][2] == "hello there"
# slices can occur one-after-another! This one's kind of ridiculous.
xs[3][:][3:6][1:][1][:][2][:] == "hello there"
# h is at index 7 in the string, so don't include following e.
xs[3][3:6][2][2][1:8:2] == "el h"
• "set membership": val in seq
• "set non-membership": val not in seq

• + (concatenation)
o note: creates a (shallow) copy from the original sequences.
• * (multiplication). Concatenate that many copies. Just like mathematical multiplication: x*3 =
x+x+x.
o 4 * ('a','b','c') == ('a','b','c','a','b','c','a','b','c','a','b','c')
• len: how many elements in the tuple? Not the same as 'what is the last valid index?' (len is one
greater in answer than "what's the last valid index?").
o EX: len ( [0,2,4,6,8]) == 5
• min / max (only use with all elements the same type, such as all numbers)

Lists

• complex data type (has sub-components; can be any python value)


• sequence (sub-values are ordered; can index/slice)
• mutable (CAN be modified after creation)
• declaration: square brackets [ ] with commas between values.
o empty list: [ ]
o length-one list: [val]
o many vals: [a,b,c,d,e,etc]
• Note: [ ] isn't equivalent to [ [ ] ]. (similar to how 3 != "3", 3!= [3], etc.)
o [] is the empty list. [[]] is the list with one element, where the one element is the empty list.
• LOOPS
- you can use a list directly in a for-loop, getting the list's values in order for your loop-variable:
+ EX: xs = [1,1,2,3,5,8,13]
fibonacci_sum = 0
for val in xs:
fibonacci_sum += val # or some other val usage

• more flexibility: use range() function to grab the indexes in your preferred order:
+ EX: for i in range(len(xs)):
print ( xs[i] )

• Mutable Sequence Operations: lists are mutable, so we can perform these operations on lists.
o index assignment: replaces the single element at indicated index with value that is
assigned.
EX : xs[3] = x + 32
o slice assignment: replaces indicated slice with the list value that is assigned.
EX: xs[1:10:2] = [2,4,6,8,5]
can 'slice' everything: xs[:].
replacement slice doesn't have to have the same length, bigger or smaller also work
• (except when step!=1, then lengths must match).
del: removes the specified spots from the list.
• del xs[i] removes position i
• del[i:j] or del[i:j:k] removes all positions that slice describes
methods: append, extend, count, index, insert, pop, remove, reverse, sort
→ be comfortable with append/extend, index, pop, sort.
Tuples

• complex data type (has sub-components which can be any python value)
• sequence (sub-values are ordered; we can index/slice)
• immutable (cannot be modified after creation)
• declaration: use commas (parentheses alone are not enough!)
+ EX: one-tuple: (val,) or val,
+ EX: triple: (a,b,c) or a,b,c

• LOOPS and tuples


o you can use a tuple directly in a for-loop, getting the tuple's values for your loop-variable:
+ EX:
tups = [(1,2,3),(4,5,6),(7,8,9)]
for (a,b,c) in tups:
print (a+b/c) # or some other usage of a,b,c

o more flexibility: use range() function to grab the indexes in your preferred order
+ EX: for i in range(len(tup)-1, -1, -1): # access in reverse order
print (tup[i])

Usage: Tuples vs. Lists


• lists:
o generally homogeneous (all values in it are the same type)
o used for mutability, tend to update or modify frequently.
• tuples:
o immutable, so length also can't change.
o tend to be heterogeneous (values in it are not the same type)
o good for grouping values together: returning values, getting many values from user, etc.

You might also like