Presentation is loading. Please wait.

Presentation is loading. Please wait.

More Repetition While and For loop variations

Similar presentations


Presentation on theme: "More Repetition While and For loop variations"— Presentation transcript:

1 More Repetition While and For loop variations
Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg

2 Today’s Agenda Going over yesterday’s lab
Exploring looping alternatives

3 Right and Wrong Challenge to new programmer
Isn’t there a right way to do things? Well, there are definitely wrong ways to do things E.g., logic errors, wrong answers, crashes But, there are often many right ways to do something

4 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

5 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?

6 For Loops for varName in iterableDataStructure: (next thing in DataStructure put in varName) suite of code

7 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…

8 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)?

9 Range How many numbers are generated in range(0,8)?
How many numbers are generated in range(x,y)?

10 Range How many numbers are generated in range(0,8)?
How many numbers are generated in range(x,y)? y-x

11 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?

12 Let’s go through an example
Annoying kid in the car (cartrip.py)

13 For loop for counter in range(age): print("Are we there yet?")

14 While loop counting up counter=0 while counter<age: print("Are we there yet?") #counter=counter+1 counter += 1

15 While loop counting down
while age>0: print("Are we there yet?") age -= 1 #But now age is destroyed!


Download ppt "More Repetition While and For loop variations"

Similar presentations


Ads by Google