QUIZ 1 REVIEW, PART 1
WHAT IS COMPUTATION?
¢ Declarative knowledge
statement of fact
¢ Imperative/Procedural knowledge
“how-to” knowledge
Frame your problem so a computer can solve it
EXAMPLE – IMPERATIVE KNOWLEDGE:
¢ Compute the sum of the odd numbers between 1
and N
¢ Initialize a counter variable to zero. For each
number from 1 to N, if the number is not divisible
by two, add the number to the counter.
RULES OF THE LANGUAGE
¢ Syntax – which statements are well-formed
¢ Static Semantics – which statements have
meaning
Static semantic errors happen when you put the right
types of pieces in the right order, but the result has
no meaning
¢ Semantics – association of each syntactically
correct statement that has no semantic errors
with some meaning
VARIABLES
Math Computer Science
¢ Alphabetic character ¢ Alphanumeric,
x, y, z underscores
x, letters_dict
¢ Represents arbitrary ¢ Represents a storage
or unknown number location containing
some value
TYPES
¢ Booleans: True, False
¢ Strings: ‘abc’, ‘123’, ‘!@#$%’
¢ Numbers:
int: -1, 0, 5, 27
float: -5.4, 0.0, 17.9
TYPE ISSUES
¢ 1/2=0 (integer division)
¢ 1 / 2.0 = 0.5 (float division)
¢ float(1) / 2 = 0.5 (casting)
NOTE: integer division truncates the answer – it does NOT round
7.0 / 3 = 2.33333333 7/3=2
7.0 / 4 = 1.75 7/4=1
OPERATIONS
¢ Arithmetic operations (follow PEMDAS rules)
+, -, *, /
** for exponents
% modulo to get remainder
¢ String operations
+ for concatenation
* to repeat
¢ Boolean comparators
>, >=, <, <=, ==, !=
¢ Logical operators
and, or, not
CONTROL: IF
Only run a block of code if a certain condition is True
if condition:
#some code to run
elif other_condition:
#some other code to run instead
else:
#some more code to run if the other conditions
#weren’t met
CONTROL: LOOPS
for while
¢ Repeat this block of ¢ Repeat this block of
code once per element code until a given
in the given iterable condition is False
¢ for var in iterable: ¢ while condition:
#code #code
CONTROL: FOR LOOPS
GUESS/CHECK
I’m thinking of a number between 1 and 100.
BISECTION
0 25 37 50 100
low guess guess high
low high
FUNCTIONS: WHY ARE THEY USEFUL?
¢ Decomposition
word_guessed()
print_guessed()
hangman
play_hangman()
¢ Abstraction
get_frequency_dict(sequence)
input output
sequence freq_dict
FUNCTIONS: FORMAT
parameters/
keyword name arguments
code
return statement (if omitted, function will
return None by default)
word_with_as = add_as(word)