< Back

Activity 15

While Conditions
While loops execute until a condition becomes False. This means that you need to write the condition determining when you want to contine the loop. But often when writing code you know the condition for when you want the loop to stop. To solve this conundrum you need to negate the stop condition to produce the continue condition. In this activity you will practice negating conditions to get loops to stop when desired.


For each of the examples below, write the condition that would cause the displayed output.

Sample Program Condition

Stop when x is odd.

Program
x = 28
while(____________________________):
    print(x)
    x = x // 2
print(x)
Output
28
14
7

Stop when x is greater than 21

Program
x = 0
while(____________________________):
    print(x)
    x = 2 x + 1
print(x)
Output
0
1
3
7
15
31

Stops when x is greater than y

Program
x = 1
y = 200
while(____________________________):
    print(x, y)
    x = x * 2
    y = y // 2
print(x, y)
Output
1 200
2 100
4 50
8 25
16 12

Stops when the user inputs a \(-1\).

Program
x = 0
while(____________________________):
    x = int(input())
    print(x)
print(x)
Output
5
2
6
3
2
1
-1

Demorgan's Law

Demorgan's law is probably the most useful law of logic we use in computer science. It allows us to successfully negate our conditions. Demorgan's law states:

$$ \neg (p \wedge q) \equiv (\neg p \vee \neg q)\\ \neg (p \vee q) \equiv (\neg p \wedge \neg q) $$

Use Demorgan's law to negate each of the following conditions. Draw a truth table to verify your negation.

  1. x != 0 and x > y

  2. x > y and y > z

  3. not victory and score > 0

  4. score > 0 or score < 0