# 1 Chapter 4 The while loop and boolean operators Samuel Marateck ©2010

• View
213

0

Embed Size (px)

### Text of 1 Chapter 4 The while loop and boolean operators Samuel Marateck ©2010

• Slide 1

1 Chapter 4 The while loop and boolean operators Samuel Marateck 2010 Slide 2 2 Boolean operators are used in boolean expressions and operate on other boolean expressions. They are the and, or and not. For instance: X>3 and y3 or y3 and y 7 So for instance in: x>3 and y3 is True and y 8 However, in: x>3 or y3 is True and y 10 In not x > 3 what is the expression the not immediately precedes? Slide 11 11 In not x > 3 the not immediately precedes the variable x which is not a boolean expression. What happens and how do you correct this? Slide 12 12 It causes a compilation error. You write it as: not (x > 3) If the value of x is 3, what is the value of the entire expression? Slide 13 13 not (x > 3) If the value of x is 3, what is the value of the entire expression? Since x > 3 is false, not (x > 3) is true. Slide 14 14 The while loop The while loop differs from the for loop in that the variables in the while statement must be defined before the loop. Slide 15 15 So in: while x < 3: the value of x must be defined before the loop this is called priming the while --and execution of the loop will continue while the value of x < 3 is true. Here is an example: Slide 16 16 x = 0 while x < 3: print(x) Since the value of x < 3 is true initially, the loop begins execution. The indented statements that follow the while are said to be in the scope of the while. How many times will the loop be executed? Slide 17 17 x = 0 while x < 3: print(x) How many times will the loop be executed? An infinite number of times. Slide 18 18 So unless a statement in the scope of the while statement changes the boolean expression in the while, execution of the while continues. x = 0 while x < 3: print(x). Slide 19 19 So we can write, for instance, x = 0 while x < 3: print(x) x = x + 1. Slide 20 20 Now the scope of the while, x = 0 while x < 3: print(x) x = x + 1 is. print(x) x = x + 1 Slide 21 21 Since x changes, the loop will only be executed a finite number of times. x = 0 while x < 3: print(x) x = x + 1 How many times will it be executed? Slide 22 22 The loop, x = 0 while x < 3: print(x) x = x + 1 will be executed three times. What is its output? Slide 23 23 The output of x = 0 while x < 3: print(x) x = x + 1 Is 0, 1 and 2. Slide 24 24 One of the purposes of the while is to insure integrity of the input. In the following, the required input is between 0 and 9 Inclusively. So the while continues until the input is between 0 and 9. Slide 25 25 invalid = True #primes the while while invalid : #continues if invalid is True n = input('type your number please \n') if 0

Recommended

Documents
Documents
Documents
Documents
Documents
Documents
Documents
Documents
Documents
Documents
Technology
Education