Presentation is loading. Please wait.

Presentation is loading. Please wait.

Loops CMSC 201. Overview Today we will learn about: Looping Structures While loops For Loops.

Similar presentations


Presentation on theme: "Loops CMSC 201. Overview Today we will learn about: Looping Structures While loops For Loops."— Presentation transcript:

1 Loops CMSC 201

2 Overview Today we will learn about: Looping Structures While loops For Loops

3 Looping Loops let us do something until a boolean condition is met. The simplest loop is called a while loop.

4 The while loop The syntax for a while loop is as follows: line-1 while someCondition: line-2 line-3 line-4

5 The while loop line-1 while someCondition: line-2 line-3 line-4 line-1 Condition is true line-2 line-3 Condition is false line-4 Condition is false Condition is true

6 Example a = 5 while a > 0: print(a) a = a – 1 Prints 5 4 3 2 1

7 Notes If the condition is false to begin with, the loop never executes! a = 4 b = 5 while a == b: print(“Hello”) print(“Goodbye”) This will only print goodbye.

8 Notes It is very important that the variable in the condition be altered at some point during the loop. a = 5 while a > 0: print(a) This is called an infinite loop, since a will always be greater than zero.

9 Example Computing factorial with a while loop. findFac = input(“Please enter a number”) currentTotal = 1 while findFac> 0: currentTotal = currentTotal * findFac findFac = findFac – 1 print(findFac)

10 Example Let’s examine this: findFac = input(“Please enter a number”) currentTotal = 1 while findFac> 0: currentTotal = currentTotal * findFac findFac = findFac – 1 print(findFac) The things in blue are our loop variables. These keep track of where we are and what we need to be doing.

11 Let’s examine this: findFac = input(“Please enter a number”) currentTotal = 1 while findFac> 0: currentTotal = currentTotal * findFac findFac = findFac – 1 print(findFac) currentTotal stores our information, making sure we remember what our current working total is. Example

12 Exercise Use a while loop to print out every number between 0 and 100 that is divisible by three.

13 Loops + If Statements Now that you know how to use loops, if statements, and variables, you can create fairly complicated algorithms. However, figuring out how to combine them can be difficult! In the next few homeworks and exercises, you will start needing to figure out when to use each tool you’ve been given so far. These are the basic elements of programming!

14 Nested Loops We can put loops in our loops. This is called nested loops. The first loop is the outer loop, and the second one is the inner loop. The inner loop can be executed many times. What does this loop print? a = 0 b = 0 while a < 4: while b < 4: print(b) b = b + 1 a = a + 1 b = 0


Download ppt "Loops CMSC 201. Overview Today we will learn about: Looping Structures While loops For Loops."

Similar presentations


Ads by Google