Lec2 Branch Loops PDF
Lec2 Branch Loops PDF
Lec2 Branch Loops PDF
BRANCHING,
ITERATION
6.00.1X LECTURE 1
Variables are names that we had to which we could associate values
VARIABLES (REVISITED)
name
◦ descriptive
◦ meaningful
◦ helps you re-read code
◦ cannot be keywords
value
-Value could be any legal expression
◦ information stored We could also update a value associated with a name
◦ can be updated
6.00.1X LECTURE 2
VARIABLE BINDING WITH =
compute the right hand side VALUE
store it (aka bind it) in the left hand side VARIABLE
left hand side will be replaced with new value
= is called assignment
x = 2
x = x*x
y = x+1
6.00.1X LECTURE 3
We need to be careful of the order in which things are done
BINDING EXAMPLE
swap variables swap variables
– is this ok? – this is ok!
x = 1 x = 1
y = 2 y = 2
y = x temp = y
x = y y = x
- In the 1st example, what if we wanted to Swap the Values? The 1st example wouldx = temp
not work.
- The 2 will be replaced by 1, so when the expression x = y is computed, it will return 1
- This does not swap the values, but rather the 2 is replaced by 1.
- 2nd example:
-Need to temporarily assign value to y to the variable y so you can overwrite the value of y
6.00.1X LECTURE 4
6.00.1X LECTURE 5
TYPES
variables and expressions
◦ int
◦ float
◦ bool
◦ string -- NEW
◦ … and others we will see later
6.00.1X LECTURE 6
STRINGS
letters, special characters, spaces, digits
enclose in quotation marks or single quotes
hi = "hello there”
greetings = ‘hello’
concatenate strings
name = "eric"
greet = hi + name
greeting = hi + " " + name
- Double quotes are good because when you want to use single quotes in a sentence, it doesn't get confused as the end of a quote
- Just as we can add numbers together, strings have a way for you to add together as well.
-If you apply an addition to strings, it means we "overloaded" it.
6.00.1X LECTURE 7
OPERATIONS ON STRINGS
‘ab’+ ‘cd’ concatenation
3* ‘eric’ successive concatenation
len(‘eric’) the length
‘eric’[1] indexing - Begins with index 0
- Attempting to index beyond
length – 1 is an error
6.00.1X LECTURE 10
- By default, the text that you put will return a string type value.
- Therefore, if you want to get a number in, you need to CAST it
- Otherwise, it will interpret it as a string of the characters of the number
- So you will need to turn it into an int before actually using it
INPUT/OUTPUT: input("")
prints whatever is within the quotes
user types in something and hits enter
returns entered sequence
can bind that value to a variable so can reference
text = input("Type anything... ")
print(5*text)
6.00.1X LECTURE 11
6.00.1X LECTURE 12
- IDE's are painful if we want to run things multiple times.
- Therefore, better to have a text editor where you can enter, edit, and save things
IDE’s
painful to just type things into a shell
better to have a text editor – integrated development
environment (IDE)
◦ IDLE or Anaconda are examples
comes with
◦ Text editor – use to enter, edit and save your programs
◦ Shell – place in which to interact with and run your
programs; standard methods to evaluate your programs
from the editor or from stored files
◦ Integrated debugger (we’ll use later)
- Let's you have an easier way to edit code before you run them.
-Gives you an easy place for you to save your code and evaluate them later.
6.00.1X LECTURE 13
6.00.1X LECTURE 14
6.00.1X LECTURE 15
BRANCHING PROGRAMS
(REVISITED)
The simplest branching statement
is a conditional
◦ A test (expression that evaluates to
True or False)
◦ A block of code to execute if the
test is True
◦ An optional block of code to
execute if the test is False
- Branching Program is something where you have a condition where you test
- If test returns boolean True
-Then it has a block of code you will run
- IF False
-Then something else you will run
6.00.1X LECTURE 16
COMPARISON OPERATORS ON
int and float
i and j are any variable names
i>j
i>=j
i<j
i<=j
i==j equality test, True if i equals j
i!=j inequality test, True if i not equal to j
6.00.1X LECTURE 17
LOGIC OPERATORS ON bools
a and b are any variable names
not a True if a is False
False if a is True
a and b True if both are True
a or b True if either or both are True
6.00.1X LECTURE 18
CONTROL FLOW - BRANCHING
if <condition>: if <condition>:
<expression> <expression>
<expression> <expression>
... ...
elif <condition>:
if <condition>: <expression>
<expression> <expression>
<expression> ...
... else:
else: <expression>
<expression> <expression>
<expression> ...
...
6.00.1X LECTURE 19
USING CONTROL IN LOOPS
simple branching programs just make choices, but
path through code is still linear
sometimes want to reuse parts of the code
indeterminate number of times
Sometimes we may want to do something over and over again, how do we do that?
6.00.1X LECTURE 20
You are in the Lost Forest. You are playing a
************ video game, and are
************
lost in some woods
************
************ If you keep going
Go left or right? right, takes you back
to this same screen,
stuck in a loop
if <exit right>:
<set background to woods_background> - We want the video game to be
in an infinite loop. The code
if <exit right>: above has a huge simple of IF's
<set background to woods_background>
if <exit right>: - If we want to do this 1000
times, we don't want to write the
<set background to woods_background> IF statement 1000 times
and so on and on and on... We can do this with a WHILE
else: loop
<set background to exit_background>
else:
<set background to exit_background>
else:
<set background to exit_background>
6.00.1X LECTURE 21
You are in the Lost Forest. You are playing a
************ video game, and are
************
lost in some woods
************
************ If you keep going
Go left or right? right, takes you back
to this same screen,
stuck in a loop
This says while you keep going right, it will keep looping until you do something else
6.00.1X LECTURE 22
CONTROL FLOW:
while LOOPS
while <condition>:
<expression>
<expression>
...
<condition> evaluates to a Boolean
if <condition> is True, do all the steps inside the
while code block
check <condition> again
repeat until <condition> is False
6.00.1X LECTURE 23
while LOOP EXAMPLE
You are in the Lost Forest.
************
************
************
************
Go left or right?
As long as N == 'Right', it will keep prompting you until you print "left"
6.00.1X LECTURE 24
CONTROL FLOW:
while and for LOOPS
# more complicated with while loop
n = 0
while n < 5:
print(n)
n = n+1
6.00.1X LECTURE 25
CONTROL FLOW: for LOOPS
for <variable> in range(<some_num>):
<expression>
<expression>
...
range(start,stop,step)
default values are start = 0 and step = 1 and is optional
loop until value is stop - 1
Give a range of numbers from 7 up to but not including 10
mysum = 0
for i in range(7, 10):
mysum += i
print(mysum)
6.00.1X LECTURE 27
What if you want to stop a loop?
break STATEMENT
immediately exits whatever loop it is in
skips remaining expressions in code block
exits only innermost loop
while <condition_1>:
while <condition_2>:
<expression_a> - Break will stop the execution of that loop at that point or
code
break - Break will give you a natural way to control where you are
inside the loop
<expression_b>
<expression_c>
6.00.1X LECTURE 28
break STATEMENT
mysum = 0
for i in range(5, 11, 2):
mysum += i
if mysum == 5:
break
print(mysum)
6.00.1X LECTURE 29
for VS while LOOPS
for loops while loops
know number of unbounded number of
iterations iterations
can end early via can end early via break
break can use a counter but
must initialize before loop
uses a counter and increment it inside loop
can rewrite a for loop may not be able to
using a while loop rewrite a while loop using
a for loop
- In most codes, we tend to use For Loops when we know what we're going to do as a computation
- We'll use While Loops when there's going to be a condition that we can't predict that's going to allow us to break out of that loop
- Both gives us the first version of iterative algorithms
6.00.1X LECTURE 30
Key Learnings: the order of operations will matter.
6.00.1X LECTURE 31
ITERATION
Concept of iteration let’s us extend
simple branching algorithms to be able to
write programs of arbitrary complexity
◦ Start with a test
◦ If evaluates to True, then execute loop
body once, and go back to reevaluate the
test
◦ Repeat until test evaluates to False,
after which code following iteration
statement is executed
Whereas, Branching Programs only go through the code once.
6.00.1X LECTURE 32
AN EXAMPLE
x = 3
ans = 0
itersLeft = x
while (itersLeft != 0):
ans = ans + x
itersLeft = itersLeft – 1
print(str(x) + '*' + str(x) + ' = ' + str(ans))
6.00.1X LECTURE 33
STEPPING THROUGH CODE
x = 3
ans = 0 x ans itersLeft
itersLeft = x 3 0 3
3 2
while (itersLeft != 0):
6 1
ans = ans + x
9 0
itersLeft = itersLeft – 1
print(str(x) + '*' + str(x) + ' = ' + str(ans))
6.00.1X LECTURE 35
6.00.1X LECTURE 36
CLASSES OF ALGORITHMS
Iterative algorithms allow us to do more complex
things than simple arithmetic
We can repeat a sequence of steps multiple times
based on some decision; leads to new classes of
algorithms
One useful example are “guess and check” methods
- Since we can repeat a sequence of steps, one good use of it is the "guess and check" methods
- Very useful, although might not be most efficient
6.00.1X LECTURE 37
GUESS AND CHECK
Remember our “declarative” definition of square root
of x
If we could guess possible values for square root (call
it g), then can use definition to check if g*g = x
We just need a good way to generate guesses
6.00.1X LECTURE 38
FINDING CUBE ROOT OF
INTEGER
One way to use this idea of generating guesses in
order to find a cube root of x is to first try 0**3, then
1**3, then 2**3, and so on
Can stop when reach k such that k**3 > x
Only a finite number of cases to try
This would only work for integers. But in this case, only a finite number of cases to try
6.00.1X LECTURE 39
SOME CODE
x = int(input('Enter an integer: '))
- Remember, Input returns something in a String, so need to
ans = 0 convert to integer
- Loop by first setting the answer = 0
- Then, as long as I have something less than something
while ans**3 < x: I'm trying to find the cube of
- Keep incrementing by 1
ans = ans + 1 - It's simply using a loop to generate guesses
- It will keep doing that until it gets to something that's
either the right thing, or if it has gone too far
if ans**3 != x: - The test is ans**3 != x
6.00.1X LECTURE 40
EXTENDING SCOPE
Only works for positive integers
Easy to fix by keeping track of sign, looking for solution
to positive case
However, this only works for positive integers. To fix that, use the code below.
6.00.1X LECTURE 41
SOME CODE
x = int(input('Enter an integer: '))
ans = 0
while ans**3 < abs(x):
ans = ans + 1
if ans**3 != abs(x):
print(str(x) + ' is not a perfect cube')
else:
if x < 0:
ans = - ans
print('Cube root of ' + str(x) + ' is ' + str(ans))
- This can be done using the abs function to take the absolute function.
- Shows you can easily extend the code to build new version of things you didn't consider in first version of code
6.00.1X LECTURE 42
LOOP CHARACTERISTICS
Need a loop variable
◦ Initialized outside loop
◦ Changes within loop
◦ Test for termination depends on variable
Useful to think about a decrementing function
◦ Maps set of program variables into an integer
◦ When loop is entered, value is non-negative
◦ When value is <= 0, loop terminates, and
◦ Value is decreased every time through loop
Here we can use abs(x) – ans**3
- How do you know when loop is going to stop?
- That's when you would need a decrementing function
- The value would keep decreasing and the loop would terminate when it gets to 0
- In this case, you can use abs (x) - ans **3 as the decrementing function
6.00.1X LECTURE 43
WHAT IF MISS A CONDITION?
Suppose we don’t initialize the variable?
◦ Likely get a NameError; or worse use an expected value to
initiate the computation
Suppose we don’t change the variable inside the loop?
◦ Will end up in an infinite loop, never reaching the
terminating condition
- If you don't initialize the variable --> NameError
- If you used loop variable somewhere else before this, you might get an unexpected value in the computation
- Make sure initialize variable before you start it.
- If you don't change variable inside the loop --> will end up in an infinite loop
- In a while loop in particular, need to make sure to change the variable
6.00.1X LECTURE 44
GUESS-AND-CHECK
you are able to guess a value for solution
you are able to check if the solution is correct
keep guessing until find solution or guessed all values
the process is exhaustive enumeration
Exhaustive because you are going to exhaust all possible options and it will take a long time to run
6.00.1X LECTURE 45
CLEANER GUESS-AND-CHECK
– cube root
cube = 8
for guess in range(cube+1):
if guess**3 == cube:
print("Cube root of ", cube, ” is ", guess)
6.00.1X LECTURE 46
CLEANER GUESS-AND-CHECK
– cube root
cube = 8
- In this code, if you get to a place where you've gone too far,
for guess in range(abs(cube)+1): just break out of the loop
- Otherwise, run through the loop
if guess**3 >= abs(cube): - When you run the code, you shouldn't just run it on things
you're expecting
break - You should add in other checks incase the code
results in things you're not expecting
if guess**3 != abs(cube):
print(cube, ’is not a perfect cube’)
else:
if cube < 0:
guess = -guess
print('Cube root of ' + str(cube) + ' is ' + str(guess))
6.00.1X LECTURE 47
EXHAUSTIVE ENUMERATION
Guess and check methods can work on problems with
a finite number of possibilities
Exhaustive enumeration is a good way to generate
guesses in an organized manner
6.00.1X LECTURE 48