Outline for April 17, 2014
Reading
:
text
, § 5, 7
Due
: April 17, 2014
Why you don’t count with floating point numbers [
roundoff.py
]
Simultaneous assignment [
swap.py
]
Simple assignment:
variable = expression
Simultaneous assignment:
variableA, variableB = expressionA, expressionB
Decision structures
If statement [
if0.py
]
Executes once, based on condition
Syntax
Conditions
Resolves to boolean value
Literal booleans:
True
(1),
False
(0)
Relational operators
Use two arithmetic expressions connected with relational operatorsto create a boolean
Relational operators:
>
,
>=
,
<
,
<=
,
==
, \lstinline/!=/
Precedence: resolved after arithmetic operators
Connectives:
and
,
or
,
not
6 > 2 + 3
;
"UCD" == "Sac State"
Two-way decisions [
if1.py
]
if-else statements
One condition, two possible code blocks
else very powerful when the positive condition is easy to describe but not the negative
Multi-way decisions [
if2.py
]
Can execute code based on several conditions
elif
(
else if
)
else only reached if all previous conditions false
Nested if statements
Indefinite loops: execute until a general condition is false (
while
)
while
[
while.py
]
Contrast with
for
break
causes program to fall out of loop (works with
for
too) [
loop1.py
]
continue
causes program to start loop over immediately (works with
for
too) [
loop1.py
]
Definite loops: execute a specific (definite) number of times (
for
)
General form:
for i in
iterator
Iterator
is either list or something that generates a list
Very common form:
for i in range(1, 10)
range()
in detail [
for.py
]
range(10)
gives 0 1 2 3 4 5 6 7 8 9
range(3, 10)
gives 3 4 5 6 7 8 9
range(2, 10, 3)
gives 2 5 8
range(10, 2, -3)
gives 10 7 4
Program: counting to 10 [
toten.py
]
Program: sum the first 10 squares [
sumsq.py
]
You can also obtain a PDF version of this.
Version of April 16, 2014 at 10:59PM