Reading Questions
Quiz
While Loop
Another name is conditional loop, a loop that runs while a condition is true
i = 0 while i < 10: print(i) i = i + 1
- Loop will run while x is less than 10
What happens if we get the condition wrong?
i = 0 while i > 10: print(i) i = i + 1
- The loop won’t run because 0 is not greater than 10
What if we get the change in x wrong?
i = 0 while i < 10: print(i) i = i - 1
- Inifinte loop, hold control and press c to kill in Idle
- Any for loop can be written as a while loop
The above loop as a for loop is
for i in range(10): print(i)
- Which is much more concise with fewer opportunities for errors
- So why use a while loop?
- Because not all while loops can be written as a for loop
- For loops are for when you know the number of times the loop will run
Sometimes you have inputs, user or function parameters that will make predicting the number of iteration impossible
user_input = input('> ') while user_input != 'bye': print(user_input) user_input = input('> ')
- Note, there are two prompts because we need user for the first while test
Could get around this by reordering the loop body
user_input = '' while user_input != 'bye': user_input = input('> ') print(user_input)
Negation
- It’s also worth emphasizing that the loop condition is true if it should continue to run
- But when writing loops you often think in terms of when you want the loop to stop
- In that case, just negate the stopping condition
- Want to stop when
user_input == 'bye'
, so the stopping condition isuser_input != 'bye'
- To negate any comparison use this table:
a == b | a != b |
a != b | a == b |
a < b | a >= b |
a > b | a <= b |
a <= b | a > b |
a >= b | a < b |
- To negate a logical expression use DeMorgan’s Law:
p and q | not p or not q |
p or q | not p and not q |