CSCI Fall 2018 Midterm Flashcards
conditional execution
instruction check for certain conditions, and run their accompanying code
repetition
instruction to perform some action repeatedly, usually with some variation
Python interpreter
program that reads and executes python code
> > >
prompt. telling you that interpreter is ready for you to enter code
*
multiply
**
62 = 36
33=27
exponent
ctrl + z
zombies the program. stops it in its track
kill %n
kills the nth job–use carefully
value
one of the basic things a program works with, like a letter or a number. Some
values we have seen so far are 2, 42.0, and ‘Hello, World!’.
type
integers, floating-point numbers, strings
type()
gives you what type of value is inside the parentheses
prompt
Characters displayed by the interpreter to indicate that it is ready to take input
from the user.
interpreter
A program that reads another program and executes it
program
A set of instructions that specifies a computation
Operator
A special symbol that represents a simple computation like addition, multiplication,
or string concatenation.
int
type
integer
whole number
float
type
numbers with fractional parts
string
sequence of charachters
syntax
rules that govern structure of program
assignment statement
creates a new variable and gives it a value:
»> message = ‘And now for something completely different’
»> n = 17
»> pi = 3.141592653589793
Python key words
False class finally is return None continue for lambda try True def from nonlocal while and del global not with as elif if or yield assert else import pass break except in raise
string concatenation
The + operator performs string concatenation, which means it joins the strings by linking them end-to-end. For example: >>> first = 'throat' >>> second = 'warbler' >>> first + second throatwarbler
syntax error
“Syntax” refers to the structure of a program and the rules about that structure.
For example, parentheses have to come in matching pairs, so (1 + 2) is legal,
but 8) is a syntax error.
semantic error
The third type of error is “semantic”, which means related to meaning.
If there is a semantic error in your program, it will run without generating error
messages, but it will not do the right thing. It will do something else. Specifically, it
will do what you told it to do.
runtime error
The second type of error is a runtime error, so called because the error does
not appear until after the program has started running. These errors are also called
exceptions because they usually indicate that something exceptional (and bad) has
happened.
variable
name that refers to a value
assignment
statement that assigns to a variable
keyword
A reserved word that is used to parse a program; you cannot use keywords like
if, def, and while as variable names.
statement
A section of code that represents a command or action. So far, the statements
we have seen are assignments and print statements.
concatenate
: To join two operands end-to-end.
argument
expression in parenthesis of a function call function(argument) print('hello world')
function
It is common to say that a function “takes” an argument and “returns” a result. The result
is also called the return value.
module
a file that contains a collection of related functions.
import some module
to call on a function in amodule
To access
one of the functions, you have to specify the name of the module and the name of the
function, separated by a dot (also known as a period). This format is called dot notation.
»> ratio = signal_power / noise_power
»> decibels = 10 * math.log10(ratio)
»> radians = 0.7
»> height = math.sin(radians)
The first example uses math.log10 to compute a signal-to-noise ratio in decibels (assuming
that signal_power and noise_power are defined). The math module also provides log,
which computes logarithms base e.
function definition
specifies the name of a new function and the sequence of statements that run when the function is called. Here is an example: def print_lyrics(): print("I'm a lumberjack, and I'm okay.") print("I sleep all night and I work all day.")
paramaters
parameter is a variable in a method definition. When a method is called, the arguments are the data you pass into the method’s parameters. Parameter is variable in the declaration of function.
equivalent to argument
local variables
When you create a variable inside a function, it is local, which means that it only exists
inside the function.
function call
statement that runs the functions
void function
always returns ‘none’
dot notation
The syntax for calling a function in another module by specifying the module name followed by a dot (period) and the function name.
docstring
string at the beginning of a function that explains the interface (“doc” is
short for “documentation”)
””” “””
‘for’ statement
The syntax of a for statement is similar to a function definition. It has a header that ends
with a colon and an indented body. The body can contain any number of statements.
A for statement is also called a loop because the flow of execution runs through the body
and then loops back to the top. In this case, it runs the body four times.
encapsulation ** need help
An objects variables should not always be directly accessible.
To prevent accidental change, an objects variables can sometimes only be changed with an objects methods. Those type of variables are private variables.
The methods can ensure the correct values are set. If an incorrect value is set, the method can return an error.
interface
what user deals with.
An interface is “clean” if it allows the
caller to do what they want without dealing with unnecessary details.
refactoring
rearranging a program to improve interfaces and facilitate code re-use
generalization
The process of replacing something unnecessarily specific (like a number)
with something appropriately general (like a variable or parameter).
precondition
A requirement that should be satisfied by the caller before a function starts.
floor division operator
// divides two numbers and rounds down to an integer
modulus operator
%
divides two numbers and returns remainder… often used with //
1) x % 10
2) x % 100
1) finds right most digit of x
2) finds the two right most digits of x
boolean expressions
expression that is either true or false
true and false are bool type objects
relational operators
x == y #x is equal in value to y x != y # x is not equal to y x > y # x is greater than y x < y # x is less than y x >= y # x is greater than or equal to y x <= y # x is less than or equal to y
logical operators
and, or, not
conditional statements
to say to do something only if a condition meets certain criteria
if ____:
do something
if else statements
if x % 2 == 0:
print(‘x is even’)
else:
print(‘x is odd’)
chained conditionals
if elif else
if x < y:
print(‘x is less than y’)
elif x > y:
print(‘x is greater than y’)
else:
print(‘x and y are equal’)
elif is an abbreviation of “else if”. Again, exactly one branch will run. There is no limit on
the number of elif statements. If there is an else clause, it has to be at the end, but there
doesn’t have to be one.
if choice == ‘a’:
draw_a()
elif choice == ‘b’:
draw_b()
elif choice == ‘c’:
draw_c()
Each condition is checked in order. If the first is false, the next is checked, and so on. If one
of them is true, the corresponding branch runs and the statement ends. Even if more than
one condition is true, only the first true branch runs.
nested conditionals
One conditional can also be nested within another. We could have written the example in the previous section like this: if x == y: print('x and y are equal') else: if x < y: print('x is less than y') else: print('x is greater than y')
recursive function
one function calls another, or even calls itself
def countdown(n):
if n <= 0:
print(‘Blastoff!’)
else:
print(n)
countdown(n-1)
If n is 0 or negative, it outputs the word, “Blastoff!” Otherwise, it outputs n and then calls
a function named countdown—itself—passing n-1 as an argument.
fibonacci
After factorial, the most common example of a recursively defined mathematical function
is fibonacci:
fib(0)=0
fib(1) =1
fibonacci(n) = fibonacci(n − 1) + fibonacci(n − 2)
temporary variable
A variable used to store an intermediate value in a complex calculation.
dead code
Part of a program that can never run, often because it appears after a return
statement
reassignment
A new assignment makes an existing variable refer to a new value (and stop referring to the old value). >>> x = 5 >>> x 5 >>> x = 7 >>> x 7
iteration
repetition of an identical or similar task
for loops/ while statements
while statement
More formally, here is the flow of execution for a while statement:
- Determine whether the condition is true or false.
- If false, exit the while statement and continue execution at the next statement.
- If the condition is true, run the body and then go back to step 1.
def countdown(n): while n > 0: print(n) n = n - 1 print('Blastoff!')
index
expression in brackets. indicates which character in the sequence you want. >>> fruit = 'banana' >>> letter = fruit[1] >>> letter 'a'
len
> > > fruit = ‘banana’
len(fruit)
6
slice
A segment of a string is called a slice. Selecting a slice is similar to selecting a character: >>> s = 'Monty Python' >>> s[0:5] 'Monty' >>> s[6:12] 'Python' The slice operator also works on lists: 92 Chapter 10. Lists >>> t = ['a', 'b', 'c', 'd', 'e', 'f'] >>> t[1:3] ['b', 'c'] >>> t[:4] ['a', 'b', 'c', 'd'] >>> t[3:] ['d', 'e', 'f']
immutable
cannot be changed after its created
mutable
a mutable object can be changed after it is created
immutable strings
The reason for the error is that strings are immutable, which means you can’t change an
existing string. The best you can do is create a new string that is a variation on the original:
»> greeting = ‘Hello, world!’
»> new_greeting = ‘J’ + greeting[1:]
»> new_greeting
‘Jello, world!’
This example concatenates a new first letter onto a slice of greeting. It has no effect on the
original string
counting
word = ‘banana’
count = 0
for letter in word:
if letter == ‘a’:
count = count + 1
print(count)
This program demonstrates another pattern of computation called a counter. The variable
count is initialized to 0 and then incremented each time an a is found. When the loop exits,
count contains the result—the total number of a’s.
‘in’ operator
The word in is a boolean operator that takes two strings and returns True if the first appears as a substring in the second: >>> 'a' in 'banana' True >>> 'seed' in 'banana' False
list
a list is a sequence of values. In a string, the values are characters; in a list,
they can be any type. The values in a list are called elements or sometimes items.
The elements
of a list don’t have to be the same type. The following list contains a string, a float, an
integer, and (lo!) another list:
[‘spam’, 2.0, 5, [10, 20]]
nested list
list within another list
mutable lists
Unlike strings, lists are mutable. When the bracket operator appears on the left side of an
assignment, it identifies the element of the list that will be assigned.
»> numbers = [42, 123]
»> numbers[1] = 5
»> numbers
[42, 5]
The one-eth element of numbers, which used to be 123, is now 5.
list operations
The + operator concatenates lists: >>> a = [1, 2, 3] >>> b = [4, 5, 6] >>> c = a + b >>> c [1, 2, 3, 4, 5, 6] The * operator repeats a list a given number of times: >>> [0] * 4 [0, 0, 0, 0] >>> [1, 2, 3] * 3 [1, 2, 3, 1, 2, 3, 1, 2, 3] The first example repeats [0] four times. The second example repeats the list [1, 2, 3] three times.
list.append
append adds a new element to the end of a list: >>> t = ['a', 'b', 'c'] >>> t.append('d') >>> t ['a', 'b', 'c', 'd']
list.extend
extend takes a list as an argument and appends all of the elements: >>> t1 = ['a', 'b', 'c'] >>> t2 = ['d', 'e'] >>> t1.extend(t2) >>> t1 ['a', 'b', 'c', 'd', 'e'] This example leaves t2 unmodified.
list.sort
sort arranges the elements of the list from low to high:
»> t = [‘d’, ‘c’, ‘e’, ‘b’, ‘a’]
»> t.sort()
»> t
[‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
Most list methods are void; they modify the list and return None.
add up everything in a list
To add up all the numbers in a list, you can use a loop like this: def add_all(t): total = 0 for x in t: total += x return total
deleting elements from lists
you can use pop: >>> t = ['a', 'b', 'c'] >>> x = t.pop(1) >>> t ['a', 'c'] >>> x 'b' pop modifies the list and returns the element that was removed. If you don’t provide an index, it deletes and returns the last element. If you don’t need the removed value, you can use the del operator: >>> t = ['a', 'b', 'c'] >>> del t[1] >>> t ['a', 'c'] If you know the element you want to remove (but not the index), you can use remove: >>> t = ['a', 'b', 'c'] >>> t.remove('b') >>> t ['a', 'c'] The return value from remove is None. To remove more than one element, you can use del with a slice index: >>> t = ['a', 'b', 'c', 'd', 'e', 'f'] >>> del t[1:5] >>> t ['a', 'f'] As usual, the slice selects all the elements up to but not including the second index.
convert string to list of characters
> > > s = ‘spam’
t = list(s)
t
[’s’, ‘p’, ‘a’, ‘m’]
Aliasing
If a refers to an object and you assign b = a, then both variables refer to the same object: >>> a = [1, 2, 3] >>> b = a >>> b is a True
An object with more than one reference has more than one name, so we say that the object is aliased.
if the aliased object is mutable, changes named to one will affect the other
editing strings vs lists
Most list methods modify the argument and return None. This is the opposite of the
string methods, which return a new string and leave the original alone.
equivalent vs identical
equivalent: Having the same value.
identical: Being the same object (which implies equivalence).
reference
association between a variable and its value
dictionary
A dictionary is like a list, but more general. In a list, the indices have to be integers; in a dictionary they can be (almost) any type. A dictionary contains a collection of indices, which are called keys, and a collection of values. Each key is associated with a single value. The association of a key and a value is called a key-value pair or sometimes an item. in mathematical language, a dictionary represents a mapping from keys to values, so you can also say that each key “maps to” a value. As an example, we’ll build a dictionary that
maps from English to Spanish words, so the keys and the values are all strings
{ }
> > > eng2sp = dict()
eng2sp
{}
eng2sp = {‘one’: ‘uno’, ‘two’: ‘dos’, ‘three’: ‘tres’}
The squiggly-brackets, {}, represent an empty dictionary. To add items to the dictionary, you can use square brackets:
eng2sp[‘one’] = ‘uno’
This line creates an item that maps from the key ‘one’ to the value ‘uno’. If we print the
dictionary again, we see a key-value pair with a colon between the key and value:
eng2sp
{‘one’: ‘uno’}
dictionary mapping
The order of the key-value pairs might not be the same. If you type the same example
on your computer, you might get a different result. In general, the order of items in a
dictionary is unpredictable.
But that’s not a problem because the elements of a dictionary are never indexed with integer
indices. Instead, you use the keys to look up the corresponding values:
»> eng2sp[‘two’]
‘dos’
The key ‘two’ always maps to the value ‘dos’ so the order of the items doesn’t matter
how to lookup a value in a dictionary
Given a dictionary d and a key k, it is easy to find the corresponding value v = d[k]
tuple
A tuple is a sequence of values. The values can be any type, and they are indexed by
integers, so in that respect tuples are a lot like lists. The important difference is that tuples are immutable.
Syntactically, a tuple is a comma-separated list of values:
»> t = ‘a’, ‘b’, ‘c’, ‘d’, ‘e’
To create a tuple with a single element, you have to include a final comma:
»> t1 = ‘a’,
»> type(t1)
tuples=immutable
But if you try to modify one of the elements of the tuple, you get an error:
»> t[0] = ‘A’
TypeError: object doesn’t support item assignment
Because tuples are immutable, you can’t modify the elements. But you can replace one
tuple with another:
»> t = (‘A’,) + t[1:]
»> t
(‘A’, ‘b’, ‘c’, ‘d’, ‘e’)
This statement makes a new tuple and then makes t refer to it.
list comprehension
def capitalize_all(t):
res = []
for s in t:
res.append(s.capitalize())
return res
We can write this more concisely using a list comprehension:
def capitalize_all(t):
return [s.capitalize() for s in t]
The bracket operators indicate that we are constructing a new list. The expression inside
the brackets specifies the elements of the list, and the for clause indicates what sequence
we are traversing.
Generator expression
Generator expressions are similar to list comprehensions, but with parentheses instead of
square brackets:
»> g = (x**2 for x in range(5))
»> g
at 0x7f4c45a786c0>
The result is a generator object that knows how to iterate through a sequence of values. But
unlike a list comprehension, it does not compute the values all at once; it waits to be asked.
The built-in function next gets the next value from the generator:
»> next(g)
0
»> next(g)
1