Session Ten

advertisement
More Repetition
While and For loop variations
Intro to Computer Science
CS1510, Section 2
Dr. Sarah Diesburg
Today’s Agenda


Going over yesterday’s lab
Exploring looping alternatives
Right and Wrong

Challenge to new programmer


Well, there are definitely wrong ways to do
things


Isn’t there a right way to do things?
E.g., logic errors, wrong answers, crashes
But, there are often many right ways to do
something
3
Rules of Thumb

So far



Have the least amount of indents (nesting) as
possible
Try to have at most two boolean expressions in a
conditional statement
Use meaningful variable names
4
Loops

What are the two ways we can generate
repetition?


while loop and for loop
What is the purpose of a for loop?


Count-controlled loop, which means we will
know in advance how many times the loop will run
Why?
5
For Loops
for varName in iterableDataStructure:
(next thing in DataStructure put in varName)
suite of code
6
For Loops
for varName in iterableDataStructure:
(next thing in DataStructure put in varName)
suite of code

varName is often called an “iterator”

Let’s take a look at quiz.py…
7
Range

3 versions



range(r,s) – means range of r to s-1
range(x) – means range(0,x), which is 0 to (x-1)
range(a,b,c) – like range(a,b), but c is the “step”
value

How about range(3, 10, 2)?
8
Range

How many numbers are generated in
range(0,8)?

How many numbers are generated in
range(1,8)?

How many numbers are generated in
range(x,y)?
9
Range

How many numbers are generated in
range(0,8)?


How many numbers are generated in
range(1,8)?


8-0=8 numbers
8-1=7 numbers
How many numbers are generated in
range(x,y)?

y-x
10
Ranges in For Loops



A range is an iteratable data structure
Why was quiz.py broken?
What are all the ways quiz.py could be fixed?
11
Let’s go through an example

Annoying kid in the car (cartrip.py)
12
For loop
for counter in range(age):
print("Are we there yet?")
13
While loop counting up
counter=0
while counter<age:
print("Are we there yet?")
#counter=counter+1
counter += 1
14
While loop counting down
while age>0:
print("Are we there yet?")
age -= 1
#But now age is destroyed!
15
Download