The structure of a while loop is similar to a for loop but instead of labelling a variable and specifying a numerical range we specify a condition like we did with the if statements. The while loop will keep repeating as long as this condition is true.
again = "yes"
while again == "yes":
print("You are a wonderful human being")
again = input("Would you like to hear that again ? yes/no ")
print("Ok, goodbye")
We have to set our variable up before the while loop so it can do the first loop and get to the input line. We don't need to do this with a for loop as the variable is created in the first line of the for loop. This program will keep printing its message until the user types in something other than yes.
If the variable you are using in the condition doesn't get changed inside the loop somewhere then the program will get stuck inside the loop, repeating for ever. If the condition is true the program goes into the loop then, once the loop is finished it will check again. If the condition can't be changed in the loop it will have to go back in and repeat the loop again, and again, and again...
Now we have a way of making a program that will loop for ever we need a way to stop the loop: Ctrl + C does the trick.
We have another data type in Python called a Boolean. Named after George Boole, a clever bloke who did a lot of work on logic around 1850. Booleans can only be either True or False. This makes them ideal for controlling while loops as the program checks the condition and if it is True it does the loop, if it is False then it skips the loop and carries on with the program. If we set a variable to True then we don't even have to check if the variable == True we can just use the variable label. eg
running = True
while running:
print("This program is running fine")
This program will keep printing its message in the Python shell for ever as we haven't programmed a way for running to become False. This would be better:
running = True
while running:
print("This program is running fine")
again = input("Do you want the program to keep running ? (y/n) ")
if again == "n":
running = False
print("OK, I'll stop then")
This program will keep printing its message until the user enters 'n', then the variable running becomes False so when it gets checked at the start of the next loop it is not True and the loop skips to the print("OK, I'll stop then") line. If anything else is entered by the user - 'yes', 'y' or just pressing the enter key - the variable running doesn't get changed, so when it is checked at the start of the next loop it is still True and the message is printed once more.
While 1 - Basic while loop
While 2 - Boolean variables, True or False