What comes after ‘for’ loops? ‘While’ loops, yay!

While loops keep repeating until some Boolean condition is met.

The general format is:

while someCondition:
do stuff

Once again, note the colon, then the tab in the next line

  1. Type and run

desiredFloor=10
currentFloor=2

while currentFloor!=desiredFloor:
print(“Keep going up!”)
currentFloor = currentFloor+1

print(“You have reached the %dth Floor! The lift is opening.” %desiredFloor)

  1. We could also do some basic number sequences like the previous day

Type and run:
num = 200
while num>195:
print(num)
num = num-1

  1. Change the code above so that it also prints 195. Do not change any numbers, just change the Boolean operator.
  2. What if you forget to write num = num-1 in the code of 2? Num will always be 200, and thus always be greater than 195. And it will be a dreaded infinite loop!

No worries – you can stop an infinite loop on Jupyter Notebook by clicking Kernel –>Interrupt. Then restart the Kernel.

Kernel is a small piece of code that runs at the backend when you run your code. Sometimes when the kernel dies for reasons such as some large code or an internet disruption – your code starts being weird and doesn’t run. In such cases, it is good to restart the kernel. Restarting the kernel is often the brute force way to fix things. Think of it as the equivalent of hitting an old-style TV until it starts showing clearer images (you are too young for this reference, perhaps 😛 )

Take a deep breath and try the infinite loop! Then stop it by interrupting and restarting the kernel.

  1. Infinite loops are often unintended ( although there are some good ways to use them – we will learn later ). Consider the same code as #2. Suppose you have written everything correctly but made the tiny little mistake of typing a plus sign instead of a minus sign when updating the num value.

Run it. It will give you an infinite loop of course. Scroll down and try to catch up to the end of the printed list – as soon as you reach the end, you will see numbers are being generated and printed continuously and you have to keep scrolling down to stay at the end.

Kill it.

  1. Ok, one more. This time we make an infinite loop using a simple Boolean.

Type and run

while True:
print(‘Kurosaki-kun!’)

There are smarter ways to kill this, by using an if condition and something called ‘break’ but we will learn that next time. For the time being just do the Kernel thing.

  1. Exercise

Write a code that will give you the following output when run. Utilize a while loop.

10!
9!
8!
7!
6!
5!
4!
3!
2!
1!
Blast off!